0.8.5.24:
[sbcl.git] / src / compiler / meta-vmdef.lisp
1 ;;;; This file contains the implementation-independent facilities used
2 ;;;; for defining the compiler's interface to the VM in a given
3 ;;;; implementation that are needed at meta-compile time. They are
4 ;;;; separated out from vmdef.lisp so that they can be compiled and
5 ;;;; loaded without trashing the running compiler.
6 ;;;;
7 ;;;; FIXME: The "trashing the running [CMU CL] compiler" motivation no
8 ;;;; longer makes sense in SBCL, since we can cross-compile cleanly.
9
10 ;;;; This software is part of the SBCL system. See the README file for
11 ;;;; more information.
12 ;;;;
13 ;;;; This software is derived from the CMU CL system, which was
14 ;;;; written at Carnegie Mellon University and released into the
15 ;;;; public domain. The software is in the public domain and is
16 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
17 ;;;; files for more information.
18
19 (in-package "SB!C")
20 \f
21 ;;;; storage class and storage base definition
22
23 ;;; Define a storage base having the specified NAME. KIND may be :FINITE,
24 ;;; :UNBOUNDED or :NON-PACKED. The following keywords are legal:
25 ;;;    :SIZE specifies the number of locations in a :FINITE SB or
26 ;;;          the initial size of an :UNBOUNDED SB.
27 ;;;
28 ;;; We enter the basic structure at meta-compile time, and then fill
29 ;;; in the missing slots at load time.
30 (defmacro define-storage-base (name kind &key size)
31
32   (declare (type symbol name))
33   (declare (type (member :finite :unbounded :non-packed) kind))
34
35   ;; SIZE is either mandatory or forbidden.
36   (ecase kind
37     (:non-packed
38      (when size
39        (error "A size specification is meaningless in a ~S SB." kind)))
40     ((:finite :unbounded)
41      (unless size (error "Size is not specified in a ~S SB." kind))
42      (aver (typep size 'unsigned-byte))))
43
44   (let ((res (if (eq kind :non-packed)
45                  (make-sb :name name :kind kind)
46                  (make-finite-sb :name name :kind kind :size size))))
47     `(progn
48        (eval-when (:compile-toplevel :load-toplevel :execute)
49          (/show0 "about to SETF GETHASH META-SB-NAMES in DEFINE-STORAGE-BASE")
50          (setf (gethash ',name *backend-meta-sb-names*)
51                ',res))
52        (/show0 "about to SETF GETHASH SB-NAMES in DEFINE-STORAGE-BASE")
53        ,(if (eq kind :non-packed)
54             `(setf (gethash ',name *backend-sb-names*)
55                    (copy-sb ',res))
56             `(let ((res (copy-finite-sb ',res)))
57                (/show0 "not :NON-PACKED, i.e. hairy case")
58                (setf (finite-sb-always-live res)
59                      (make-array ',size
60                                  :initial-element
61                                  #-(or sb-xc sb-xc-host) #*
62                                  ;; The cross-compiler isn't very good
63                                  ;; at dumping specialized arrays; we
64                                  ;; work around that by postponing
65                                  ;; generation of the specialized
66                                  ;; array 'til runtime.
67                                  #+(or sb-xc sb-xc-host)
68                                  (make-array 0 :element-type 'bit)))
69                (/show0 "doing second SETF")
70                (setf (finite-sb-conflicts res)
71                      (make-array ',size :initial-element '#()))
72                (/show0 "doing third SETF")
73                (setf (finite-sb-live-tns res)
74                      (make-array ',size :initial-element nil))
75                (/show0 "doing fourth and final SETF")
76                (setf (gethash ',name *backend-sb-names*)
77                      res)))
78
79        (/show0 "about to put SB onto/into SB-LIST")
80        (setf *backend-sb-list*
81              (cons (sb-or-lose ',name)
82                    (remove ',name *backend-sb-list* :key #'sb-name)))
83        (/show0 "finished with DEFINE-STORAGE-BASE expansion")
84        ',name)))
85
86 ;;; Define a storage class NAME that uses the named Storage-Base.
87 ;;; NUMBER is a small, non-negative integer that is used as an alias.
88 ;;; The following keywords are defined:
89 ;;;
90 ;;; :ELEMENT-SIZE Size
91 ;;;   The size of objects in this SC in whatever units the SB uses.
92 ;;;   This defaults to 1.
93 ;;;
94 ;;; :ALIGNMENT Size
95 ;;;   The alignment restrictions for this SC. TNs will only be
96 ;;;   allocated at offsets that are an even multiple of this number.
97 ;;;   This defaults to 1.
98 ;;;
99 ;;; :LOCATIONS (Location*)
100 ;;;   If the SB is :FINITE, then this is a list of the offsets within
101 ;;;   the SB that are in this SC.
102 ;;;
103 ;;; :RESERVE-LOCATIONS (Location*)
104 ;;;   A subset of the Locations that the register allocator should try to
105 ;;;   reserve for operand loading (instead of to hold variable values.)
106 ;;;
107 ;;; :SAVE-P {T | NIL}
108 ;;;   If T, then values stored in this SC must be saved in one of the
109 ;;;   non-save-p :ALTERNATE-SCs across calls.
110 ;;;
111 ;;; :ALTERNATE-SCS (SC*)
112 ;;;   Indicates other SCs that can be used to hold values from this SC across
113 ;;;   calls or when storage in this SC is exhausted. The SCs should be
114 ;;;   specified in order of decreasing \"goodness\". There must be at least
115 ;;;   one SC in an unbounded SB, unless this SC is only used for restricted or
116 ;;;   wired TNs.
117 ;;;
118 ;;; :CONSTANT-SCS (SC*)
119 ;;;   A list of the names of all the constant SCs that can be loaded into this
120 ;;;   SC by a move function.
121 (defmacro define-storage-class (name number sb-name &key (element-size '1)
122                                      (alignment '1) locations reserve-locations
123                                      save-p alternate-scs constant-scs)
124   (declare (type symbol name))
125   (declare (type sc-number number))
126   (declare (type symbol sb-name))
127   (declare (type list locations reserve-locations alternate-scs constant-scs))
128   (declare (type boolean save-p))
129   (unless (= (logcount alignment) 1)
130     (error "alignment not a power of two: ~W" alignment))
131
132   (let ((sb (meta-sb-or-lose sb-name)))
133     (if (eq (sb-kind sb) :finite)
134         (let ((size (sb-size sb))
135               (element-size (eval element-size)))
136           (declare (type unsigned-byte element-size))
137           (dolist (el locations)
138             (declare (type unsigned-byte el))
139             (unless (<= 1 (+ el element-size) size)
140               (error "SC element ~W out of bounds for ~S" el sb))))
141         (when locations
142           (error ":LOCATIONS is meaningless in a ~S SB." (sb-kind sb))))
143
144     (unless (subsetp reserve-locations locations)
145       (error "RESERVE-LOCATIONS not a subset of LOCATIONS."))
146
147     (when (and (or alternate-scs constant-scs)
148                (eq (sb-kind sb) :non-packed))
149       (error
150        "It's meaningless to specify alternate or constant SCs in a ~S SB."
151        (sb-kind sb))))
152
153   (let ((nstack-p
154          (if (or (eq sb-name 'non-descriptor-stack)
155                  (find 'non-descriptor-stack
156                        (mapcar #'meta-sc-or-lose alternate-scs)
157                        :key (lambda (x)
158                               (sb-name (sc-sb x)))))
159              t nil)))
160     `(progn
161        (eval-when (:compile-toplevel :load-toplevel :execute)
162          (let ((res (make-sc :name ',name :number ',number
163                              :sb (meta-sb-or-lose ',sb-name)
164                              :element-size ,element-size
165                              :alignment ,alignment
166                              :locations ',locations
167                              :reserve-locations ',reserve-locations
168                              :save-p ',save-p
169                              :number-stack-p ,nstack-p
170                              :alternate-scs (mapcar #'meta-sc-or-lose
171                                                     ',alternate-scs)
172                              :constant-scs (mapcar #'meta-sc-or-lose
173                                                    ',constant-scs))))
174            (setf (gethash ',name *backend-meta-sc-names*) res)
175            (setf (svref *backend-meta-sc-numbers* ',number) res)
176            (setf (svref (sc-load-costs res) ',number) 0)))
177
178        (let ((old (svref *backend-sc-numbers* ',number)))
179          (when (and old (not (eq (sc-name old) ',name)))
180            (warn "redefining SC number ~W from ~S to ~S" ',number
181                  (sc-name old) ',name)))
182
183        (setf (svref *backend-sc-numbers* ',number)
184              (meta-sc-or-lose ',name))
185        (setf (gethash ',name *backend-sc-names*)
186              (meta-sc-or-lose ',name))
187        (setf (sc-sb (sc-or-lose ',name)) (sb-or-lose ',sb-name))
188        ',name)))
189 \f
190 ;;;; move/coerce definition
191
192 ;;; Given a list of pairs of lists of SCs (as given to DEFINE-MOVE-VOP,
193 ;;; etc.), bind TO-SC and FROM-SC to all the combinations.
194 (defmacro do-sc-pairs ((from-sc-var to-sc-var scs) &body body)
195   `(do ((froms ,scs (cddr froms))
196         (tos (cdr ,scs) (cddr tos)))
197        ((null froms))
198      (dolist (from (car froms))
199        (let ((,from-sc-var (meta-sc-or-lose from)))
200          (dolist (to (car tos))
201            (let ((,to-sc-var (meta-sc-or-lose to)))
202              ,@body))))))
203
204 ;;; Define the function NAME and note it as the function used for
205 ;;; moving operands from the From-SCs to the To-SCs. Cost is the cost
206 ;;; of this move operation. The function is called with three
207 ;;; arguments: the VOP (for context), and the source and destination
208 ;;; TNs. An ASSEMBLE form is wrapped around the body. All uses of
209 ;;; DEFINE-MOVE-FUN should be compiled before any uses of
210 ;;; DEFINE-VOP.
211 (defmacro define-move-fun ((name cost) lambda-list scs &body body)
212   (declare (type index cost))
213   (when (or (oddp (length scs)) (null scs))
214     (error "malformed SCs spec: ~S" scs))
215   `(progn
216      (eval-when (:compile-toplevel :load-toplevel :execute)
217        (do-sc-pairs (from-sc to-sc ',scs)
218          (unless (eq from-sc to-sc)
219            (let ((num (sc-number from-sc)))
220              (setf (svref (sc-move-funs to-sc) num) ',name)
221              (setf (svref (sc-load-costs to-sc) num) ',cost)))))
222
223      (defun ,name ,lambda-list
224        (sb!assem:assemble (*code-segment* ,(first lambda-list))
225          ,@body))))
226
227 (eval-when (:compile-toplevel :load-toplevel :execute)
228   (defparameter *sc-vop-slots*
229     '((:move . sc-move-vops)
230       (:move-arg . sc-move-arg-vops))))
231
232 ;;; Make NAME be the VOP used to move values in the specified FROM-SCs
233 ;;; to the representation of the TO-SCs of each SC pair in SCS.
234 ;;;
235 ;;; If KIND is :MOVE-ARG, then the VOP takes an extra argument,
236 ;;; which is the frame pointer of the frame to move into.
237 ;;;
238 ;;; We record the VOP and costs for all SCs that we can move between
239 ;;; (including implicit loading).
240 (defmacro define-move-vop (name kind &rest scs)
241   (when (or (oddp (length scs)) (null scs))
242     (error "malformed SCs spec: ~S" scs))
243   (let ((accessor (or (cdr (assoc kind *sc-vop-slots*))
244                       (error "unknown kind ~S" kind))))
245     `(progn
246        ,@(when (eq kind :move)
247            `((eval-when (:compile-toplevel :load-toplevel :execute)
248                (do-sc-pairs (from-sc to-sc ',scs)
249                  (compute-move-costs from-sc to-sc
250                                      ,(vop-parse-cost
251                                        (vop-parse-or-lose name)))))))
252
253        (let ((vop (template-or-lose ',name)))
254          (do-sc-pairs (from-sc to-sc ',scs)
255            (dolist (dest-sc (cons to-sc (sc-alternate-scs to-sc)))
256              (let ((vec (,accessor dest-sc)))
257                (let ((scn (sc-number from-sc)))
258                  (setf (svref vec scn)
259                        (adjoin-template vop (svref vec scn))))
260                (dolist (sc (append (sc-alternate-scs from-sc)
261                                    (sc-constant-scs from-sc)))
262                  (let ((scn (sc-number sc)))
263                    (setf (svref vec scn)
264                          (adjoin-template vop (svref vec scn))))))))))))
265 \f
266 ;;;; primitive type definition
267
268 (defun meta-primitive-type-or-lose (name)
269   (the primitive-type
270        (or (gethash name *backend-meta-primitive-type-names*)
271            (error "~S is not a defined primitive type." name))))
272
273 ;;; Define a primitive type NAME. Each SCS entry specifies a storage
274 ;;; class that values of this type may be allocated in. TYPE is the
275 ;;; type descriptor for the Lisp type that is equivalent to this type.
276 (defmacro !def-primitive-type (name scs &key (type name))
277   (declare (type symbol name) (type list scs))
278   (let ((scns (mapcar #'meta-sc-number-or-lose scs)))
279     `(progn
280        (/show0 "doing !DEF-PRIMITIVE-TYPE, NAME=..")
281        (/primitive-print ,(symbol-name name))
282        (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
283          (setf (gethash ',name *backend-meta-primitive-type-names*)
284                (make-primitive-type :name ',name
285                                     :scs ',scns
286                                     :specifier ',type)))
287        ,(once-only ((n-old `(gethash ',name *backend-primitive-type-names*)))
288           `(progn
289              ;; If the PRIMITIVE-TYPE structure already exists, we
290              ;; destructively modify it so that existing references in
291              ;; templates won't be invalidated. FIXME: This should no
292              ;; longer be an issue in SBCL, since we don't try to do
293              ;; serious surgery on ourselves. Probably this should
294              ;; just become an assertion that N-OLD is NIL, so that we
295              ;; don't have to try to maintain the correctness of the
296              ;; never-ordinarily-used clause.
297              (/show0 "in !DEF-PRIMITIVE-TYPE, about to COND")
298              (cond (,n-old
299                     (/show0 "in ,N-OLD clause of COND")
300                     (setf (primitive-type-scs ,n-old) ',scns)
301                     (setf (primitive-type-specifier ,n-old) ',type))
302                    (t
303                     (/show0 "in T clause of COND")
304                     (setf (gethash ',name *backend-primitive-type-names*)
305                           (make-primitive-type :name ',name
306                                                :scs ',scns
307                                                :specifier ',type))))
308              (/show0 "done with !DEF-PRIMITIVE-TYPE")
309              ',name)))))
310
311 ;;; Define NAME to be an alias for RESULT in VOP operand type restrictions.
312 (defmacro !def-primitive-type-alias (name result)
313   ;; Just record the translation.
314   `(eval-when (:compile-toplevel :load-toplevel :execute)
315      (setf (gethash ',name *backend-primitive-type-aliases*) ',result)
316      ',name))
317
318 (defparameter *primitive-type-slot-alist*
319   '((:check . primitive-type-check)))
320
321 ;;;  Primitive-Type-VOP Vop (Kind*) Type*
322 ;;;
323 ;;; Annotate all the specified primitive Types with the named VOP
324 ;;; under each of the specified kinds:
325 ;;;
326 ;;; :CHECK
327 ;;;    A one-argument one-result VOP that moves the argument to the
328 ;;;    result, checking that the value is of this type in the process.
329 (defmacro primitive-type-vop (vop kinds &rest types)
330   (let ((n-vop (gensym))
331         (n-type (gensym)))
332     `(let ((,n-vop (template-or-lose ',vop)))
333        ,@(mapcar
334           (lambda (type)
335             `(let ((,n-type (primitive-type-or-lose ',type)))
336                ,@(mapcar
337                   (lambda (kind)
338                     (let ((slot (or (cdr (assoc kind
339                                                 *primitive-type-slot-alist*))
340                                     (error "unknown kind: ~S" kind))))
341                       `(setf (,slot ,n-type) ,n-vop)))
342                   kinds)))
343           types)
344        nil)))
345
346 ;;; Return true if SC is either one of PTYPE's SC's, or one of those
347 ;;; SC's alternate or constant SCs.
348 (defun meta-sc-allowed-by-primitive-type (sc ptype)
349   (declare (type sc sc) (type primitive-type ptype))
350   (let ((scn (sc-number sc)))
351     (dolist (allowed (primitive-type-scs ptype) nil)
352       (when (eql allowed scn)
353         (return t))
354       (let ((allowed-sc (svref *backend-meta-sc-numbers* allowed)))
355         (when (or (member sc (sc-alternate-scs allowed-sc))
356                   (member sc (sc-constant-scs allowed-sc)))
357           (return t))))))
358 \f
359 ;;;; VOP definition structures
360 ;;;;
361 ;;;; DEFINE-VOP uses some fairly complex data structures at
362 ;;;; meta-compile time, both to hold the results of parsing the
363 ;;;; elaborate syntax and to retain the information so that it can be
364 ;;;; inherited by other VOPs.
365
366 ;;; A VOP-PARSE object holds everything we need to know about a VOP at
367 ;;; meta-compile time.
368 (def!struct (vop-parse
369              (:make-load-form-fun just-dump-it-normally)
370              #-sb-xc-host (:pure t))
371   ;; the name of this VOP
372   (name nil :type symbol)
373   ;; If true, then the name of the VOP we inherit from.
374   (inherits nil :type (or symbol null))
375   ;; lists of OPERAND-PARSE structures describing the arguments,
376   ;; results and temporaries of the VOP
377   (args nil :type list)
378   (results nil :type list)
379   (temps nil :type list)
380   ;; OPERAND-PARSE structures containing information about more args
381   ;; and results. If null, then there there are no more operands of
382   ;; that kind
383   (more-args nil :type (or operand-parse null))
384   (more-results nil :type (or operand-parse null))
385   ;; a list of all the above together
386   (operands nil :type list)
387   ;; names of variables that should be declared IGNORE
388   (ignores () :type list)
389   ;; true if this is a :CONDITIONAL VOP
390   (conditional-p nil)
391   ;; argument and result primitive types. These are pulled out of the
392   ;; operands, since we often want to change them without respecifying
393   ;; the operands.
394   (arg-types :unspecified :type (or (member :unspecified) list))
395   (result-types :unspecified :type (or (member :unspecified) list))
396   ;; the guard expression specified, or NIL if none
397   (guard nil)
398   ;; the cost of and body code for the generator
399   (cost 0 :type unsigned-byte)
400   (body :unspecified :type (or (member :unspecified) list))
401   ;; info for VOP variants. The list of forms to be evaluated to get
402   ;; the variant args for this VOP, and the list of variables to be
403   ;; bound to the variant args.
404   (variant () :type list)
405   (variant-vars () :type list)
406   ;; variables bound to the VOP and Vop-Node when in the generator body
407   (vop-var (gensym) :type symbol)
408   (node-var nil :type (or symbol null))
409   ;; a list of the names of the codegen-info arguments to this VOP
410   (info-args () :type list)
411   ;; an efficiency note associated with this VOP
412   (note nil :type (or string null))
413   ;; a list of the names of the Effects and Affected attributes for
414   ;; this VOP
415   (effects '(any) :type list)
416   (affected '(any) :type list)
417   ;; a list of the names of functions this VOP is a translation of and
418   ;; the policy that allows this translation to be done. :FAST is a
419   ;; safe default, since it isn't a safe policy.
420   (translate () :type list)
421   (ltn-policy :fast :type ltn-policy)
422   ;; stuff used by life analysis
423   (save-p nil :type (member t nil :compute-only :force-to-stack))
424   ;; info about how to emit MOVE-ARG VOPs for the &MORE operand in
425   ;; call/return VOPs
426   (move-args nil :type (member nil :local-call :full-call :known-return)))
427 (defprinter (vop-parse)
428   name
429   (inherits :test inherits)
430   args
431   results
432   temps
433   (more-args :test more-args)
434   (more-results :test more-results)
435   (conditional-p :test conditional-p)
436   ignores
437   arg-types
438   result-types
439   cost
440   body
441   (variant :test variant)
442   (variant-vars :test variant-vars)
443   (info-args :test info-args)
444   (note :test note)
445   effects
446   affected
447   translate
448   ltn-policy
449   (save-p :test save-p)
450   (move-args :test move-args))
451
452 ;;; An OPERAND-PARSE object contains stuff we need to know about an
453 ;;; operand or temporary at meta-compile time. Besides the obvious
454 ;;; stuff, we also store the names of per-operand temporaries here.
455 (def!struct (operand-parse
456              (:make-load-form-fun just-dump-it-normally)
457              #-sb-xc-host (:pure t))
458   ;; name of the operand (which we bind to the TN)
459   (name nil :type symbol)
460   ;; the way this operand is used:
461   (kind (missing-arg)
462         :type (member :argument :result :temporary
463                       :more-argument :more-result))
464   ;; If true, the name of an operand that this operand is targeted to.
465   ;; This is only meaningful in :ARGUMENT and :TEMPORARY operands.
466   (target nil :type (or symbol null))
467   ;; TEMP is a temporary that holds the TN-REF for this operand.
468   ;; TEMP-TEMP holds the write reference that begins a temporary's
469   ;; lifetime.
470   (temp (gensym) :type symbol)
471   (temp-temp nil :type (or symbol null))
472   ;; the time that this operand is first live and the time at which it
473   ;; becomes dead again. These are TIME-SPECs, as returned by
474   ;; PARSE-TIME-SPEC.
475   born
476   dies
477   ;; a list of the names of the SCs that this operand is allowed into.
478   ;; If false, there is no restriction.
479   (scs nil :type list)
480   ;; Variable that is bound to the load TN allocated for this operand, or to
481   ;; NIL if no load-TN was allocated.
482   (load-tn (gensym) :type symbol)
483   ;; an expression that tests whether to do automatic operand loading
484   (load t)
485   ;; In a wired or restricted temporary this is the SC the TN is to be
486   ;; packed in. Null otherwise.
487   (sc nil :type (or symbol null))
488   ;; If non-null, we are a temp wired to this offset in SC.
489   (offset nil :type (or unsigned-byte null)))
490 (defprinter (operand-parse)
491   name
492   kind
493   (target :test target)
494   born
495   dies
496   (scs :test scs)
497   (load :test load)
498   (sc :test sc)
499   (offset :test offset))
500 \f
501 ;;;; miscellaneous utilities
502
503 ;;; Find the operand or temporary with the specifed Name in the VOP
504 ;;; Parse. If there is no such operand, signal an error. Also error if
505 ;;; the operand kind isn't one of the specified Kinds. If Error-P is
506 ;;; NIL, just return NIL if there is no such operand.
507 (defun find-operand (name parse &optional
508                           (kinds '(:argument :result :temporary))
509                           (error-p t))
510   (declare (symbol name) (type vop-parse parse) (list kinds))
511   (let ((found (find name (vop-parse-operands parse)
512                      :key #'operand-parse-name)))
513     (if found
514         (unless (member (operand-parse-kind found) kinds)
515           (error "Operand ~S isn't one of these kinds: ~S." name kinds))
516         (when error-p
517           (error "~S is not an operand to ~S." name (vop-parse-name parse))))
518     found))
519
520 ;;; Get the VOP-PARSE structure for NAME or die trying. For all
521 ;;; meta-compile time uses, the VOP-PARSE should be used instead of
522 ;;; the VOP-INFO.
523 (defun vop-parse-or-lose (name)
524   (the vop-parse
525        (or (gethash name *backend-parsed-vops*)
526            (error "~S is not the name of a defined VOP." name))))
527
528 ;;; Return a list of LET-forms to parse a TN-REF list into the temps
529 ;;; specified by the operand-parse structures. MORE-OPERAND is the
530 ;;; Operand-Parse describing any more operand, or NIL if none. REFS is
531 ;;; an expression that evaluates into the first tn-ref.
532 (defun access-operands (operands more-operand refs)
533   (declare (list operands))
534   (collect ((res))
535     (let ((prev refs))
536       (dolist (op operands)
537         (let ((n-ref (operand-parse-temp op)))
538           (res `(,n-ref ,prev))
539           (setq prev `(tn-ref-across ,n-ref))))
540
541       (when more-operand
542         (res `(,(operand-parse-name more-operand) ,prev))))
543     (res)))
544
545 ;;; This is used with ACCESS-OPERANDS to prevent warnings for TN-REF
546 ;;; temps not used by some particular function. It returns the name of
547 ;;; the last operand, or NIL if Operands is NIL.
548 (defun ignore-unreferenced-temps (operands)
549   (when operands
550     (operand-parse-temp (car (last operands)))))
551
552 ;;; Grab an arg out of a VOP spec, checking the type and syntax and stuff.
553 (defun vop-spec-arg (spec type &optional (n 1) (last t))
554   (let ((len (length spec)))
555     (when (<= len n)
556       (error "~:R argument missing: ~S" n spec))
557     (when (and last (> len (1+ n)))
558       (error "extra junk at end of ~S" spec))
559     (let ((thing (elt spec n)))
560       (unless (typep thing type)
561         (error "~:R argument is not a ~S: ~S" n type spec))
562       thing)))
563 \f
564 ;;;; time specs
565
566 ;;; Return a time spec describing a time during the evaluation of a
567 ;;; VOP, used to delimit operand and temporary lifetimes. The
568 ;;; representation is a cons whose CAR is the number of the evaluation
569 ;;; phase and the CDR is the sub-phase. The sub-phase is 0 in the
570 ;;; :LOAD and :SAVE phases.
571 (defun parse-time-spec (spec)
572   (let ((dspec (if (atom spec) (list spec 0) spec)))
573     (unless (and (= (length dspec) 2)
574                  (typep (second dspec) 'unsigned-byte))
575       (error "malformed time specifier: ~S" spec))
576
577     (cons (case (first dspec)
578             (:load 0)
579             (:argument 1)
580             (:eval 2)
581             (:result 3)
582             (:save 4)
583             (t
584              (error "unknown phase in time specifier: ~S" spec)))
585           (second dspec))))
586
587 ;;; Return true if the time spec X is the same or later time than Y.
588 (defun time-spec-order (x y)
589   (or (> (car x) (car y))
590       (and (= (car x) (car y))
591            (>= (cdr x) (cdr y)))))
592 \f
593 ;;;; generation of emit functions
594
595 (defun compute-temporaries-description (parse)
596   (let ((temps (vop-parse-temps parse))
597         (element-type '(unsigned-byte 16)))
598     (when temps
599       (let ((results (make-specializable-array
600                       (length temps)
601                       :element-type element-type))
602             (index 0))
603         (dolist (temp temps)
604           (declare (type operand-parse temp))
605           (let ((sc (operand-parse-sc temp))
606                 (offset (operand-parse-offset temp)))
607             (aver sc)
608             (setf (aref results index)
609                   (if offset
610                       (+ (ash offset (1+ sc-bits))
611                          (ash (meta-sc-number-or-lose sc) 1)
612                          1)
613                       (ash (meta-sc-number-or-lose sc) 1))))
614           (incf index))
615         ;; KLUDGE: As in the other COERCEs wrapped around with
616         ;; MAKE-SPECIALIZABLE-ARRAY results in COMPUTE-REF-ORDERING,
617         ;; this coercion could be removed by a sufficiently smart
618         ;; compiler, but I dunno whether Python is that smart. It
619         ;; would be good to check this and help it if it's not smart
620         ;; enough to remove it for itself. However, it's probably not
621         ;; urgent, since the overhead of an extra no-op conversion is
622         ;; unlikely to be large compared to consing and corresponding
623         ;; GC. -- WHN ca. 19990701
624         `(coerce ,results '(specializable-vector ,element-type))))))
625
626 (defun compute-ref-ordering (parse)
627   (let* ((num-args (+ (length (vop-parse-args parse))
628                       (if (vop-parse-more-args parse) 1 0)))
629          (num-results (+ (length (vop-parse-results parse))
630                          (if (vop-parse-more-results parse) 1 0)))
631          (index 0))
632     (collect ((refs) (targets))
633       (dolist (op (vop-parse-operands parse))
634         (when (operand-parse-target op)
635           (unless (member (operand-parse-kind op) '(:argument :temporary))
636             (error "cannot target a ~S operand: ~S" (operand-parse-kind op)
637                    (operand-parse-name op)))
638           (let ((target (find-operand (operand-parse-target op) parse
639                                       '(:temporary :result))))
640             ;; KLUDGE: These formulas must be consistent with those in
641             ;; %EMIT-GENERIC-VOP, and this is currently maintained by
642             ;; hand. -- WHN 2002-01-30, paraphrasing APD
643             (targets (+ (* index max-vop-tn-refs)
644                         (ecase (operand-parse-kind target)
645                           (:result
646                            (+ (position-or-lose target
647                                                 (vop-parse-results parse))
648                               num-args))
649                           (:temporary
650                            (+ (* (position-or-lose target
651                                                    (vop-parse-temps parse))
652                                  2)
653                               1
654                               num-args
655                               num-results)))))))
656         (let ((born (operand-parse-born op))
657               (dies (operand-parse-dies op)))
658           (ecase (operand-parse-kind op)
659             (:argument
660              (refs (cons (cons dies nil) index)))
661             (:more-argument
662              (refs (cons (cons dies nil) index)))
663             (:result
664              (refs (cons (cons born t) index)))
665             (:more-result
666              (refs (cons (cons born t) index)))
667             (:temporary
668              (refs (cons (cons dies nil) index))
669              (incf index)
670              (refs (cons (cons born t) index))))
671           (incf index)))
672       (let* ((sorted (sort (refs)
673                            (lambda (x y)
674                              (let ((x-time (car x))
675                                    (y-time (car y)))
676                                (if (time-spec-order x-time y-time)
677                                    (if (time-spec-order y-time x-time)
678                                        (and (not (cdr x)) (cdr y))
679                                        nil)
680                                    t)))
681                            :key #'car))
682              ;; :REF-ORDERING element type
683              ;;
684              ;; KLUDGE: was (MOD #.MAX-VOP-TN-REFS), which is still right
685              (oe-type '(unsigned-byte 8))
686              ;; :TARGETS element-type
687              ;;
688              ;; KLUDGE: was (MOD #.(* MAX-VOP-TN-REFS 2)), which does
689              ;; not correspond to the definition in
690              ;; src/compiler/vop.lisp.
691              (te-type '(unsigned-byte 16))
692              (ordering (make-specializable-array
693                         (length sorted)
694                         :element-type oe-type)))
695         (let ((index 0))
696           (dolist (ref sorted)
697             (setf (aref ordering index) (cdr ref))
698             (incf index)))
699         `(:num-args ,num-args
700           :num-results ,num-results
701           ;; KLUDGE: The (COERCE .. (SPECIALIZABLE-VECTOR ..)) wrapper
702           ;; here around the result returned by
703           ;; MAKE-SPECIALIZABLE-ARRAY above was of course added to
704           ;; help with cross-compilation. "A sufficiently smart
705           ;; compiler" should be able to optimize all this away in the
706           ;; final target Lisp, leaving a single MAKE-ARRAY with no
707           ;; subsequent coercion. However, I don't know whether Python
708           ;; is that smart. (Can it figure out the return type of
709           ;; MAKE-ARRAY? Does it know that COERCE can be optimized
710           ;; away if the input type is known to be the same as the
711           ;; COERCEd-to type?) At some point it would be good to test
712           ;; to see whether this construct is in fact causing run-time
713           ;; overhead, and fix it if so. (Some declarations of the
714           ;; types returned by MAKE-ARRAY might be enough to fix it.)
715           ;; However, it's probably not urgent to fix this, since it's
716           ;; hard to imagine that any overhead caused by calling
717           ;; COERCE and letting it decide to bail out could be large
718           ;; compared to the cost of consing and GCing the vectors in
719           ;; the first place. -- WHN ca. 19990701
720           :ref-ordering (coerce ',ordering
721                                 '(specializable-vector ,oe-type))
722           ,@(when (targets)
723               `(:targets (coerce ',(targets)
724                                  '(specializable-vector ,te-type)))))))))
725
726 (defun make-emit-function-and-friends (parse)
727   `(:emit-function #'emit-generic-vop
728     :temps ,(compute-temporaries-description parse)
729     ,@(compute-ref-ordering parse)))
730 \f
731 ;;;; generator functions
732
733 ;;; Return an alist that translates from lists of SCs we can load OP
734 ;;; from to the move function used for loading those SCs. We quietly
735 ;;; ignore restrictions to :non-packed (constant) and :unbounded SCs,
736 ;;; since we don't load into those SCs.
737 (defun find-move-funs (op load-p)
738   (collect ((funs))
739     (dolist (sc-name (operand-parse-scs op))
740       (let* ((sc (meta-sc-or-lose sc-name))
741              (scn (sc-number sc))
742              (load-scs (append (when load-p
743                                  (sc-constant-scs sc))
744                                (sc-alternate-scs sc))))
745         (cond
746          (load-scs
747           (dolist (alt load-scs)
748             (unless (member (sc-name alt) (operand-parse-scs op) :test #'eq)
749               (let* ((altn (sc-number alt))
750                      (name (if load-p
751                                (svref (sc-move-funs sc) altn)
752                                (svref (sc-move-funs alt) scn)))
753                      (found (or (assoc alt (funs) :test #'member)
754                                 (rassoc name (funs)))))
755                 (unless name
756                   (error "no move function defined to ~:[save~;load~] SC ~S ~
757                           ~:[to~;from~] from SC ~S"
758                          load-p sc-name load-p (sc-name alt)))
759                 
760                 (cond (found
761                        (unless (eq (cdr found) name)
762                          (error "can't tell whether to ~:[save~;load~]~@
763                                  with ~S or ~S when operand is in SC ~S"
764                                 load-p name (cdr found) (sc-name alt)))
765                        (pushnew alt (car found)))
766                       (t
767                        (funs (cons (list alt) name))))))))
768          ((member (sb-kind (sc-sb sc)) '(:non-packed :unbounded)))
769          (t
770           (error "SC ~S has no alternate~:[~; or constant~] SCs, yet it is~@
771                   mentioned in the restriction for operand ~S"
772                  sc-name load-p (operand-parse-name op))))))
773     (funs)))
774
775 ;;; Return a form to load/save the specified operand when it has a
776 ;;; load TN. For any given SC that we can load from, there must be a
777 ;;; unique load function. If all SCs we can load from have the same
778 ;;; move function, then we just call that when there is a load TN. If
779 ;;; there are multiple possible move functions, then we dispatch off
780 ;;; of the operand TN's type to see which move function to use.
781 (defun call-move-fun (parse op load-p)
782   (let ((funs (find-move-funs op load-p))
783         (load-tn (operand-parse-load-tn op)))
784     (if funs
785         (let* ((tn `(tn-ref-tn ,(operand-parse-temp op)))
786                (n-vop (or (vop-parse-vop-var parse)
787                           (setf (vop-parse-vop-var parse) (gensym))))
788                (form (if (rest funs)
789                          `(sc-case ,tn
790                             ,@(mapcar (lambda (x)
791                                         `(,(mapcar #'sc-name (car x))
792                                           ,(if load-p
793                                                `(,(cdr x) ,n-vop ,tn
794                                                  ,load-tn)
795                                                `(,(cdr x) ,n-vop ,load-tn
796                                                  ,tn))))
797                                       funs))
798                          (if load-p
799                              `(,(cdr (first funs)) ,n-vop ,tn ,load-tn)
800                              `(,(cdr (first funs)) ,n-vop ,load-tn ,tn)))))
801           (if (eq (operand-parse-load op) t)
802               `(when ,load-tn ,form)
803               `(when (eq ,load-tn ,(operand-parse-name op))
804                  ,form)))
805         `(when ,load-tn
806            (error "load TN allocated, but no move function?~@
807                    VM definition is inconsistent, recompile and try again.")))))
808
809 ;;; Return the TN that we should bind to the operand's var in the
810 ;;; generator body. In general, this involves evaluating the :LOAD-IF
811 ;;; test expression.
812 (defun decide-to-load (parse op)
813   (let ((load (operand-parse-load op))
814         (load-tn (operand-parse-load-tn op))
815         (temp (operand-parse-temp op)))
816     (if (eq load t)
817         `(or ,load-tn (tn-ref-tn ,temp))
818         (collect ((binds)
819                   (ignores))
820           (dolist (x (vop-parse-operands parse))
821             (when (member (operand-parse-kind x) '(:argument :result))
822               (let ((name (operand-parse-name x)))
823                 (binds `(,name (tn-ref-tn ,(operand-parse-temp x))))
824                 (ignores name))))
825           `(if (and ,load-tn
826                     (let ,(binds)
827                       (declare (ignorable ,@(ignores)))
828                       ,load))
829                ,load-tn
830                (tn-ref-tn ,temp))))))
831
832 ;;; Make a lambda that parses the VOP TN-REFS, does automatic operand
833 ;;; loading, and runs the appropriate code generator.
834 (defun make-generator-function (parse)
835   (declare (type vop-parse parse))
836   (let ((n-vop (vop-parse-vop-var parse))
837         (operands (vop-parse-operands parse))
838         (n-info (gensym)) (n-variant (gensym)))
839     (collect ((binds)
840               (loads)
841               (saves))
842       (dolist (op operands)
843         (ecase (operand-parse-kind op)
844           ((:argument :result)
845            (let ((temp (operand-parse-temp op))
846                  (name (operand-parse-name op)))
847              (cond ((and (operand-parse-load op) (operand-parse-scs op))
848                     (binds `(,(operand-parse-load-tn op)
849                              (tn-ref-load-tn ,temp)))
850                     (binds `(,name ,(decide-to-load parse op)))
851                     (if (eq (operand-parse-kind op) :argument)
852                         (loads (call-move-fun parse op t))
853                         (saves (call-move-fun parse op nil))))
854                    (t
855                     (binds `(,name (tn-ref-tn ,temp)))))))
856           (:temporary
857            (binds `(,(operand-parse-name op)
858                     (tn-ref-tn ,(operand-parse-temp op)))))
859           ((:more-argument :more-result))))
860
861       `(lambda (,n-vop)
862          (let* (,@(access-operands (vop-parse-args parse)
863                                    (vop-parse-more-args parse)
864                                    `(vop-args ,n-vop))
865                   ,@(access-operands (vop-parse-results parse)
866                                      (vop-parse-more-results parse)
867                                      `(vop-results ,n-vop))
868                   ,@(access-operands (vop-parse-temps parse) nil
869                                      `(vop-temps ,n-vop))
870                   ,@(when (vop-parse-info-args parse)
871                       `((,n-info (vop-codegen-info ,n-vop))
872                         ,@(mapcar (lambda (x) `(,x (pop ,n-info)))
873                                   (vop-parse-info-args parse))))
874                   ,@(when (vop-parse-variant-vars parse)
875                       `((,n-variant (vop-info-variant (vop-info ,n-vop)))
876                         ,@(mapcar (lambda (x) `(,x (pop ,n-variant)))
877                                   (vop-parse-variant-vars parse))))
878                   ,@(when (vop-parse-node-var parse)
879                       `((,(vop-parse-node-var parse) (vop-node ,n-vop))))
880                   ,@(binds))
881            (declare (ignore ,@(vop-parse-ignores parse)))
882            ,@(loads)
883            (sb!assem:assemble (*code-segment* ,n-vop)
884                               ,@(vop-parse-body parse))
885            ,@(saves))))))
886 \f
887 ;;; Given a list of operand specifications as given to DEFINE-VOP,
888 ;;; return a list of OPERAND-PARSE structures describing the fixed
889 ;;; operands, and a single OPERAND-PARSE describing any more operand.
890 ;;; If we are inheriting a VOP, we default attributes to the inherited
891 ;;; operand of the same name.
892 (defun !parse-vop-operands (parse specs kind)
893   (declare (list specs)
894            (type (member :argument :result) kind))
895   (let ((num -1)
896         (more nil))
897     (collect ((operands))
898       (dolist (spec specs)
899         (unless (and (consp spec) (symbolp (first spec)) (oddp (length spec)))
900           (error "malformed operand specifier: ~S" spec))
901         (when more
902           (error "The MORE operand isn't the last operand: ~S" specs))
903         (let* ((name (first spec))
904                (old (if (vop-parse-inherits parse)
905                         (find-operand name
906                                       (vop-parse-or-lose
907                                        (vop-parse-inherits parse))
908                                       (list kind)
909                                       nil)
910                         nil))
911                (res (if old
912                         (make-operand-parse
913                          :name name
914                          :kind kind
915                          :target (operand-parse-target old)
916                          :born (operand-parse-born old)
917                          :dies (operand-parse-dies old)
918                          :scs (operand-parse-scs old)
919                          :load-tn (operand-parse-load-tn old)
920                          :load (operand-parse-load old))
921                         (ecase kind
922                           (:argument
923                            (make-operand-parse
924                             :name (first spec)
925                             :kind :argument
926                             :born (parse-time-spec :load)
927                             :dies (parse-time-spec `(:argument ,(incf num)))))
928                           (:result
929                            (make-operand-parse
930                             :name (first spec)
931                             :kind :result
932                             :born (parse-time-spec `(:result ,(incf num)))
933                             :dies (parse-time-spec :save)))))))
934           (do ((key (rest spec) (cddr key)))
935               ((null key))
936             (let ((value (second key)))
937               (case (first key)
938                 (:scs
939                  (aver (typep value 'list))
940                  (setf (operand-parse-scs res) (remove-duplicates value)))
941                 (:load-tn
942                  (aver (typep value 'symbol))
943                  (setf (operand-parse-load-tn res) value))
944                 (:load-if
945                  (setf (operand-parse-load res) value))
946                 (:more
947                  (aver (typep value 'boolean))
948                  (setf (operand-parse-kind res)
949                        (if (eq kind :argument) :more-argument :more-result))
950                  (setf (operand-parse-load res) nil)
951                  (setq more res))
952                 (:target
953                  (aver (typep value 'symbol))
954                  (setf (operand-parse-target res) value))
955                 (:from
956                  (unless (eq kind :result)
957                    (error "can only specify :FROM in a result: ~S" spec))
958                  (setf (operand-parse-born res) (parse-time-spec value)))
959                 (:to
960                  (unless (eq kind :argument)
961                    (error "can only specify :TO in an argument: ~S" spec))
962                  (setf (operand-parse-dies res) (parse-time-spec value)))
963                 (t
964                  (error "unknown keyword in operand specifier: ~S" spec)))))
965
966           (cond ((not more)
967                  (operands res))
968                 ((operand-parse-target more)
969                  (error "cannot specify :TARGET in a :MORE operand"))
970                 ((operand-parse-load more)
971                  (error "cannot specify :LOAD-IF in a :MORE operand")))))
972       (values (the list (operands)) more))))
973 \f
974 ;;; Parse a temporary specification, putting the OPERAND-PARSE
975 ;;; structures in the PARSE structure.
976 (defun parse-temporary (spec parse)
977   (declare (list spec)
978            (type vop-parse parse))
979   (let ((len (length spec)))
980     (unless (>= len 2)
981       (error "malformed temporary spec: ~S" spec))
982     (unless (listp (second spec))
983       (error "malformed options list: ~S" (second spec)))
984     (unless (evenp (length (second spec)))
985       (error "odd number of arguments in keyword options: ~S" spec))
986     (unless (consp (cddr spec))
987       (warn "temporary spec allocates no temps:~%  ~S" spec))
988     (dolist (name (cddr spec))
989       (unless (symbolp name)
990         (error "bad temporary name: ~S" name))
991       (let ((res (make-operand-parse :name name
992                                      :kind :temporary
993                                      :temp-temp (gensym)
994                                      :born (parse-time-spec :load)
995                                      :dies (parse-time-spec :save))))
996         (do ((opt (second spec) (cddr opt)))
997             ((null opt))
998           (case (first opt)
999             (:target
1000              (setf (operand-parse-target res)
1001                    (vop-spec-arg opt 'symbol 1 nil)))
1002             (:sc
1003              (setf (operand-parse-sc res)
1004                    (vop-spec-arg opt 'symbol 1 nil)))
1005             (:offset
1006              (let ((offset (eval (second opt))))
1007                (aver (typep offset 'unsigned-byte))
1008                (setf (operand-parse-offset res) offset)))
1009             (:from
1010              (setf (operand-parse-born res) (parse-time-spec (second opt))))
1011             (:to
1012              (setf (operand-parse-dies res) (parse-time-spec (second opt))))
1013             ;; backward compatibility...
1014             (:scs
1015              (let ((scs (vop-spec-arg opt 'list 1 nil)))
1016                (unless (= (length scs) 1)
1017                  (error "must specify exactly one SC for a temporary"))
1018                (setf (operand-parse-sc res) (first scs))))
1019             (:type)
1020             (t
1021              (error "unknown temporary option: ~S" opt))))
1022
1023         (unless (and (time-spec-order (operand-parse-dies res)
1024                                       (operand-parse-born res))
1025                      (not (time-spec-order (operand-parse-born res)
1026                                            (operand-parse-dies res))))
1027           (error "Temporary lifetime doesn't begin before it ends: ~S" spec))
1028
1029         (unless (operand-parse-sc res)
1030           (error "must specify :SC for all temporaries: ~S" spec))
1031
1032         (setf (vop-parse-temps parse)
1033               (cons res
1034                     (remove name (vop-parse-temps parse)
1035                             :key #'operand-parse-name))))))
1036   (values))
1037 \f
1038 ;;; the top level parse function: clobber PARSE to represent the
1039 ;;; specified options.
1040 (defun parse-define-vop (parse specs)
1041   (declare (type vop-parse parse) (list specs))
1042   (dolist (spec specs)
1043     (unless (consp spec)
1044       (error "malformed option specification: ~S" spec))
1045     (case (first spec)
1046       (:args
1047        (multiple-value-bind (fixed more)
1048            (!parse-vop-operands parse (rest spec) :argument)
1049          (setf (vop-parse-args parse) fixed)
1050          (setf (vop-parse-more-args parse) more)))
1051       (:results
1052        (multiple-value-bind (fixed more)
1053            (!parse-vop-operands parse (rest spec) :result)
1054          (setf (vop-parse-results parse) fixed)
1055          (setf (vop-parse-more-results parse) more))
1056        (setf (vop-parse-conditional-p parse) nil))
1057       (:conditional
1058        (setf (vop-parse-result-types parse) ())
1059        (setf (vop-parse-results parse) ())
1060        (setf (vop-parse-more-results parse) nil)
1061        (setf (vop-parse-conditional-p parse) t))
1062       (:temporary
1063        (parse-temporary spec parse))
1064       (:generator
1065        (setf (vop-parse-cost parse)
1066              (vop-spec-arg spec 'unsigned-byte 1 nil))
1067        (setf (vop-parse-body parse) (cddr spec)))
1068       (:effects
1069        (setf (vop-parse-effects parse) (rest spec)))
1070       (:affected
1071        (setf (vop-parse-affected parse) (rest spec)))
1072       (:info
1073        (setf (vop-parse-info-args parse) (rest spec)))
1074       (:ignore
1075        (setf (vop-parse-ignores parse) (rest spec)))
1076       (:variant
1077        (setf (vop-parse-variant parse) (rest spec)))
1078       (:variant-vars
1079        (let ((vars (rest spec)))
1080          (setf (vop-parse-variant-vars parse) vars)
1081          (setf (vop-parse-variant parse)
1082                (make-list (length vars) :initial-element nil))))
1083       (:variant-cost
1084        (setf (vop-parse-cost parse) (vop-spec-arg spec 'unsigned-byte)))
1085       (:vop-var
1086        (setf (vop-parse-vop-var parse) (vop-spec-arg spec 'symbol)))
1087       (:move-args
1088        (setf (vop-parse-move-args parse)
1089              (vop-spec-arg spec '(member nil :local-call :full-call
1090                                          :known-return))))
1091       (:node-var
1092        (setf (vop-parse-node-var parse) (vop-spec-arg spec 'symbol)))
1093       (:note
1094        (setf (vop-parse-note parse) (vop-spec-arg spec '(or string null))))
1095       (:arg-types
1096        (setf (vop-parse-arg-types parse)
1097              (!parse-vop-operand-types (rest spec) t)))
1098       (:result-types
1099        (setf (vop-parse-result-types parse)
1100              (!parse-vop-operand-types (rest spec) nil)))
1101       (:translate
1102        (setf (vop-parse-translate parse) (rest spec)))
1103       (:guard
1104        (setf (vop-parse-guard parse) (vop-spec-arg spec t)))
1105       ;; FIXME: :LTN-POLICY would be a better name for this. It would
1106       ;; probably be good to leave it unchanged for a while, though,
1107       ;; at least until the first port to some other architecture,
1108       ;; since the renaming would be a change to the interface between
1109       (:policy
1110        (setf (vop-parse-ltn-policy parse)
1111              (vop-spec-arg spec 'ltn-policy)))
1112       (:save-p
1113        (setf (vop-parse-save-p parse)
1114              (vop-spec-arg spec
1115                            '(member t nil :compute-only :force-to-stack))))
1116       (t
1117        (error "unknown option specifier: ~S" (first spec)))))
1118   (values))
1119 \f
1120 ;;;; making costs and restrictions
1121
1122 ;;; Given an operand, returns two values:
1123 ;;; 1. A SC-vector of the cost for the operand being in that SC,
1124 ;;;    including both the costs for move functions and coercion VOPs.
1125 ;;; 2. A SC-vector holding the SC that we load into, for any SC
1126 ;;;    that we can directly load from.
1127 ;;;
1128 ;;; In both vectors, unused entries are NIL. LOAD-P specifies the
1129 ;;; direction: if true, we are loading, if false we are saving.
1130 (defun compute-loading-costs (op load-p)
1131   (declare (type operand-parse op))
1132   (let ((scs (operand-parse-scs op))
1133         (costs (make-array sc-number-limit :initial-element nil))
1134         (load-scs (make-array sc-number-limit :initial-element nil)))
1135     (dolist (sc-name scs)
1136       (let* ((load-sc (meta-sc-or-lose sc-name))
1137              (load-scn (sc-number load-sc)))
1138         (setf (svref costs load-scn) 0)
1139         (setf (svref load-scs load-scn) t)
1140         (dolist (op-sc (append (when load-p
1141                                  (sc-constant-scs load-sc))
1142                                (sc-alternate-scs load-sc)))
1143           (let* ((op-scn (sc-number op-sc))
1144                  (load (if load-p
1145                            (aref (sc-load-costs load-sc) op-scn)
1146                            (aref (sc-load-costs op-sc) load-scn))))
1147             (unless load
1148               (error "no move function defined to move ~:[from~;to~] SC ~
1149                       ~S~%~:[to~;from~] alternate or constant SC ~S"
1150                      load-p sc-name load-p (sc-name op-sc)))
1151
1152             (let ((op-cost (svref costs op-scn)))
1153               (when (or (not op-cost) (< load op-cost))
1154                 (setf (svref costs op-scn) load)))
1155
1156             (let ((op-load (svref load-scs op-scn)))
1157               (unless (eq op-load t)
1158                 (pushnew load-scn (svref load-scs op-scn))))))
1159
1160         (dotimes (i sc-number-limit)
1161           (unless (svref costs i)
1162             (let ((op-sc (svref *backend-meta-sc-numbers* i)))
1163               (when op-sc
1164                 (let ((cost (if load-p
1165                                 (svref (sc-move-costs load-sc) i)
1166                                 (svref (sc-move-costs op-sc) load-scn))))
1167                   (when cost
1168                     (setf (svref costs i) cost)))))))))
1169
1170     (values costs load-scs)))
1171
1172 (defparameter *no-costs*
1173   (make-array sc-number-limit :initial-element 0))
1174
1175 (defparameter *no-loads*
1176   (make-array sc-number-limit :initial-element t))
1177
1178 ;;; Pick off the case of operands with no restrictions.
1179 (defun compute-loading-costs-if-any (op load-p)
1180   (declare (type operand-parse op))
1181   (if (operand-parse-scs op)
1182       (compute-loading-costs op load-p)
1183       (values *no-costs* *no-loads*)))
1184
1185 (defun compute-costs-and-restrictions-list (ops load-p)
1186   (declare (list ops))
1187   (collect ((costs)
1188             (scs))
1189     (dolist (op ops)
1190       (multiple-value-bind (costs scs) (compute-loading-costs-if-any op load-p)
1191         (costs costs)
1192         (scs scs)))
1193     (values (costs) (scs))))
1194
1195 (defun make-costs-and-restrictions (parse)
1196   (multiple-value-bind (arg-costs arg-scs)
1197       (compute-costs-and-restrictions-list (vop-parse-args parse) t)
1198     (multiple-value-bind (result-costs result-scs)
1199         (compute-costs-and-restrictions-list (vop-parse-results parse) nil)
1200       `(
1201         :cost ,(vop-parse-cost parse)
1202         
1203         :arg-costs ',arg-costs
1204         :arg-load-scs ',arg-scs
1205         :result-costs ',result-costs
1206         :result-load-scs ',result-scs
1207         
1208         :more-arg-costs
1209         ',(if (vop-parse-more-args parse)
1210               (compute-loading-costs-if-any (vop-parse-more-args parse) t)
1211               nil)
1212         
1213         :more-result-costs
1214         ',(if (vop-parse-more-results parse)
1215               (compute-loading-costs-if-any (vop-parse-more-results parse) nil)
1216               nil)))))
1217 \f
1218 ;;;; operand checking and stuff
1219
1220 ;;; Given a list of arg/result restrictions, check for valid syntax
1221 ;;; and convert to canonical form.
1222 (defun !parse-vop-operand-types (specs args-p)
1223   (declare (list specs))
1224   (labels ((parse-operand-type (spec)
1225              (cond ((eq spec '*) spec)
1226                    ((symbolp spec)
1227                     (let ((alias (gethash spec
1228                                           *backend-primitive-type-aliases*)))
1229                       (if alias
1230                           (parse-operand-type alias)
1231                           `(:or ,spec))))
1232                    ((atom spec)
1233                     (error "bad thing to be a operand type: ~S" spec))
1234                    (t
1235                     (case (first spec)
1236                       (:or
1237                        (collect ((results))
1238                          (results :or)
1239                          (dolist (item (cdr spec))
1240                            (unless (symbolp item)
1241                              (error "bad PRIMITIVE-TYPE name in ~S: ~S"
1242                                     spec item))
1243                            (let ((alias
1244                                   (gethash item
1245                                            *backend-primitive-type-aliases*)))
1246                              (if alias
1247                                  (let ((alias (parse-operand-type alias)))
1248                                    (unless (eq (car alias) :or)
1249                                      (error "can't include primitive-type ~
1250                                              alias ~S in an :OR restriction: ~S"
1251                                             item spec))
1252                                    (dolist (x (cdr alias))
1253                                      (results x)))
1254                                  (results item))))
1255                          (remove-duplicates (results)
1256                                             :test #'eq
1257                                             :start 1)))
1258                       (:constant
1259                        (unless args-p
1260                          (error "can't :CONSTANT for a result"))
1261                        (unless (= (length spec) 2)
1262                          (error "bad :CONSTANT argument type spec: ~S" spec))
1263                        spec)
1264                       (t
1265                        (error "bad thing to be a operand type: ~S" spec)))))))
1266     (mapcar #'parse-operand-type specs)))
1267
1268 ;;; Check the consistency of OP's SC restrictions with the specified
1269 ;;; primitive-type restriction. :CONSTANT operands have already been
1270 ;;; filtered out, so only :OR and * restrictions are left.
1271 ;;;
1272 ;;; We check that every representation allowed by the type can be
1273 ;;; directly loaded into some SC in the restriction, and that the type
1274 ;;; allows every SC in the restriction. With *, we require that T
1275 ;;; satisfy the first test, and omit the second.
1276 (defun check-operand-type-scs (parse op type load-p)
1277   (declare (type vop-parse parse) (type operand-parse op))
1278   (let ((ptypes (if (eq type '*) (list t) (rest type)))
1279         (scs (operand-parse-scs op)))
1280     (when scs
1281       (multiple-value-bind (costs load-scs) (compute-loading-costs op load-p)
1282         (declare (ignore costs))
1283         (dolist (ptype ptypes)
1284           (unless (dolist (rep (primitive-type-scs
1285                                 (meta-primitive-type-or-lose ptype))
1286                                nil)
1287                     (when (svref load-scs rep) (return t)))
1288             (error "In the ~A ~:[result~;argument~] to VOP ~S,~@
1289                     none of the SCs allowed by the operand type ~S can ~
1290                     directly be loaded~@
1291                     into any of the restriction's SCs:~%  ~S~:[~;~@
1292                     [* type operand must allow T's SCs.]~]"
1293                    (operand-parse-name op) load-p (vop-parse-name parse)
1294                    ptype
1295                    scs (eq type '*)))))
1296
1297       (dolist (sc scs)
1298         (unless (or (eq type '*)
1299                     (dolist (ptype ptypes nil)
1300                       (when (meta-sc-allowed-by-primitive-type
1301                              (meta-sc-or-lose sc)
1302                              (meta-primitive-type-or-lose ptype))
1303                         (return t))))
1304           (warn "~:[Result~;Argument~] ~A to VOP ~S~@
1305                  has SC restriction ~S which is ~
1306                  not allowed by the operand type:~%  ~S"
1307                 load-p (operand-parse-name op) (vop-parse-name parse)
1308                 sc type)))))
1309
1310   (values))
1311
1312 ;;; If the operand types are specified, then check the number specified
1313 ;;; against the number of defined operands.
1314 (defun check-operand-types (parse ops more-op types load-p)
1315   (declare (type vop-parse parse) (list ops)
1316            (type (or list (member :unspecified)) types)
1317            (type (or operand-parse null) more-op))
1318   (unless (eq types :unspecified)
1319     (let ((num (+ (length ops) (if more-op 1 0))))
1320       (unless (= (count-if-not (lambda (x)
1321                                  (and (consp x)
1322                                       (eq (car x) :constant)))
1323                                types)
1324                  num)
1325         (error "expected ~W ~:[result~;argument~] type~P: ~S"
1326                num load-p types num)))
1327
1328     (when more-op
1329       (let ((mtype (car (last types))))
1330         (when (and (consp mtype) (eq (first mtype) :constant))
1331           (error "can't use :CONSTANT on VOP more args")))))
1332
1333   (when (vop-parse-translate parse)
1334     (let ((types (specify-operand-types types ops more-op)))
1335       (mapc (lambda (x y)
1336               (check-operand-type-scs parse x y load-p))
1337             (if more-op (butlast ops) ops)
1338             (remove-if (lambda (x)
1339                          (and (consp x)
1340                               (eq (car x) ':constant)))
1341                        (if more-op (butlast types) types)))))
1342
1343   (values))
1344
1345 ;;; Compute stuff that can only be computed after we are done parsing
1346 ;;; everying. We set the VOP-PARSE-OPERANDS, and do various error checks.
1347 (defun !grovel-vop-operands (parse)
1348   (declare (type vop-parse parse))
1349
1350   (setf (vop-parse-operands parse)
1351         (append (vop-parse-args parse)
1352                 (if (vop-parse-more-args parse)
1353                     (list (vop-parse-more-args parse)))
1354                 (vop-parse-results parse)
1355                 (if (vop-parse-more-results parse)
1356                     (list (vop-parse-more-results parse)))
1357                 (vop-parse-temps parse)))
1358
1359   (check-operand-types parse
1360                        (vop-parse-args parse)
1361                        (vop-parse-more-args parse)
1362                        (vop-parse-arg-types parse)
1363                        t)
1364
1365   (check-operand-types parse
1366                        (vop-parse-results parse)
1367                        (vop-parse-more-results parse)
1368                        (vop-parse-result-types parse)
1369                        nil)
1370
1371   (values))
1372 \f
1373 ;;;; function translation stuff
1374
1375 ;;; Return forms to establish this VOP as a IR2 translation template
1376 ;;; for the :TRANSLATE functions specified in the VOP-PARSE. We also
1377 ;;; set the PREDICATE attribute for each translated function when the
1378 ;;; VOP is conditional, causing IR1 conversion to ensure that a call
1379 ;;; to the translated is always used in a predicate position.
1380 (defun !set-up-fun-translation (parse n-template)
1381   (declare (type vop-parse parse))
1382   (mapcar (lambda (name)
1383             `(let ((info (fun-info-or-lose ',name)))
1384                (setf (fun-info-templates info)
1385                      (adjoin-template ,n-template (fun-info-templates info)))
1386                ,@(when (vop-parse-conditional-p parse)
1387                    '((setf (fun-info-attributes info)
1388                            (attributes-union
1389                             (ir1-attributes predicate)
1390                             (fun-info-attributes info)))))))
1391           (vop-parse-translate parse)))
1392
1393 ;;; Return a form that can be evaluated to get the TEMPLATE operand type
1394 ;;; restriction from the given specification.
1395 (defun make-operand-type (type)
1396   (cond ((eq type '*) ''*)
1397         ((symbolp type)
1398          ``(:or ,(primitive-type-or-lose ',type)))
1399         (t
1400          (ecase (first type)
1401            (:or
1402             ``(:or ,,@(mapcar (lambda (type)
1403                                 `(primitive-type-or-lose ',type))
1404                               (rest type))))
1405            (:constant
1406             ``(:constant ,#'(lambda (x)
1407                               (typep x ',(second type)))
1408                          ,',(second type)))))))
1409
1410 (defun specify-operand-types (types ops more-ops)
1411   (if (eq types :unspecified)
1412       (make-list (+ (length ops) (if more-ops 1 0)) :initial-element '*)
1413       types))
1414
1415 ;;; Return a list of forms to use as &KEY args to MAKE-VOP-INFO for
1416 ;;; setting up the template argument and result types. Here we make an
1417 ;;; initial dummy TEMPLATE-TYPE, since it is awkward to compute the
1418 ;;; type until the template has been made.
1419 (defun make-vop-info-types (parse)
1420   (let* ((more-args (vop-parse-more-args parse))
1421          (all-args (specify-operand-types (vop-parse-arg-types parse)
1422                                           (vop-parse-args parse)
1423                                           more-args))
1424          (args (if more-args (butlast all-args) all-args))
1425          (more-arg (when more-args (car (last all-args))))
1426          (more-results (vop-parse-more-results parse))
1427          (all-results (specify-operand-types (vop-parse-result-types parse)
1428                                              (vop-parse-results parse)
1429                                              more-results))
1430          (results (if more-results (butlast all-results) all-results))
1431          (more-result (when more-results (car (last all-results))))
1432          (conditional (vop-parse-conditional-p parse)))
1433
1434     `(:type (specifier-type '(function () nil))
1435       :arg-types (list ,@(mapcar #'make-operand-type args))
1436       :more-args-type ,(when more-args (make-operand-type more-arg))
1437       :result-types ,(if conditional
1438                          :conditional
1439                          `(list ,@(mapcar #'make-operand-type results)))
1440       :more-results-type ,(when more-results
1441                             (make-operand-type more-result)))))
1442 \f
1443 ;;;; setting up VOP-INFO
1444
1445 (eval-when (:compile-toplevel :load-toplevel :execute)
1446   (defparameter *slot-inherit-alist*
1447     '((:generator-function . vop-info-generator-function))))
1448
1449 ;;; This is something to help with inheriting VOP-INFO slots. We
1450 ;;; return a keyword/value pair that can be passed to the constructor.
1451 ;;; SLOT is the keyword name of the slot, Parse is a form that
1452 ;;; evaluates to the VOP-PARSE structure for the VOP inherited. If
1453 ;;; PARSE is NIL, then we do nothing. If the TEST form evaluates to
1454 ;;; true, then we return a form that selects the named slot from the
1455 ;;; VOP-INFO structure corresponding to PARSE. Otherwise, we return
1456 ;;; the FORM so that the slot is recomputed.
1457 (defmacro inherit-vop-info (slot parse test form)
1458   `(if (and ,parse ,test)
1459        (list ,slot `(,',(or (cdr (assoc slot *slot-inherit-alist*))
1460                             (error "unknown slot ~S" slot))
1461                      (template-or-lose ',(vop-parse-name ,parse))))
1462        (list ,slot ,form)))
1463
1464 ;;; Return a form that creates a VOP-INFO structure which describes VOP.
1465 (defun set-up-vop-info (iparse parse)
1466   (declare (type vop-parse parse) (type (or vop-parse null) iparse))
1467   (let ((same-operands
1468          (and iparse
1469               (equal (vop-parse-operands parse)
1470                      (vop-parse-operands iparse))
1471               (equal (vop-parse-info-args iparse)
1472                      (vop-parse-info-args parse))))
1473         (variant (vop-parse-variant parse)))
1474
1475     (let ((nvars (length (vop-parse-variant-vars parse))))
1476       (unless (= (length variant) nvars)
1477         (error "expected ~W variant values: ~S" nvars variant)))
1478
1479     `(make-vop-info
1480       :name ',(vop-parse-name parse)
1481       ,@(make-vop-info-types parse)
1482       :guard ,(when (vop-parse-guard parse)
1483                 `(lambda () ,(vop-parse-guard parse)))
1484       :note ',(vop-parse-note parse)
1485       :info-arg-count ,(length (vop-parse-info-args parse))
1486       :ltn-policy ',(vop-parse-ltn-policy parse)
1487       :save-p ',(vop-parse-save-p parse)
1488       :move-args ',(vop-parse-move-args parse)
1489       :effects (vop-attributes ,@(vop-parse-effects parse))
1490       :affected (vop-attributes ,@(vop-parse-affected parse))
1491       ,@(make-costs-and-restrictions parse)
1492       ,@(make-emit-function-and-friends parse)
1493       ,@(inherit-vop-info :generator-function iparse
1494           (and same-operands
1495                (equal (vop-parse-body parse) (vop-parse-body iparse)))
1496           (unless (eq (vop-parse-body parse) :unspecified)
1497             (make-generator-function parse)))
1498       :variant (list ,@variant))))
1499 \f
1500 ;;; Define the symbol NAME to be a Virtual OPeration in the compiler.
1501 ;;; If specified, INHERITS is the name of a VOP that we default
1502 ;;; unspecified information from. Each SPEC is a list beginning with a
1503 ;;; keyword indicating the interpretation of the other forms in the
1504 ;;; SPEC:
1505 ;;;
1506 ;;; :ARGS {(Name {Key Value}*)}*
1507 ;;; :RESULTS {(Name {Key Value}*)}*
1508 ;;;     The Args and Results are specifications of the operand TNs passed
1509 ;;;     to the VOP. If there is an inherited VOP, any unspecified options
1510 ;;;     are defaulted from the inherited argument (or result) of the same
1511 ;;;     name. The following operand options are defined:
1512 ;;;
1513 ;;;     :SCs (SC*)
1514 ;;;         :SCs specifies good SCs for this operand. Other SCs will
1515 ;;;         be penalized according to move costs. A load TN will be
1516 ;;;         allocated if necessary, guaranteeing that the operand is
1517 ;;;         always one of the specified SCs.
1518 ;;;
1519 ;;;     :LOAD-TN Load-Name
1520 ;;;         Load-Name is bound to the load TN allocated for this
1521 ;;;         operand, or to NIL if no load TN was allocated.
1522 ;;;
1523 ;;;     :LOAD-IF EXPRESSION
1524 ;;;         Controls whether automatic operand loading is done.
1525 ;;;         EXPRESSION is evaluated with the fixed operand TNs bound.
1526 ;;;         If EXPRESSION is true,then loading is done and the variable
1527 ;;;         is bound to the load TN in the generator body. Otherwise,
1528 ;;;         loading is not done, and the variable is bound to the actual
1529 ;;;         operand.
1530 ;;;
1531 ;;;     :MORE T-or-NIL
1532 ;;;         If specified, NAME is bound to the TN-REF for the first
1533 ;;;         argument or result following the fixed arguments or results.
1534 ;;;         A :MORE operand must appear last, and cannot be targeted or
1535 ;;;         restricted.
1536 ;;;
1537 ;;;     :TARGET Operand
1538 ;;;         This operand is targeted to the named operand, indicating a
1539 ;;;         desire to pack in the same location. Not legal for results.
1540 ;;;
1541 ;;;     :FROM Time-Spec
1542 ;;;     :TO Time-Spec
1543 ;;;         Specify the beginning or end of the operand's lifetime.
1544 ;;;         :FROM can only be used with results, and :TO only with
1545 ;;;         arguments. The default for the N'th argument/result is
1546 ;;;         (:ARGUMENT N)/(:RESULT N). These options are necessary
1547 ;;;         primarily when operands are read or written out of order.
1548 ;;;
1549 ;;; :CONDITIONAL
1550 ;;;     This is used in place of :RESULTS with conditional branch VOPs.
1551 ;;;     There are no result values: the result is a transfer of control.
1552 ;;;     The target label is passed as the first :INFO arg. The second
1553 ;;;     :INFO arg is true if the sense of the test should be negated.
1554 ;;;     A side effect is to set the PREDICATE attribute for functions
1555 ;;;     in the :TRANSLATE option.
1556 ;;;
1557 ;;; :TEMPORARY ({Key Value}*) Name*
1558 ;;;     Allocate a temporary TN for each Name, binding that variable to
1559 ;;;     the TN within the body of the generators. In addition to :TARGET
1560 ;;;     (which is is the same as for operands), the following options are
1561 ;;;     defined:
1562 ;;;
1563 ;;;     :SC SC-Name
1564 ;;;     :OFFSET SB-Offset
1565 ;;;         Force the temporary to be allocated in the specified SC
1566 ;;;         with the specified offset. Offset is evaluated at
1567 ;;;         macroexpand time. If Offset is emitted, the register
1568 ;;;         allocator chooses a free location in SC. If both SC and
1569 ;;;         Offset are omitted, then the temporary is packed according
1570 ;;;         to its primitive type.
1571 ;;;
1572 ;;;     :FROM Time-Spec
1573 ;;;     :TO Time-Spec
1574 ;;;         Similar to the argument/result option, this specifies the
1575 ;;;         start and end of the temporaries' lives. The defaults are
1576 ;;;         :LOAD and :SAVE, i.e. the duration of the VOP. The other
1577 ;;;         intervening phases are :ARGUMENT,:EVAL and :RESULT.
1578 ;;;         Non-zero sub-phases can be specified by a list, e.g. by
1579 ;;;         default the second argument's life ends at (:ARGUMENT 1).
1580 ;;;
1581 ;;; :GENERATOR Cost Form*
1582 ;;;     Specifies the translation into assembly code. Cost is the
1583 ;;;     estimated cost of the code emitted by this generator. The body
1584 ;;;     is arbitrary Lisp code that emits the assembly language
1585 ;;;     translation of the VOP. An ASSEMBLE form is wrapped around
1586 ;;;     the body, so code may be emitted by using the local INST macro.
1587 ;;;     During the evaluation of the body, the names of the operands
1588 ;;;     and temporaries are bound to the actual TNs.
1589 ;;;
1590 ;;; :EFFECTS Effect*
1591 ;;; :AFFECTED Effect*
1592 ;;;     Specifies the side effects that this VOP has and the side
1593 ;;;     effects that effect its execution. If unspecified, these
1594 ;;;     default to the worst case.
1595 ;;;
1596 ;;; :INFO Name*
1597 ;;;     Define some magic arguments that are passed directly to the code
1598 ;;;     generator. The corresponding trailing arguments to VOP or
1599 ;;;     %PRIMITIVE are stored in the VOP structure. Within the body
1600 ;;;     of the generators, the named variables are bound to these
1601 ;;;     values. Except in the case of :CONDITIONAL VOPs, :INFO arguments
1602 ;;;     cannot be specified for VOPS that are the direct translation
1603 ;;;     for a function (specified by :TRANSLATE).
1604 ;;;
1605 ;;; :IGNORE Name*
1606 ;;;     Causes the named variables to be declared IGNORE in the
1607 ;;;     generator body.
1608 ;;;
1609 ;;; :VARIANT Thing*
1610 ;;; :VARIANT-VARS Name*
1611 ;;;     These options provide a way to parameterize families of VOPs
1612 ;;;     that differ only trivially. :VARIANT makes the specified
1613 ;;;     evaluated Things be the "variant" associated with this VOP.
1614 ;;;     :VARIANT-VARS causes the named variables to be bound to the
1615 ;;;     corresponding Things within the body of the generator.
1616 ;;;
1617 ;;; :VARIANT-COST Cost
1618 ;;;     Specifies the cost of this VOP, overriding the cost of any 
1619 ;;;     inherited generator.
1620 ;;;
1621 ;;; :NOTE {String | NIL}
1622 ;;;     A short noun-like phrase describing what this VOP "does", i.e.
1623 ;;;     the implementation strategy. If supplied, efficiency notes will
1624 ;;;     be generated when type uncertainty prevents :TRANSLATE from
1625 ;;;     working. NIL inhibits any efficiency note.
1626 ;;;
1627 ;;; :ARG-TYPES    {* | PType | (:OR PType*) | (:CONSTANT Type)}*
1628 ;;; :RESULT-TYPES {* | PType | (:OR PType*)}*
1629 ;;;     Specify the template type restrictions used for automatic
1630 ;;;     translation. If there is a :MORE operand, the last type is the
1631 ;;;     more type. :CONSTANT specifies that the argument must be a
1632 ;;;     compile-time constant of the specified Lisp type. The constant
1633 ;;;     values of :CONSTANT arguments are passed as additional :INFO
1634 ;;;     arguments rather than as :ARGS.
1635 ;;;
1636 ;;; :TRANSLATE Name*
1637 ;;;     This option causes the VOP template to be entered as an IR2
1638 ;;;     translation for the named functions.
1639 ;;;
1640 ;;; :POLICY {:SMALL | :FAST | :SAFE | :FAST-SAFE}
1641 ;;;     Specifies the policy under which this VOP is the best translation.
1642 ;;;
1643 ;;; :GUARD Form
1644 ;;;     Specifies a Form that is evaluated in the global environment.
1645 ;;;     If form returns NIL, then emission of this VOP is prohibited
1646 ;;;     even when all other restrictions are met.
1647 ;;;
1648 ;;; :VOP-VAR Name
1649 ;;; :NODE-VAR Name
1650 ;;;     In the generator, bind the specified variable to the VOP or
1651 ;;;     the Node that generated this VOP.
1652 ;;;
1653 ;;; :SAVE-P {NIL | T | :COMPUTE-ONLY | :FORCE-TO-STACK}
1654 ;;;     Indicates how a VOP wants live registers saved.
1655 ;;;
1656 ;;; :MOVE-ARGS {NIL | :FULL-CALL | :LOCAL-CALL | :KNOWN-RETURN}
1657 ;;;     Indicates if and how the more args should be moved into a
1658 ;;;     different frame.
1659 (def!macro define-vop ((name &optional inherits) &rest specs)
1660   (declare (type symbol name))
1661   ;; Parse the syntax into a VOP-PARSE structure, and then expand into
1662   ;; code that creates the appropriate VOP-INFO structure at load time.
1663   ;; We implement inheritance by copying the VOP-PARSE structure for
1664   ;; the inherited structure.
1665   (let* ((inherited-parse (when inherits
1666                             (vop-parse-or-lose inherits)))
1667          (parse (if inherits
1668                     (copy-vop-parse inherited-parse)
1669                     (make-vop-parse)))
1670          (n-res (gensym)))
1671     (setf (vop-parse-name parse) name)
1672     (setf (vop-parse-inherits parse) inherits)
1673
1674     (parse-define-vop parse specs)
1675     (!grovel-vop-operands parse)
1676
1677     `(progn
1678        (eval-when (:compile-toplevel :load-toplevel :execute)
1679          (setf (gethash ',name *backend-parsed-vops*)
1680                ',parse))
1681
1682        (let ((,n-res ,(set-up-vop-info inherited-parse parse)))
1683          (setf (gethash ',name *backend-template-names*) ,n-res)
1684          (setf (template-type ,n-res)
1685                (specifier-type (template-type-specifier ,n-res)))
1686          ,@(!set-up-fun-translation parse n-res))
1687        ',name)))
1688 \f
1689 ;;;; emission macros
1690
1691 ;;; Return code to make a list of VOP arguments or results, linked by
1692 ;;; TN-REF-ACROSS. The first value is code, the second value is LET*
1693 ;;; forms, and the third value is a variable that evaluates to the
1694 ;;; head of the list, or NIL if there are no operands. Fixed is a list
1695 ;;; of forms that evaluate to TNs for the fixed operands. TN-REFS will
1696 ;;; be made for these operands according using the specified value of
1697 ;;; WRITE-P. More is an expression that evaluates to a list of TN-REFS
1698 ;;; that will be made the tail of the list. If it is constant NIL,
1699 ;;; then we don't bother to set the tail.
1700 (defun make-operand-list (fixed more write-p)
1701   (collect ((forms)
1702             (binds))
1703     (let ((n-head nil)
1704           (n-prev nil))
1705       (dolist (op fixed)
1706         (let ((n-ref (gensym)))
1707           (binds `(,n-ref (reference-tn ,op ,write-p)))
1708           (if n-prev
1709               (forms `(setf (tn-ref-across ,n-prev) ,n-ref))
1710               (setq n-head n-ref))
1711           (setq n-prev n-ref)))
1712
1713       (when more
1714         (let ((n-more (gensym)))
1715           (binds `(,n-more ,more))
1716           (if n-prev
1717               (forms `(setf (tn-ref-across ,n-prev) ,n-more))
1718               (setq n-head n-more))))
1719
1720       (values (forms) (binds) n-head))))
1721
1722 ;;; Emit-Template Node Block Template Args Results [Info]
1723 ;;;
1724 ;;; Call the emit function for TEMPLATE, linking the result in at the
1725 ;;; end of BLOCK.
1726 (defmacro emit-template (node block template args results &optional info)
1727   (let ((n-first (gensym))
1728         (n-last (gensym)))
1729     (once-only ((n-node node)
1730                 (n-block block)
1731                 (n-template template))
1732       `(multiple-value-bind (,n-first ,n-last)
1733            (funcall (template-emit-function ,n-template)
1734                     ,n-node ,n-block ,n-template ,args ,results
1735                     ,@(when info `(,info)))
1736          (insert-vop-sequence ,n-first ,n-last ,n-block nil)))))
1737
1738 ;;; VOP Name Node Block Arg* Info* Result*
1739 ;;;
1740 ;;; Emit the VOP (or other template) NAME at the end of the IR2-BLOCK
1741 ;;; BLOCK, using NODE for the source context. The interpretation of
1742 ;;; the remaining arguments depends on the number of operands of
1743 ;;; various kinds that are declared in the template definition. VOP
1744 ;;; cannot be used for templates that have more-args or more-results,
1745 ;;; since the number of arguments and results is indeterminate for
1746 ;;; these templates. Use VOP* instead.
1747 ;;;
1748 ;;; ARGS and RESULTS are the TNs that are to be referenced by the
1749 ;;; template as arguments and results. If the template has
1750 ;;; codegen-info arguments, then the appropriate number of INFO forms
1751 ;;; following the arguments are used for codegen info.
1752 (defmacro vop (name node block &rest operands)
1753   (let* ((parse (vop-parse-or-lose name))
1754          (arg-count (length (vop-parse-args parse)))
1755          (result-count (length (vop-parse-results parse)))
1756          (info-count (length (vop-parse-info-args parse)))
1757          (noperands (+ arg-count result-count info-count))
1758          (n-node (gensym))
1759          (n-block (gensym))
1760          (n-template (gensym)))
1761
1762     (when (or (vop-parse-more-args parse) (vop-parse-more-results parse))
1763       (error "cannot use VOP with variable operand count templates"))
1764     (unless (= noperands (length operands))
1765       (error "called with ~W operands, but was expecting ~W"
1766              (length operands) noperands))
1767
1768     (multiple-value-bind (acode abinds n-args)
1769         (make-operand-list (subseq operands 0 arg-count) nil nil)
1770       (multiple-value-bind (rcode rbinds n-results)
1771           (make-operand-list (subseq operands (+ arg-count info-count)) nil t)
1772
1773         (collect ((ibinds)
1774                   (ivars))
1775           (dolist (info (subseq operands arg-count (+ arg-count info-count)))
1776             (let ((temp (gensym)))
1777               (ibinds `(,temp ,info))
1778               (ivars temp)))
1779
1780           `(let* ((,n-node ,node)
1781                   (,n-block ,block)
1782                   (,n-template (template-or-lose ',name))
1783                   ,@abinds
1784                   ,@(ibinds)
1785                   ,@rbinds)
1786              ,@acode
1787              ,@rcode
1788              (emit-template ,n-node ,n-block ,n-template ,n-args
1789                             ,n-results
1790                             ,@(when (ivars)
1791                                 `((list ,@(ivars)))))
1792              (values)))))))
1793
1794 ;;; VOP* Name Node Block (Arg* More-Args) (Result* More-Results) Info*
1795 ;;;
1796 ;;; This is like VOP, but allows for emission of templates with
1797 ;;; arbitrary numbers of arguments, and for emission of templates
1798 ;;; using already-created TN-REF lists.
1799 ;;;
1800 ;;; The ARGS and RESULTS are TNs to be referenced as the first
1801 ;;; arguments and results to the template. More-Args and More-Results
1802 ;;; are heads of TN-REF lists that are added onto the end of the
1803 ;;; TN-REFS for the explicitly supplied operand TNs. The TN-REFS for
1804 ;;; the more operands must have the TN and WRITE-P slots correctly
1805 ;;; initialized.
1806 ;;;
1807 ;;; As with VOP, the INFO forms are evaluated and passed as codegen
1808 ;;; info arguments.
1809 (defmacro vop* (name node block args results &rest info)
1810   (declare (type cons args results))
1811   (let* ((parse (vop-parse-or-lose name))
1812          (arg-count (length (vop-parse-args parse)))
1813          (result-count (length (vop-parse-results parse)))
1814          (info-count (length (vop-parse-info-args parse)))
1815          (fixed-args (butlast args))
1816          (fixed-results (butlast results))
1817          (n-node (gensym))
1818          (n-block (gensym))
1819          (n-template (gensym)))
1820
1821     (unless (or (vop-parse-more-args parse)
1822                 (<= (length fixed-args) arg-count))
1823       (error "too many fixed arguments"))
1824     (unless (or (vop-parse-more-results parse)
1825                 (<= (length fixed-results) result-count))
1826       (error "too many fixed results"))
1827     (unless (= (length info) info-count)
1828       (error "expected ~W info args" info-count))
1829
1830     (multiple-value-bind (acode abinds n-args)
1831         (make-operand-list fixed-args (car (last args)) nil)
1832       (multiple-value-bind (rcode rbinds n-results)
1833           (make-operand-list fixed-results (car (last results)) t)
1834
1835         `(let* ((,n-node ,node)
1836                 (,n-block ,block)
1837                 (,n-template (template-or-lose ',name))
1838                 ,@abinds
1839                 ,@rbinds)
1840            ,@acode
1841            ,@rcode
1842            (emit-template ,n-node ,n-block ,n-template ,n-args ,n-results
1843                           ,@(when info
1844                               `((list ,@info))))
1845            (values))))))
1846 \f
1847 ;;;; miscellaneous macros
1848
1849 ;;; SC-Case TN {({(SC-Name*) | SC-Name | T} Form*)}*
1850 ;;;
1851 ;;; Case off of TN's SC. The first clause containing TN's SC is
1852 ;;; evaluated, returning the values of the last form. A clause
1853 ;;; beginning with T specifies a default. If it appears, it must be
1854 ;;; last. If no default is specified, and no clause matches, then an
1855 ;;; error is signalled.
1856 (def!macro sc-case (tn &rest forms)
1857   (let ((n-sc (gensym))
1858         (n-tn (gensym)))
1859     (collect ((clauses))
1860       (do ((cases forms (rest cases)))
1861           ((null cases)
1862            (clauses `(t (error "unknown SC to SC-CASE for ~S:~%  ~S" ,n-tn
1863                                (sc-name (tn-sc ,n-tn))))))
1864         (let ((case (first cases)))
1865           (when (atom case)
1866             (error "illegal SC-CASE clause: ~S" case))
1867           (let ((head (first case)))
1868             (when (eq head t)
1869               (when (rest cases)
1870                 (error "T case is not last in SC-CASE."))
1871               (clauses `(t nil ,@(rest case)))
1872               (return))
1873             (clauses `((or ,@(mapcar (lambda (x)
1874                                        `(eql ,(meta-sc-number-or-lose x)
1875                                              ,n-sc))
1876                                      (if (atom head) (list head) head)))
1877                        nil ,@(rest case))))))
1878
1879       `(let* ((,n-tn ,tn)
1880               (,n-sc (sc-number (tn-sc ,n-tn))))
1881          (cond ,@(clauses))))))
1882
1883 ;;; Return true if TNs SC is any of the named SCs, false otherwise.
1884 (defmacro sc-is (tn &rest scs)
1885   (once-only ((n-sc `(sc-number (tn-sc ,tn))))
1886     `(or ,@(mapcar (lambda (x)
1887                      `(eql ,n-sc ,(meta-sc-number-or-lose x)))
1888                    scs))))
1889
1890 ;;; Iterate over the IR2 blocks in component, in emission order.
1891 (defmacro do-ir2-blocks ((block-var component &optional result)
1892                          &body forms)
1893   `(do ((,block-var (block-info (component-head ,component))
1894                     (ir2-block-next ,block-var)))
1895        ((null ,block-var) ,result)
1896      ,@forms))
1897
1898 ;;; Iterate over all the TNs live at some point, with the live set
1899 ;;; represented by a local conflicts bit-vector and the IR2-BLOCK
1900 ;;; containing the location.
1901 (defmacro do-live-tns ((tn-var live block &optional result) &body body)
1902   (let ((n-conf (gensym))
1903         (n-bod (gensym))
1904         (i (gensym))
1905         (ltns (gensym)))
1906     (once-only ((n-live live)
1907                 (n-block block))
1908       `(block nil
1909          (flet ((,n-bod (,tn-var) ,@body))
1910            ;; Do component-live TNs.
1911            (dolist (,tn-var (ir2-component-component-tns
1912                              (component-info
1913                               (block-component
1914                                (ir2-block-block ,n-block)))))
1915              (,n-bod ,tn-var))
1916
1917            (let ((,ltns (ir2-block-local-tns ,n-block)))
1918              ;; Do TNs always-live in this block and live :MORE TNs.
1919              (do ((,n-conf (ir2-block-global-tns ,n-block)
1920                            (global-conflicts-next-blockwise ,n-conf)))
1921                  ((null ,n-conf))
1922                (when (or (eq (global-conflicts-kind ,n-conf) :live)
1923                          (let ((,i (global-conflicts-number ,n-conf)))
1924                            (and (eq (svref ,ltns ,i) :more)
1925                                 (not (zerop (sbit ,n-live ,i))))))
1926                  (,n-bod (global-conflicts-tn ,n-conf))))
1927              ;; Do TNs locally live in the designated live set.
1928              (dotimes (,i (ir2-block-local-tn-count ,n-block) ,result)
1929                (unless (zerop (sbit ,n-live ,i))
1930                  (let ((,tn-var (svref ,ltns ,i)))
1931                    (when (and ,tn-var (not (eq ,tn-var :more)))
1932                      (,n-bod ,tn-var)))))))))))
1933
1934 ;;; Iterate over all the IR2 blocks in PHYSENV, in emit order.
1935 (defmacro do-physenv-ir2-blocks ((block-var physenv &optional result)
1936                                  &body body)
1937   (once-only ((n-physenv physenv))
1938     (once-only ((n-first `(lambda-block (physenv-lambda ,n-physenv))))
1939       (once-only ((n-tail `(block-info
1940                             (component-tail
1941                              (block-component ,n-first)))))
1942         `(do ((,block-var (block-info ,n-first)
1943                           (ir2-block-next ,block-var)))
1944              ((or (eq ,block-var ,n-tail)
1945                   (not (eq (ir2-block-physenv ,block-var) ,n-physenv)))
1946               ,result)
1947            ,@body)))))