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