0.8.16.16:
[sbcl.git] / src / compiler / macros.lisp
1 ;;;; miscellaneous types and macros used in writing the compiler
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!C")
13
14 (declaim (special *wild-type* *universal-type* *compiler-error-context*))
15
16 ;;; An INLINEP value describes how a function is called. The values
17 ;;; have these meanings:
18 ;;;     NIL     No declaration seen: do whatever you feel like, but don't 
19 ;;;             dump an inline expansion.
20 ;;; :NOTINLINE  NOTINLINE declaration seen: always do full function call.
21 ;;;    :INLINE  INLINE declaration seen: save expansion, expanding to it 
22 ;;;             if policy favors.
23 ;;; :MAYBE-INLINE
24 ;;;             Retain expansion, but only use it opportunistically.
25 (deftype inlinep () '(member :inline :maybe-inline :notinline nil))
26 \f
27 ;;;; source-hacking defining forms
28
29 ;;; Parse a DEFMACRO-style lambda-list, setting things up so that a
30 ;;; compiler error happens if the syntax is invalid.
31 ;;;
32 ;;; Define a function that converts a special form or other magical
33 ;;; thing into IR1. LAMBDA-LIST is a defmacro style lambda
34 ;;; list. START-VAR, NEXT-VAR and RESULT-VAR are bound to the start and
35 ;;; result continuations for the resulting IR1. KIND is the function
36 ;;; kind to associate with NAME.
37 (defmacro def-ir1-translator (name (lambda-list start-var next-var result-var)
38                               &body body)
39   (let ((fn-name (symbolicate "IR1-CONVERT-" name))
40         (n-form (gensym))
41         (n-env (gensym)))
42     (multiple-value-bind (body decls doc)
43         (parse-defmacro lambda-list n-form body name "special form"
44                         :environment n-env
45                         :error-fun 'compiler-error
46                         :wrap-block nil)
47       `(progn
48          (declaim (ftype (function (ctran ctran (or lvar null) t) (values))
49                          ,fn-name))
50          (defun ,fn-name (,start-var ,next-var ,result-var ,n-form
51                           &aux (,n-env *lexenv*))
52            (declare (ignorable ,start-var ,next-var ,result-var))
53            ,@decls
54            ,body
55            (values))
56          ,@(when doc
57              `((setf (fdocumentation ',name 'function) ,doc)))
58          ;; FIXME: Evidently "there can only be one!" -- we overwrite any
59          ;; other :IR1-CONVERT value. This deserves a warning, I think.
60          (setf (info :function :ir1-convert ',name) #',fn-name)
61          ;; FIXME: rename this to SPECIAL-OPERATOR, to update it to
62          ;; the 1990s?
63          (setf (info :function :kind ',name) :special-form)
64          ;; It's nice to do this for error checking in the target
65          ;; SBCL, but it's not nice to do this when we're running in
66          ;; the cross-compilation host Lisp, which owns the
67          ;; SYMBOL-FUNCTION of its COMMON-LISP symbols.
68          #-sb-xc-host
69          (let ((fun (lambda (&rest rest)
70                       (declare (ignore rest))
71                       (error 'special-form-function :name ',name))))
72            (setf (%simple-fun-arglist fun) ',lambda-list)
73            (setf (symbol-function ',name) fun))
74          ',name))))
75
76 ;;; (This is similar to DEF-IR1-TRANSLATOR, except that we pass if the
77 ;;; syntax is invalid.)
78 ;;;
79 ;;; Define a macro-like source-to-source transformation for the
80 ;;; function NAME. A source transform may "pass" by returning a
81 ;;; non-nil second value. If the transform passes, then the form is
82 ;;; converted as a normal function call. If the supplied arguments are
83 ;;; not compatible with the specified LAMBDA-LIST, then the transform
84 ;;; automatically passes.
85 ;;;
86 ;;; Source transforms may only be defined for functions. Source
87 ;;; transformation is not attempted if the function is declared
88 ;;; NOTINLINE. Source transforms should not examine their arguments.
89 ;;; If it matters how the function is used, then DEFTRANSFORM should
90 ;;; be used to define an IR1 transformation.
91 ;;;
92 ;;; If the desirability of the transformation depends on the current
93 ;;; OPTIMIZE parameters, then the POLICY macro should be used to
94 ;;; determine when to pass.
95 (defmacro source-transform-lambda (lambda-list &body body)
96   (let ((n-form (gensym))
97         (n-env (gensym))
98         (name (gensym)))
99     (multiple-value-bind (body decls)
100         (parse-defmacro lambda-list n-form body "source transform" "form"
101                         :environment n-env
102                         :error-fun `(lambda (&rest stuff)
103                                       (declare (ignore stuff))
104                                       (return-from ,name
105                                         (values nil t)))
106                         :wrap-block nil)
107       `(lambda (,n-form &aux (,n-env *lexenv*))
108          ,@decls
109          (block ,name
110            ,body)))))
111 (defmacro define-source-transform (name lambda-list &body body)
112   `(setf (info :function :source-transform ',name)
113          (source-transform-lambda ,lambda-list ,@body)))
114 \f
115 ;;;; boolean attribute utilities
116 ;;;;
117 ;;;; We need to maintain various sets of boolean attributes for known
118 ;;;; functions and VOPs. To save space and allow for quick set
119 ;;;; operations, we represent the attributes as bits in a fixnum.
120
121 (deftype attributes () 'fixnum)
122
123 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
124
125 ;;; Given a list of attribute names and an alist that translates them
126 ;;; to masks, return the OR of the masks.
127 (defun compute-attribute-mask (names alist)
128   (collect ((res 0 logior))
129     (dolist (name names)
130       (let ((mask (cdr (assoc name alist))))
131         (unless mask
132           (error "unknown attribute name: ~S" name))
133         (res mask)))
134     (res)))
135
136 ) ; EVAL-WHEN
137
138 ;;; Define a new class of boolean attributes, with the attributes
139 ;;; having the specified ATTRIBUTE-NAMES. NAME is the name of the
140 ;;; class, which is used to generate some macros to manipulate sets of
141 ;;; the attributes:
142 ;;;
143 ;;;    NAME-attributep attributes attribute-name*
144 ;;;      Return true if one of the named attributes is present, false
145 ;;;      otherwise. When set with SETF, updates the place Attributes
146 ;;;      setting or clearing the specified attributes.
147 ;;;
148 ;;;    NAME-attributes attribute-name*
149 ;;;      Return a set of the named attributes.
150 #-sb-xc
151 (progn
152   (def!macro !def-boolean-attribute (name &rest attribute-names)
153
154     (let ((translations-name (symbolicate "*" name "-ATTRIBUTE-TRANSLATIONS*"))
155           (test-name (symbolicate name "-ATTRIBUTEP"))
156           (decoder-name (symbolicate "DECODE-" name "-ATTRIBUTES")))
157       (collect ((alist))
158         (do ((mask 1 (ash mask 1))
159              (names attribute-names (cdr names)))
160             ((null names))
161           (alist (cons (car names) mask)))
162         `(progn
163            (eval-when (:compile-toplevel :load-toplevel :execute)
164              (defparameter ,translations-name ',(alist)))
165            (defmacro ,(symbolicate name "-ATTRIBUTES") (&rest attribute-names)
166              "Automagically generated boolean attribute creation function.
167   See !DEF-BOOLEAN-ATTRIBUTE."
168              (compute-attribute-mask attribute-names ,translations-name))
169            (defmacro ,test-name (attributes &rest attribute-names)
170              "Automagically generated boolean attribute test function.
171   See !DEF-BOOLEAN-ATTRIBUTE."
172              `(logtest ,(compute-attribute-mask attribute-names
173                                                 ,translations-name)
174                        (the attributes ,attributes)))
175            ;; This definition transforms strangely under UNCROSS, in a
176            ;; way that DEF!MACRO doesn't understand, so we delegate it
177            ;; to a submacro then define the submacro differently when
178            ;; building the xc and when building the target compiler.
179            (!def-boolean-attribute-setter ,test-name
180                                           ,translations-name
181                                           ,@attribute-names)
182            (defun ,decoder-name (attributes)
183              (loop for (name . mask) in ,translations-name
184                    when (logtest mask attributes)
185                      collect name))))))
186
187   ;; It seems to be difficult to express in DEF!MACRO machinery what
188   ;; to do with target-vs-host GET-SETF-EXPANSION in here, so we just
189   ;; hack it by hand, passing a different GET-SETF-EXPANSION-FUN-NAME
190   ;; in the host DEFMACRO and target DEFMACRO-MUNDANELY cases.
191   (defun guts-of-!def-boolean-attribute-setter (test-name
192                                                 translations-name
193                                                 attribute-names
194                                                 get-setf-expansion-fun-name)
195     `(define-setf-expander ,test-name (place &rest attributes
196                                              &environment env)
197        "Automagically generated boolean attribute setter. See
198  !DEF-BOOLEAN-ATTRIBUTE."
199        #-sb-xc-host (declare (type sb!c::lexenv env))
200        ;; FIXME: It would be better if &ENVIRONMENT arguments were
201        ;; automatically declared to have type LEXENV by the
202        ;; hairy-argument-handling code.
203        (multiple-value-bind (temps values stores set get)
204            (,get-setf-expansion-fun-name place env)
205          (when (cdr stores)
206            (error "multiple store variables for ~S" place))
207          (let ((newval (gensym))
208                (n-place (gensym))
209                (mask (compute-attribute-mask attributes ,translations-name)))
210            (values `(,@temps ,n-place)
211                    `(,@values ,get)
212                    `(,newval)
213                    `(let ((,(first stores)
214                            (if ,newval
215                                (logior ,n-place ,mask)
216                                (logand ,n-place ,(lognot mask)))))
217                       ,set
218                       ,newval)
219                    `(,',test-name ,n-place ,@attributes))))))
220   ;; We define the host version here, and the just-like-it-but-different
221   ;; target version later, after DEFMACRO-MUNDANELY has been defined.
222   (defmacro !def-boolean-attribute-setter (test-name
223                                            translations-name
224                                            &rest attribute-names)
225     (guts-of-!def-boolean-attribute-setter test-name
226                                            translations-name
227                                            attribute-names
228                                            'get-setf-expansion)))
229
230 ;;; And now for some gratuitous pseudo-abstraction...
231 ;;;
232 ;;; ATTRIBUTES-UNION 
233 ;;;   Return the union of all the sets of boolean attributes which are its
234 ;;;   arguments.
235 ;;; ATTRIBUTES-INTERSECTION
236 ;;;   Return the intersection of all the sets of boolean attributes which
237 ;;;   are its arguments.
238 ;;; ATTRIBUTES
239 ;;;   True if the attributes present in ATTR1 are identical to
240 ;;;   those in ATTR2.
241 (defmacro attributes-union (&rest attributes)
242   `(the attributes
243         (logior ,@(mapcar (lambda (x) `(the attributes ,x)) attributes))))
244 (defmacro attributes-intersection (&rest attributes)
245   `(the attributes
246         (logand ,@(mapcar (lambda (x) `(the attributes ,x)) attributes))))
247 (declaim (ftype (function (attributes attributes) boolean) attributes=))
248 #!-sb-fluid (declaim (inline attributes=))
249 (defun attributes= (attr1 attr2)
250   (eql attr1 attr2))
251 \f
252 ;;;; lambda-list parsing utilities
253 ;;;;
254 ;;;; IR1 transforms, optimizers and type inferencers need to be able
255 ;;;; to parse the IR1 representation of a function call using a
256 ;;;; standard function lambda-list.
257
258 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
259
260 ;;; Given a DEFTRANSFORM-style lambda-list, generate code that parses
261 ;;; the arguments of a combination with respect to that
262 ;;; lambda-list. BODY is the list of forms which are to be
263 ;;; evaluated within the bindings. ARGS is the variable that holds
264 ;;; list of argument lvars. ERROR-FORM is a form which is evaluated
265 ;;; when the syntax of the supplied arguments is incorrect or a
266 ;;; non-constant argument keyword is supplied. Defaults and other gunk
267 ;;; are ignored. The second value is a list of all the arguments
268 ;;; bound. We make the variables IGNORABLE so that we don't have to
269 ;;; manually declare them IGNORE if their only purpose is to make the
270 ;;; syntax work.
271 (defun parse-deftransform (lambda-list body args error-form)
272   (multiple-value-bind (req opt restp rest keyp keys allowp)
273       (parse-lambda-list lambda-list)
274     (let* ((min-args (length req))
275            (max-args (+ min-args (length opt)))
276            (n-keys (gensym)))
277       (collect ((binds)
278                 (vars)
279                 (pos 0 +)
280                 (keywords))
281         (dolist (arg req)
282           (vars arg)
283           (binds `(,arg (nth ,(pos) ,args)))
284           (pos 1))
285
286         (dolist (arg opt)
287           (let ((var (if (atom arg) arg (first  arg))))
288             (vars var)
289             (binds `(,var (nth ,(pos) ,args)))
290             (pos 1)))
291
292         (when restp
293           (vars rest)
294           (binds `(,rest (nthcdr ,(pos) ,args))))
295
296         (dolist (spec keys)
297           (if (or (atom spec) (atom (first spec)))
298               (let* ((var (if (atom spec) spec (first spec)))
299                      (key (keywordicate var)))
300                 (vars var)
301                 (binds `(,var (find-keyword-lvar ,n-keys ,key)))
302                 (keywords key))
303               (let* ((head (first spec))
304                      (var (second head))
305                      (key (first head)))
306                 (vars var)
307                 (binds `(,var (find-keyword-lvar ,n-keys ,key)))
308                 (keywords key))))
309
310         (let ((n-length (gensym))
311               (limited-legal (not (or restp keyp))))
312           (values
313            `(let ((,n-length (length ,args))
314                   ,@(when keyp `((,n-keys (nthcdr ,(pos) ,args)))))
315               (unless (and
316                        ;; FIXME: should be PROPER-LIST-OF-LENGTH-P
317                        ,(if limited-legal
318                             `(<= ,min-args ,n-length ,max-args)
319                             `(<= ,min-args ,n-length))
320                        ,@(when keyp
321                            (if allowp
322                                `((check-key-args-constant ,n-keys))
323                                `((check-transform-keys ,n-keys ',(keywords))))))
324                 ,error-form)
325               (let ,(binds)
326                 (declare (ignorable ,@(vars)))
327                 ,@body))
328            (vars)))))))
329
330 ) ; EVAL-WHEN
331 \f
332 ;;;; DEFTRANSFORM
333
334 ;;; Define an IR1 transformation for NAME. An IR1 transformation
335 ;;; computes a lambda that replaces the function variable reference
336 ;;; for the call. A transform may pass (decide not to transform the
337 ;;; call) by calling the GIVE-UP-IR1-TRANSFORM function. LAMBDA-LIST
338 ;;; both determines how the current call is parsed and specifies the
339 ;;; LAMBDA-LIST for the resulting lambda.
340 ;;;
341 ;;; We parse the call and bind each of the lambda-list variables to
342 ;;; the lvar which represents the value of the argument. When parsing
343 ;;; the call, we ignore the defaults, and always bind the variables
344 ;;; for unsupplied arguments to NIL. If a required argument is
345 ;;; missing, an unknown keyword is supplied, or an argument keyword is
346 ;;; not a constant, then the transform automatically passes. The
347 ;;; DECLARATIONS apply to the bindings made by DEFTRANSFORM at
348 ;;; transformation time, rather than to the variables of the resulting
349 ;;; lambda. Bound-but-not-referenced warnings are suppressed for the
350 ;;; lambda-list variables. The DOC-STRING is used when printing
351 ;;; efficiency notes about the defined transform.
352 ;;;
353 ;;; Normally, the body evaluates to a form which becomes the body of
354 ;;; an automatically constructed lambda. We make LAMBDA-LIST the
355 ;;; lambda-list for the lambda, and automatically insert declarations
356 ;;; of the argument and result types. If the second value of the body
357 ;;; is non-null, then it is a list of declarations which are to be
358 ;;; inserted at the head of the lambda. Automatic lambda generation
359 ;;; may be inhibited by explicitly returning a lambda from the body.
360 ;;;
361 ;;; The ARG-TYPES and RESULT-TYPE are used to create a function type
362 ;;; which the call must satisfy before transformation is attempted.
363 ;;; The function type specifier is constructed by wrapping (FUNCTION
364 ;;; ...) around these values, so the lack of a restriction may be
365 ;;; specified by omitting the argument or supplying *. The argument
366 ;;; syntax specified in the ARG-TYPES need not be the same as that in
367 ;;; the LAMBDA-LIST, but the transform will never happen if the
368 ;;; syntaxes can't be satisfied simultaneously. If there is an
369 ;;; existing transform for the same function that has the same type,
370 ;;; then it is replaced with the new definition.
371 ;;;
372 ;;; These are the legal keyword options:
373 ;;;   :RESULT - A variable which is bound to the result lvar.
374 ;;;   :NODE   - A variable which is bound to the combination node for the call.
375 ;;;   :POLICY - A form which is supplied to the POLICY macro to determine
376 ;;;             whether this transformation is appropriate. If the result
377 ;;;             is false, then the transform automatically gives up.
378 ;;;   :EVAL-NAME
379 ;;;           - The name and argument/result types are actually forms to be
380 ;;;             evaluated. Useful for getting closures that transform similar
381 ;;;             functions.
382 ;;;   :DEFUN-ONLY
383 ;;;           - Don't actually instantiate a transform, instead just DEFUN
384 ;;;             Name with the specified transform definition function. This
385 ;;;             may be later instantiated with %DEFTRANSFORM.
386 ;;;   :IMPORTANT
387 ;;;           - If supplied and non-NIL, note this transform as ``important,''
388 ;;;             which means efficiency notes will be generated when this
389 ;;;             transform fails even if INHIBIT-WARNINGS=SPEED (but not if
390 ;;;             INHIBIT-WARNINGS>SPEED).
391 (defmacro deftransform (name (lambda-list &optional (arg-types '*)
392                                           (result-type '*)
393                                           &key result policy node defun-only
394                                           eval-name important)
395                              &body body-decls-doc)
396   (when (and eval-name defun-only)
397     (error "can't specify both DEFUN-ONLY and EVAL-NAME"))
398   (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
399     (let ((n-args (gensym))
400           (n-node (or node (gensym)))
401           (n-decls (gensym))
402           (n-lambda (gensym))
403           (decls-body `(,@decls ,@body)))
404       (multiple-value-bind (parsed-form vars)
405           (parse-deftransform lambda-list
406                               (if policy
407                                   `((unless (policy ,n-node ,policy)
408                                       (give-up-ir1-transform))
409                                     ,@decls-body)
410                                   body)
411                               n-args
412                               '(give-up-ir1-transform))
413         (let ((stuff
414                `((,n-node)
415                  (let* ((,n-args (basic-combination-args ,n-node))
416                         ,@(when result
417                             `((,result (node-lvar ,n-node)))))
418                    (multiple-value-bind (,n-lambda ,n-decls)
419                        ,parsed-form
420                      (if (and (consp ,n-lambda) (eq (car ,n-lambda) 'lambda))
421                          ,n-lambda
422                        `(lambda ,',lambda-list
423                           (declare (ignorable ,@',vars))
424                           ,@,n-decls
425                           ,,n-lambda)))))))
426           (if defun-only
427               `(defun ,name ,@(when doc `(,doc)) ,@stuff)
428               `(%deftransform
429                 ,(if eval-name name `',name)
430                 ,(if eval-name
431                      ``(function ,,arg-types ,,result-type)
432                      `'(function ,arg-types ,result-type))
433                 (lambda ,@stuff)
434                 ,doc
435                 ,(if important t nil))))))))
436 \f
437 ;;;; DEFKNOWN and DEFOPTIMIZER
438
439 ;;; This macro should be the way that all implementation independent
440 ;;; information about functions is made known to the compiler.
441 ;;;
442 ;;; FIXME: The comment above suggests that perhaps some of my added
443 ;;; FTYPE declarations are in poor taste. Should I change my
444 ;;; declarations, or change the comment, or what?
445 ;;;
446 ;;; FIXME: DEFKNOWN is needed only at build-the-system time. Figure
447 ;;; out some way to keep it from appearing in the target system.
448 ;;;
449 ;;; Declare the function NAME to be a known function. We construct a
450 ;;; type specifier for the function by wrapping (FUNCTION ...) around
451 ;;; the ARG-TYPES and RESULT-TYPE. ATTRIBUTES is an unevaluated list
452 ;;; of boolean attributes of the function. See their description in
453 ;;; (!DEF-BOOLEAN-ATTRIBUTE IR1). NAME may also be a list of names, in
454 ;;; which case the same information is given to all the names. The
455 ;;; keywords specify the initial values for various optimizers that
456 ;;; the function might have.
457 (defmacro defknown (name arg-types result-type &optional (attributes '(any))
458                     &rest keys)
459   (when (and (intersection attributes '(any call unwind))
460              (intersection attributes '(movable)))
461     (error "function cannot have both good and bad attributes: ~S" attributes))
462
463   (when (member 'any attributes)
464     (setq attributes (union '(call unsafe unwind) attributes)))
465   (when (member 'flushable attributes)
466     (pushnew 'unsafely-flushable attributes))
467
468   `(%defknown ',(if (and (consp name)
469                          (not (legal-fun-name-p name)))
470                     name
471                     (list name))
472               '(sfunction ,arg-types ,result-type)
473               (ir1-attributes ,@attributes)
474               ,@keys))
475
476 ;;; Create a function which parses combination args according to WHAT
477 ;;; and LAMBDA-LIST, where WHAT is either a function name or a list
478 ;;; (FUN-NAME KIND) and does some KIND of optimization.
479 ;;;
480 ;;; The FUN-NAME must name a known function. LAMBDA-LIST is used
481 ;;; to parse the arguments to the combination as in DEFTRANSFORM. If
482 ;;; the argument syntax is invalid or there are non-constant keys,
483 ;;; then we simply return NIL.
484 ;;;
485 ;;; The function is DEFUN'ed as FUNCTION-KIND-OPTIMIZER. Possible
486 ;;; kinds are DERIVE-TYPE, OPTIMIZER, LTN-ANNOTATE and IR2-CONVERT. If
487 ;;; a symbol is specified instead of a (FUNCTION KIND) list, then we
488 ;;; just do a DEFUN with the symbol as its name, and don't do anything
489 ;;; with the definition. This is useful for creating optimizers to be
490 ;;; passed by name to DEFKNOWN.
491 ;;;
492 ;;; If supplied, NODE-VAR is bound to the combination node being
493 ;;; optimized. If additional VARS are supplied, then they are used as
494 ;;; the rest of the optimizer function's lambda-list. LTN-ANNOTATE
495 ;;; methods are passed an additional POLICY argument, and IR2-CONVERT
496 ;;; methods are passed an additional IR2-BLOCK argument.
497 (defmacro defoptimizer (what (lambda-list &optional (n-node (gensym))
498                                           &rest vars)
499                              &body body)
500   (let ((name (if (symbolp what) what
501                   (symbolicate (first what) "-" (second what) "-OPTIMIZER"))))
502
503     (let ((n-args (gensym)))
504       `(progn
505         (defun ,name (,n-node ,@vars)
506           (declare (ignorable ,@vars))
507           (let ((,n-args (basic-combination-args ,n-node)))
508             ,(parse-deftransform lambda-list body n-args
509                                  `(return-from ,name nil))))
510         ,@(when (consp what)
511             `((setf (,(let ((*package* (symbol-package 'sb!c::fun-info)))
512                         (symbolicate "FUN-INFO-" (second what)))
513                      (fun-info-or-lose ',(first what)))
514                     #',name)))))))
515 \f
516 ;;;; IR groveling macros
517
518 ;;; Iterate over the blocks in a component, binding BLOCK-VAR to each
519 ;;; block in turn. The value of ENDS determines whether to iterate
520 ;;; over dummy head and tail blocks:
521 ;;;    NIL  -- Skip Head and Tail (the default)
522 ;;;   :HEAD -- Do head but skip tail
523 ;;;   :TAIL -- Do tail but skip head
524 ;;;   :BOTH -- Do both head and tail
525 ;;;
526 ;;; If supplied, RESULT-FORM is the value to return.
527 (defmacro do-blocks ((block-var component &optional ends result) &body body)
528   (unless (member ends '(nil :head :tail :both))
529     (error "losing ENDS value: ~S" ends))
530   (let ((n-component (gensym))
531         (n-tail (gensym)))
532     `(let* ((,n-component ,component)
533             (,n-tail ,(if (member ends '(:both :tail))
534                           nil
535                           `(component-tail ,n-component))))
536        (do ((,block-var ,(if (member ends '(:both :head))
537                              `(component-head ,n-component)
538                              `(block-next (component-head ,n-component)))
539                         (block-next ,block-var)))
540            ((eq ,block-var ,n-tail) ,result)
541          ,@body))))
542 ;;; like DO-BLOCKS, only iterating over the blocks in reverse order
543 (defmacro do-blocks-backwards ((block-var component &optional ends result) &body body)
544   (unless (member ends '(nil :head :tail :both))
545     (error "losing ENDS value: ~S" ends))
546   (let ((n-component (gensym))
547         (n-head (gensym)))
548     `(let* ((,n-component ,component)
549             (,n-head ,(if (member ends '(:both :head))
550                           nil
551                           `(component-head ,n-component))))
552        (do ((,block-var ,(if (member ends '(:both :tail))
553                              `(component-tail ,n-component)
554                              `(block-prev (component-tail ,n-component)))
555                         (block-prev ,block-var)))
556            ((eq ,block-var ,n-head) ,result)
557          ,@body))))
558
559 ;;; Iterate over the uses of LVAR, binding NODE to each one
560 ;;; successively.
561 ;;;
562 ;;; XXX Could change it not to replicate the code someday perhaps...
563 (defmacro do-uses ((node-var lvar &optional result) &body body)
564   (with-unique-names (uses)
565     `(let ((,uses (lvar-uses ,lvar)))
566        (if (listp ,uses)
567            (dolist (,node-var ,uses ,result)
568              ,@body)
569            (block nil
570              (let ((,node-var ,uses))
571                ,@body))))))
572
573 ;;; Iterate over the nodes in BLOCK, binding NODE-VAR to the each node
574 ;;; and LVAR-VAR to the node's LVAR. The only keyword option is
575 ;;; RESTART-P, which causes iteration to be restarted when a node is
576 ;;; deleted out from under us. (If not supplied, this is an error.)
577 ;;;
578 ;;; In the forward case, we terminate when NODE does not have NEXT, so
579 ;;; that we do not have to worry about our termination condition being
580 ;;; changed when new code is added during the iteration. In the
581 ;;; backward case, we do NODE-PREV before evaluating the body so that
582 ;;; we can keep going when the current node is deleted.
583 ;;;
584 ;;; When RESTART-P is supplied to DO-NODES, we start iterating over
585 ;;; again at the beginning of the block when we run into a ctran whose
586 ;;; block differs from the one we are trying to iterate over, either
587 ;;; because the block was split, or because a node was deleted out
588 ;;; from under us (hence its block is NIL.) If the block start is
589 ;;; deleted, we just punt. With RESTART-P, we are also more careful
590 ;;; about termination, re-indirecting the BLOCK-LAST each time.
591 (defmacro do-nodes ((node-var lvar-var block &key restart-p)
592                     &body body)
593   (with-unique-names (n-block n-start)
594     `(do* ((,n-block ,block)
595            (,n-start (block-start ,n-block))
596
597            (,node-var (ctran-next ,n-start)
598                       ,(if restart-p
599                            `(let ((next (node-next ,node-var)))
600                               (cond
601                                 ((not next)
602                                  (return))
603                                 ((eq (ctran-block next) ,n-block)
604                                  (ctran-next next))
605                                 (t
606                                  (let ((start (block-start ,n-block)))
607                                    (unless (eq (ctran-kind start)
608                                                :block-start)
609                                      (return nil))
610                                    (ctran-next start)))))
611                            `(acond ((node-next ,node-var)
612                                     (ctran-next it))
613                                    (t (return)))))
614            ,@(when lvar-var
615                    `((,lvar-var (when (valued-node-p ,node-var)
616                                   (node-lvar ,node-var))
617                                 (when (valued-node-p ,node-var)
618                                   (node-lvar ,node-var))))))
619           (nil)
620        ,@body
621        ,@(when restart-p
622            `((when (block-delete-p ,n-block)
623                (return)))))))
624
625 ;;; Like DO-NODES, only iterating in reverse order. Should be careful
626 ;;; with block being split under us.
627 (defmacro do-nodes-backwards ((node-var lvar block &key restart-p) &body body)
628   (let ((n-block (gensym))
629         (n-prev (gensym)))
630     `(loop with ,n-block = ,block
631            for ,node-var = (block-last ,n-block) then
632                            ,(if restart-p
633                                 `(if (eq ,n-block (ctran-block ,n-prev))
634                                      (ctran-use ,n-prev)
635                                      (block-last ,n-block))
636                                 `(ctran-use ,n-prev))
637            for ,n-prev = (when ,node-var (node-prev ,node-var))
638            and ,lvar = (when (and ,node-var (valued-node-p ,node-var))
639                          (node-lvar ,node-var))
640            while ,(if restart-p
641                       `(and ,node-var (not (block-to-be-deleted-p ,n-block)))
642                       node-var)
643            do (progn
644                 ,@body))))
645
646 (defmacro do-nodes-carefully ((node-var block) &body body)
647   (with-unique-names (n-block n-ctran)
648     `(loop with ,n-block = ,block
649            for ,n-ctran = (block-start ,n-block) then (node-next ,node-var)
650            for ,node-var = (and ,n-ctran (ctran-next ,n-ctran))
651            while ,node-var
652            do (progn ,@body))))
653
654 ;;; Bind the IR1 context variables to the values associated with NODE,
655 ;;; so that new, extra IR1 conversion related to NODE can be done
656 ;;; after the original conversion pass has finished.
657 (defmacro with-ir1-environment-from-node (node &rest forms)
658   `(flet ((closure-needing-ir1-environment-from-node ()
659             ,@forms))
660      (%with-ir1-environment-from-node
661       ,node
662       #'closure-needing-ir1-environment-from-node)))
663 (defun %with-ir1-environment-from-node (node fun)
664   (declare (type node node) (type function fun))
665   (let ((*current-component* (node-component node))
666         (*lexenv* (node-lexenv node))
667         (*current-path* (node-source-path node)))
668     (aver-live-component *current-component*)
669     (funcall fun)))
670
671 ;;; Bind the hashtables used for keeping track of global variables,
672 ;;; functions, etc. Also establish condition handlers.
673 (defmacro with-ir1-namespace (&body forms)
674   `(let ((*free-vars* (make-hash-table :test 'eq))
675          (*free-funs* (make-hash-table :test 'equal))
676          (*constants* (make-hash-table :test 'equal))
677          (*source-paths* (make-hash-table :test 'eq)))
678      (handler-bind ((compiler-error #'compiler-error-handler)
679                     (style-warning #'compiler-style-warning-handler)
680                     (warning #'compiler-warning-handler))
681        ,@forms)))
682
683 ;;; Look up NAME in the lexical environment namespace designated by
684 ;;; SLOT, returning the <value, T>, or <NIL, NIL> if no entry. The
685 ;;; :TEST keyword may be used to determine the name equality
686 ;;; predicate.
687 (defmacro lexenv-find (name slot &key test)
688   (once-only ((n-res `(assoc ,name (,(let ((*package* (symbol-package 'lexenv-funs)))
689                                           (symbolicate "LEXENV-" slot))
690                                      *lexenv*)
691                              :test ,(or test '#'eq))))
692     `(if ,n-res
693          (values (cdr ,n-res) t)
694          (values nil nil))))
695
696 (defmacro with-component-last-block ((component block) &body body)
697   (with-unique-names (old-last-block)
698     (once-only ((component component)
699                 (block block))
700       `(let ((,old-last-block (component-last-block ,component)))
701          (unwind-protect
702               (progn (setf (component-last-block ,component)
703                            ,block)
704                      ,@body)
705            (setf (component-last-block ,component)
706                  ,old-last-block))))))
707
708 \f
709 ;;;; the EVENT statistics/trace utility
710
711 ;;; FIXME: This seems to be useful for troubleshooting and
712 ;;; experimentation, not for ordinary use, so it should probably
713 ;;; become conditional on SB-SHOW.
714
715 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
716
717 (defstruct (event-info (:copier nil))
718   ;; The name of this event.
719   (name (missing-arg) :type symbol)
720   ;; The string rescribing this event.
721   (description (missing-arg) :type string)
722   ;; The name of the variable we stash this in.
723   (var (missing-arg) :type symbol)
724   ;; The number of times this event has happened.
725   (count 0 :type fixnum)
726   ;; The level of significance of this event.
727   (level (missing-arg) :type unsigned-byte)
728   ;; If true, a function that gets called with the node that the event
729   ;; happened to.
730   (action nil :type (or function null)))
731
732 ;;; A hashtable from event names to event-info structures.
733 (defvar *event-info* (make-hash-table :test 'eq))
734
735 ;;; Return the event info for Name or die trying.
736 (declaim (ftype (function (t) event-info) event-info-or-lose))
737 (defun event-info-or-lose (name)
738   (let ((res (gethash name *event-info*)))
739     (unless res
740       (error "~S is not the name of an event." name))
741     res))
742
743 ) ; EVAL-WHEN
744
745 ;;; Return the number of times that EVENT has happened.
746 (declaim (ftype (function (symbol) fixnum) event-count))
747 (defun event-count (name)
748   (event-info-count (event-info-or-lose name)))
749
750 ;;; Return the function that is called when Event happens. If this is
751 ;;; null, there is no action. The function is passed the node to which
752 ;;; the event happened, or NIL if there is no relevant node. This may
753 ;;; be set with SETF.
754 (declaim (ftype (function (symbol) (or function null)) event-action))
755 (defun event-action (name)
756   (event-info-action (event-info-or-lose name)))
757 (declaim (ftype (function (symbol (or function null)) (or function null))
758                 %set-event-action))
759 (defun %set-event-action (name new-value)
760   (setf (event-info-action (event-info-or-lose name))
761         new-value))
762 (defsetf event-action %set-event-action)
763
764 ;;; Return the non-negative integer which represents the level of
765 ;;; significance of the event Name. This is used to determine whether
766 ;;; to print a message when the event happens. This may be set with
767 ;;; SETF.
768 (declaim (ftype (function (symbol) unsigned-byte) event-level))
769 (defun event-level (name)
770   (event-info-level (event-info-or-lose name)))
771 (declaim (ftype (function (symbol unsigned-byte) unsigned-byte) %set-event-level))
772 (defun %set-event-level (name new-value)
773   (setf (event-info-level (event-info-or-lose name))
774         new-value))
775 (defsetf event-level %set-event-level)
776
777 ;;; Define a new kind of event. NAME is a symbol which names the event
778 ;;; and DESCRIPTION is a string which describes the event. Level
779 ;;; (default 0) is the level of significance associated with this
780 ;;; event; it is used to determine whether to print a Note when the
781 ;;; event happens.
782 (defmacro defevent (name description &optional (level 0))
783   (let ((var-name (symbolicate "*" name "-EVENT-INFO*")))
784     `(eval-when (:compile-toplevel :load-toplevel :execute)
785        (defvar ,var-name
786          (make-event-info :name ',name
787                           :description ',description
788                           :var ',var-name
789                           :level ,level))
790        (setf (gethash ',name *event-info*) ,var-name)
791        ',name)))
792
793 ;;; the lowest level of event that will print a note when it occurs
794 (declaim (type unsigned-byte *event-note-threshold*))
795 (defvar *event-note-threshold* 1)
796
797 ;;; Note that the event with the specified NAME has happened. NODE is
798 ;;; evaluated to determine the node to which the event happened.
799 (defmacro event (name &optional node)
800   ;; Increment the counter and do any action. Mumble about the event if
801   ;; policy indicates.
802   `(%event ,(event-info-var (event-info-or-lose name)) ,node))
803
804 ;;; Print a listing of events and their counts, sorted by the count.
805 ;;; Events that happened fewer than Min-Count times will not be
806 ;;; printed. Stream is the stream to write to.
807 (declaim (ftype (function (&optional unsigned-byte stream) (values)) event-statistics))
808 (defun event-statistics (&optional (min-count 1) (stream *standard-output*))
809   (collect ((info))
810     (maphash (lambda (k v)
811                (declare (ignore k))
812                (when (>= (event-info-count v) min-count)
813                  (info v)))
814              *event-info*)
815     (dolist (event (sort (info) #'> :key #'event-info-count))
816       (format stream "~6D: ~A~%" (event-info-count event)
817               (event-info-description event)))
818     (values))
819   (values))
820
821 (declaim (ftype (function nil (values)) clear-event-statistics))
822 (defun clear-event-statistics ()
823   (maphash (lambda (k v)
824              (declare (ignore k))
825              (setf (event-info-count v) 0))
826            *event-info*)
827   (values))
828 \f
829 ;;;; functions on directly-linked lists (linked through specialized
830 ;;;; NEXT operations)
831
832 #!-sb-fluid (declaim (inline find-in position-in))
833
834 ;;; Find ELEMENT in a null-terminated LIST linked by the accessor
835 ;;; function NEXT. KEY, TEST and TEST-NOT are the same as for generic
836 ;;; sequence functions.
837 (defun find-in (next
838                 element
839                 list
840                 &key
841                 (key #'identity)
842                 (test #'eql test-p)
843                 (test-not #'eql not-p))
844   (declare (type function next key test test-not))
845   (when (and test-p not-p)
846     (error "It's silly to supply both :TEST and :TEST-NOT arguments."))
847   (if not-p
848       (do ((current list (funcall next current)))
849           ((null current) nil)
850         (unless (funcall test-not (funcall key current) element)
851           (return current)))
852       (do ((current list (funcall next current)))
853           ((null current) nil)
854         (when (funcall test (funcall key current) element)
855           (return current)))))
856
857 ;;; Return the position of ELEMENT (or NIL if absent) in a
858 ;;; null-terminated LIST linked by the accessor function NEXT. KEY,
859 ;;; TEST and TEST-NOT are the same as for generic sequence functions.
860 (defun position-in (next
861                     element
862                     list
863                     &key
864                     (key #'identity)
865                     (test #'eql test-p)
866                     (test-not #'eql not-p))
867   (declare (type function next key test test-not))
868   (when (and test-p not-p)
869     (error "It's silly to supply both :TEST and :TEST-NOT arguments."))
870   (if not-p
871       (do ((current list (funcall next current))
872            (i 0 (1+ i)))
873           ((null current) nil)
874         (unless (funcall test-not (funcall key current) element)
875           (return i)))
876       (do ((current list (funcall next current))
877            (i 0 (1+ i)))
878           ((null current) nil)
879         (when (funcall test (funcall key current) element)
880           (return i)))))
881
882
883 ;;; KLUDGE: This is expanded out twice, by cut-and-paste, in a
884 ;;;   (DEF!MACRO FOO (..) .. CL:GET-SETF-EXPANSION ..)
885 ;;;   #+SB-XC-HOST
886 ;;;   (SB!XC:DEFMACRO FOO (..) .. SB!XC:GET-SETF-EXPANSION ..)
887 ;;; arrangement, in order to get it to work in cross-compilation. This
888 ;;; duplication should be removed, perhaps by rewriting the macro in a more
889 ;;; cross-compiler-friendly way, or perhaps just by using some (MACROLET ((FROB
890 ;;; ..)) .. FROB .. FROB) form, or perhaps by completely eliminating this macro
891 ;;; and its partner PUSH-IN, but I don't want to do it now, because the system
892 ;;; isn't running yet, so it'd be too hard to check that my changes were
893 ;;; correct -- WHN 19990806
894 (def!macro deletef-in (next place item &environment env)
895   (multiple-value-bind (temps vals stores store access)
896       (get-setf-expansion place env)
897     (when (cdr stores)
898       (error "multiple store variables for ~S" place))
899     (let ((n-item (gensym))
900           (n-place (gensym))
901           (n-current (gensym))
902           (n-prev (gensym)))
903       `(let* (,@(mapcar #'list temps vals)
904               (,n-place ,access)
905               (,n-item ,item))
906          (if (eq ,n-place ,n-item)
907              (let ((,(first stores) (,next ,n-place)))
908                ,store)
909              (do ((,n-prev ,n-place ,n-current)
910                   (,n-current (,next ,n-place)
911                               (,next ,n-current)))
912                  ((eq ,n-current ,n-item)
913                   (setf (,next ,n-prev)
914                         (,next ,n-current)))))
915          (values)))))
916 ;;; #+SB-XC-HOST SB!XC:DEFMACRO version is in late-macros.lisp. -- WHN 19990806
917
918 ;;; Push ITEM onto a list linked by the accessor function NEXT that is
919 ;;; stored in PLACE.
920 ;;;
921 ;;; KLUDGE: This is expanded out twice, by cut-and-paste, in a
922 ;;;   (DEF!MACRO FOO (..) .. CL:GET-SETF-EXPANSION ..)
923 ;;;   #+SB-XC-HOST
924 ;;;   (SB!XC:DEFMACRO FOO (..) .. SB!XC:GET-SETF-EXPANSION ..)
925 ;;; arrangement, in order to get it to work in cross-compilation. This
926 ;;; duplication should be removed, perhaps by rewriting the macro in a more
927 ;;; cross-compiler-friendly way, or perhaps just by using some (MACROLET ((FROB
928 ;;; ..)) .. FROB .. FROB) form, or perhaps by completely eliminating this macro
929 ;;; and its partner DELETEF-IN, but I don't want to do it now, because the
930 ;;; system isn't running yet, so it'd be too hard to check that my changes were
931 ;;; correct -- WHN 19990806
932 (def!macro push-in (next item place &environment env)
933   (multiple-value-bind (temps vals stores store access)
934       (get-setf-expansion place env)
935     (when (cdr stores)
936       (error "multiple store variables for ~S" place))
937     `(let (,@(mapcar #'list temps vals)
938            (,(first stores) ,item))
939        (setf (,next ,(first stores)) ,access)
940        ,store
941        (values))))
942 ;;; #+SB-XC-HOST SB!XC:DEFMACRO version is in late-macros.lisp. -- WHN 19990806
943
944 (defmacro position-or-lose (&rest args)
945   `(or (position ,@args)
946        (error "shouldn't happen?")))
947
948 ;;; user-definable compiler io syntax
949
950 ;;; We use WITH-SANE-IO-SYNTAX to provide safe defaults, and provide
951 ;;; *COMPILER-PRINT-VARIABLE-ALIST* for user customization.
952 (defvar *compiler-print-variable-alist* nil
953   #!+sb-doc
954   "an association list describing new bindings for special variables
955 to be used by the compiler for error-reporting, etc. Eg.
956
957  ((*PRINT-LENGTH* . 10) (*PRINT-LEVEL* . 6) (*PRINT-PRETTY* . NIL))
958
959 The variables in the CAR positions are bound to the values in the CDR
960 during the execution of some debug commands. When evaluating arbitrary
961 expressions in the debugger, the normal values of the printer control
962 variables are in effect.
963
964 Initially empty, *COMPILER-PRINT-VARIABLE-ALIST* is Typically used to
965 specify bindings for printer control variables.")
966
967 (defmacro with-compiler-io-syntax (&body forms)
968   `(with-sane-io-syntax
969     (progv
970         (nreverse (mapcar #'car *compiler-print-variable-alist*))
971         (nreverse (mapcar #'cdr *compiler-print-variable-alist*))
972       ,@forms)))