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