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