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