015768c573fa848fef55ac6a515b1fe0ab12fd30
[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 ;;;             :MAYBE-INLINE is quite different from :INLINE. As explained
26 ;;;             by APD on #lisp 2005-11-26: "MAYBE-INLINE lambda is
27 ;;;             instantiated once per component, INLINE - for all
28 ;;;             references (even under #'without FUNCALL)."
29 (deftype inlinep () '(member :inline :maybe-inline :notinline nil))
30 \f
31 ;;;; source-hacking defining forms
32
33 ;;; Parse a DEFMACRO-style lambda-list, setting things up so that a
34 ;;; compiler error happens if the syntax is invalid.
35 ;;;
36 ;;; Define a function that converts a special form or other magical
37 ;;; thing into IR1. LAMBDA-LIST is a defmacro style lambda
38 ;;; list. START-VAR, NEXT-VAR and RESULT-VAR are bound to the start and
39 ;;; result continuations for the resulting IR1. KIND is the function
40 ;;; kind to associate with NAME.
41 (defmacro def-ir1-translator (name (lambda-list start-var next-var result-var)
42                               &body body)
43   (let ((fn-name (symbolicate "IR1-CONVERT-" name)))
44     (with-unique-names (whole-var n-env)
45       (multiple-value-bind (body decls doc)
46           (parse-defmacro lambda-list whole-var body name "special form"
47                           :environment n-env
48                           :error-fun 'compiler-error
49                           :wrap-block nil)
50         `(progn
51            (declaim (ftype (function (ctran ctran (or lvar null) t) (values))
52                            ,fn-name))
53            (defun ,fn-name (,start-var ,next-var ,result-var ,whole-var
54                             &aux (,n-env *lexenv*))
55              (declare (ignorable ,start-var ,next-var ,result-var))
56              ,@decls
57              ,body
58              (values))
59            ,@(when doc
60                    `((setf (fdocumentation ',name 'function) ,doc)))
61            ;; FIXME: Evidently "there can only be one!" -- we overwrite any
62            ;; other :IR1-CONVERT value. This deserves a warning, I think.
63            (setf (info :function :ir1-convert ',name) #',fn-name)
64            ;; FIXME: rename this to SPECIAL-OPERATOR, to update it to
65            ;; the 1990s?
66            (setf (info :function :kind ',name) :special-form)
67            ;; It's nice to do this for error checking in the target
68            ;; SBCL, but it's not nice to do this when we're running in
69            ;; the cross-compilation host Lisp, which owns the
70            ;; SYMBOL-FUNCTION of its COMMON-LISP symbols.
71            #-sb-xc-host
72            (let ((fun (lambda (&rest rest)
73                         (declare (ignore rest))
74                         (error 'special-form-function :name ',name))))
75              (setf (%simple-fun-arglist fun) ',lambda-list)
76              (setf (symbol-function ',name) fun))
77            ',name)))))
78
79 ;;; (This is similar to DEF-IR1-TRANSLATOR, except that we pass if the
80 ;;; syntax is invalid.)
81 ;;;
82 ;;; Define a macro-like source-to-source transformation for the
83 ;;; function NAME. A source transform may "pass" by returning a
84 ;;; non-nil second value. If the transform passes, then the form is
85 ;;; converted as a normal function call. If the supplied arguments are
86 ;;; not compatible with the specified LAMBDA-LIST, then the transform
87 ;;; automatically passes.
88 ;;;
89 ;;; Source transforms may only be defined for functions. Source
90 ;;; transformation is not attempted if the function is declared
91 ;;; NOTINLINE. Source transforms should not examine their arguments.
92 ;;; If it matters how the function is used, then DEFTRANSFORM should
93 ;;; be used to define an IR1 transformation.
94 ;;;
95 ;;; If the desirability of the transformation depends on the current
96 ;;; OPTIMIZE parameters, then the POLICY macro should be used to
97 ;;; determine when to pass.
98 (defmacro source-transform-lambda (lambda-list &body body)
99   (with-unique-names (whole-var n-env name)
100     (multiple-value-bind (body decls)
101         (parse-defmacro lambda-list whole-var body "source transform" "form"
102                         :environment n-env
103                         :error-fun `(lambda (&rest stuff)
104                                       (declare (ignore stuff))
105                                       (return-from ,name
106                                         (values nil t)))
107                         :wrap-block nil)
108       `(lambda (,whole-var &aux (,n-env *lexenv*))
109          ,@decls
110          (block ,name
111            ,body)))))
112 (defmacro define-source-transform (name lambda-list &body body)
113   `(setf (info :function :source-transform ',name)
114          (source-transform-lambda ,lambda-list ,@body)))
115 \f
116 ;;;; boolean attribute utilities
117 ;;;;
118 ;;;; We need to maintain various sets of boolean attributes for known
119 ;;;; functions and VOPs. To save space and allow for quick set
120 ;;;; operations, we represent the attributes as bits in a fixnum.
121
122 (deftype attributes () 'fixnum)
123
124 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
125
126 ;;; Given a list of attribute names and an alist that translates them
127 ;;; to masks, return the OR of the masks.
128 (defun compute-attribute-mask (names alist)
129   (collect ((res 0 logior))
130     (dolist (name names)
131       (let ((mask (cdr (assoc name alist))))
132         (unless mask
133           (error "unknown attribute name: ~S" name))
134         (res mask)))
135     (res)))
136
137 ) ; EVAL-WHEN
138
139 ;;; Define a new class of boolean attributes, with the attributes
140 ;;; having the specified ATTRIBUTE-NAMES. NAME is the name of the
141 ;;; class, which is used to generate some macros to manipulate sets of
142 ;;; the attributes:
143 ;;;
144 ;;;    NAME-attributep attributes attribute-name*
145 ;;;      Return true if one of the named attributes is present, false
146 ;;;      otherwise. When set with SETF, updates the place Attributes
147 ;;;      setting or clearing the specified attributes.
148 ;;;
149 ;;;    NAME-attributes attribute-name*
150 ;;;      Return a set of the named attributes.
151 #-sb-xc
152 (progn
153   (def!macro !def-boolean-attribute (name &rest attribute-names)
154
155     (let ((translations-name (symbolicate "*" name "-ATTRIBUTE-TRANSLATIONS*"))
156           (test-name (symbolicate name "-ATTRIBUTEP"))
157           (decoder-name (symbolicate "DECODE-" name "-ATTRIBUTES")))
158       (collect ((alist))
159         (do ((mask 1 (ash mask 1))
160              (names attribute-names (cdr names)))
161             ((null names))
162           (alist (cons (car names) mask)))
163         `(progn
164            (eval-when (:compile-toplevel :load-toplevel :execute)
165              (defparameter ,translations-name ',(alist)))
166            (defmacro ,(symbolicate name "-ATTRIBUTES") (&rest attribute-names)
167              "Automagically generated boolean attribute creation function.
168   See !DEF-BOOLEAN-ATTRIBUTE."
169              (compute-attribute-mask attribute-names ,translations-name))
170            (defmacro ,test-name (attributes &rest attribute-names)
171              "Automagically generated boolean attribute test function.
172   See !DEF-BOOLEAN-ATTRIBUTE."
173              `(logtest ,(compute-attribute-mask attribute-names
174                                                 ,translations-name)
175                        (the attributes ,attributes)))
176            ;; This definition transforms strangely under UNCROSS, in a
177            ;; way that DEF!MACRO doesn't understand, so we delegate it
178            ;; to a submacro then define the submacro differently when
179            ;; building the xc and when building the target compiler.
180            (!def-boolean-attribute-setter ,test-name
181                                           ,translations-name
182                                           ,@attribute-names)
183            (defun ,decoder-name (attributes)
184              (loop for (name . mask) in ,translations-name
185                    when (logtest mask attributes)
186                      collect name))))))
187
188   ;; It seems to be difficult to express in DEF!MACRO machinery what
189   ;; to do with target-vs-host GET-SETF-EXPANSION in here, so we just
190   ;; hack it by hand, passing a different GET-SETF-EXPANSION-FUN-NAME
191   ;; in the host DEFMACRO and target DEFMACRO-MUNDANELY cases.
192   (defun guts-of-!def-boolean-attribute-setter (test-name
193                                                 translations-name
194                                                 attribute-names
195                                                 get-setf-expansion-fun-name)
196     `(define-setf-expander ,test-name (place &rest attributes
197                                              &environment env)
198        "Automagically generated boolean attribute setter. See
199  !DEF-BOOLEAN-ATTRIBUTE."
200        #-sb-xc-host (declare (type sb!c::lexenv env))
201        ;; FIXME: It would be better if &ENVIRONMENT arguments were
202        ;; automatically declared to have type LEXENV by the
203        ;; hairy-argument-handling code.
204        (multiple-value-bind (temps values stores set get)
205            (,get-setf-expansion-fun-name place env)
206          (when (cdr stores)
207            (error "multiple store variables for ~S" place))
208          (let ((newval (gensym))
209                (n-place (gensym))
210                (mask (compute-attribute-mask attributes ,translations-name)))
211            (values `(,@temps ,n-place)
212                    `(,@values ,get)
213                    `(,newval)
214                    `(let ((,(first stores)
215                            (if ,newval
216                                (logior ,n-place ,mask)
217                                (logand ,n-place ,(lognot mask)))))
218                       ,set
219                       ,newval)
220                    `(,',test-name ,n-place ,@attributes))))))
221   ;; We define the host version here, and the just-like-it-but-different
222   ;; target version later, after DEFMACRO-MUNDANELY has been defined.
223   (defmacro !def-boolean-attribute-setter (test-name
224                                            translations-name
225                                            &rest attribute-names)
226     (guts-of-!def-boolean-attribute-setter test-name
227                                            translations-name
228                                            attribute-names
229                                            'get-setf-expansion)))
230
231 ;;; And now for some gratuitous pseudo-abstraction...
232 ;;;
233 ;;; ATTRIBUTES-UNION
234 ;;;   Return the union of all the sets of boolean attributes which are its
235 ;;;   arguments.
236 ;;; ATTRIBUTES-INTERSECTION
237 ;;;   Return the intersection of all the sets of boolean attributes which
238 ;;;   are its arguments.
239 ;;; ATTRIBUTES
240 ;;;   True if the attributes present in ATTR1 are identical to
241 ;;;   those in ATTR2.
242 (defmacro attributes-union (&rest attributes)
243   `(the attributes
244         (logior ,@(mapcar (lambda (x) `(the attributes ,x)) attributes))))
245 (defmacro attributes-intersection (&rest attributes)
246   `(the attributes
247         (logand ,@(mapcar (lambda (x) `(the attributes ,x)) attributes))))
248 (declaim (ftype (function (attributes attributes) boolean) attributes=))
249 #!-sb-fluid (declaim (inline attributes=))
250 (defun attributes= (attr1 attr2)
251   (eql attr1 attr2))
252 \f
253 ;;;; lambda-list parsing utilities
254 ;;;;
255 ;;;; IR1 transforms, optimizers and type inferencers need to be able
256 ;;;; to parse the IR1 representation of a function call using a
257 ;;;; standard function lambda-list.
258
259 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
260
261 ;;; Given a DEFTRANSFORM-style lambda-list, generate code that parses
262 ;;; the arguments of a combination with respect to that
263 ;;; lambda-list. BODY is the list of forms which are to be
264 ;;; evaluated within the bindings. ARGS is the variable that holds
265 ;;; list of argument lvars. ERROR-FORM is a form which is evaluated
266 ;;; when the syntax of the supplied arguments is incorrect or a
267 ;;; non-constant argument keyword is supplied. Defaults and other gunk
268 ;;; are ignored. The second value is a list of all the arguments
269 ;;; bound. We make the variables IGNORABLE so that we don't have to
270 ;;; manually declare them IGNORE if their only purpose is to make the
271 ;;; 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-lvar ,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-lvar ,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 lvar which represents the value of the argument. When parsing
344 ;;; the call, we ignore the defaults, and always bind the variables
345 ;;; for unsupplied arguments to NIL. If a required argument is
346 ;;; missing, an unknown keyword is supplied, or an argument keyword is
347 ;;; 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 lvar.
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-lvar ,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           (declare (ignorable ,@vars))
508           (let ((,n-args (basic-combination-args ,n-node)))
509             ,(parse-deftransform lambda-list body n-args
510                                  `(return-from ,name nil))))
511         ,@(when (consp what)
512             `((setf (,(let ((*package* (symbol-package 'sb!c::fun-info)))
513                         (symbolicate "FUN-INFO-" (second what)))
514                      (fun-info-or-lose ',(first what)))
515                     #',name)))))))
516 \f
517 ;;;; IR groveling macros
518
519 ;;; Iterate over the blocks in a component, binding BLOCK-VAR to each
520 ;;; block in turn. The value of ENDS determines whether to iterate
521 ;;; over dummy head and tail blocks:
522 ;;;    NIL  -- Skip Head and Tail (the default)
523 ;;;   :HEAD -- Do head but skip tail
524 ;;;   :TAIL -- Do tail but skip head
525 ;;;   :BOTH -- Do both head and tail
526 ;;;
527 ;;; If supplied, RESULT-FORM is the value to return.
528 (defmacro do-blocks ((block-var component &optional ends result) &body body)
529   (unless (member ends '(nil :head :tail :both))
530     (error "losing ENDS value: ~S" ends))
531   (let ((n-component (gensym))
532         (n-tail (gensym)))
533     `(let* ((,n-component ,component)
534             (,n-tail ,(if (member ends '(:both :tail))
535                           nil
536                           `(component-tail ,n-component))))
537        (do ((,block-var ,(if (member ends '(:both :head))
538                              `(component-head ,n-component)
539                              `(block-next (component-head ,n-component)))
540                         (block-next ,block-var)))
541            ((eq ,block-var ,n-tail) ,result)
542          ,@body))))
543 ;;; like DO-BLOCKS, only iterating over the blocks in reverse order
544 (defmacro do-blocks-backwards ((block-var component &optional ends result) &body body)
545   (unless (member ends '(nil :head :tail :both))
546     (error "losing ENDS value: ~S" ends))
547   (let ((n-component (gensym))
548         (n-head (gensym)))
549     `(let* ((,n-component ,component)
550             (,n-head ,(if (member ends '(:both :head))
551                           nil
552                           `(component-head ,n-component))))
553        (do ((,block-var ,(if (member ends '(:both :tail))
554                              `(component-tail ,n-component)
555                              `(block-prev (component-tail ,n-component)))
556                         (block-prev ,block-var)))
557            ((eq ,block-var ,n-head) ,result)
558          ,@body))))
559
560 ;;; Iterate over the uses of LVAR, binding NODE to each one
561 ;;; successively.
562 ;;;
563 ;;; XXX Could change it not to replicate the code someday perhaps...
564 (defmacro do-uses ((node-var lvar &optional result) &body body)
565   (with-unique-names (uses)
566     `(let ((,uses (lvar-uses ,lvar)))
567        (if (listp ,uses)
568            (dolist (,node-var ,uses ,result)
569              ,@body)
570            (block nil
571              (let ((,node-var ,uses))
572                ,@body))))))
573
574 ;;; Iterate over the nodes in BLOCK, binding NODE-VAR to the each node
575 ;;; and LVAR-VAR to the node's LVAR. The only keyword option is
576 ;;; RESTART-P, which causes iteration to be restarted when a node is
577 ;;; deleted out from under us. (If not supplied, this is an error.)
578 ;;;
579 ;;; In the forward case, we terminate when NODE does not have NEXT, so
580 ;;; that we do not have to worry about our termination condition being
581 ;;; changed when new code is added during the iteration. In the
582 ;;; backward case, we do NODE-PREV before evaluating the body so that
583 ;;; we can keep going when the current node is deleted.
584 ;;;
585 ;;; When RESTART-P is supplied to DO-NODES, we start iterating over
586 ;;; again at the beginning of the block when we run into a ctran whose
587 ;;; block differs from the one we are trying to iterate over, either
588 ;;; because the block was split, or because a node was deleted out
589 ;;; from under us (hence its block is NIL.) If the block start is
590 ;;; deleted, we just punt. With RESTART-P, we are also more careful
591 ;;; about termination, re-indirecting the BLOCK-LAST each time.
592 (defmacro do-nodes ((node-var lvar-var block &key restart-p)
593                     &body body)
594   (with-unique-names (n-block n-start)
595     `(do* ((,n-block ,block)
596            (,n-start (block-start ,n-block))
597
598            (,node-var (ctran-next ,n-start)
599                       ,(if restart-p
600                            `(let ((next (node-next ,node-var)))
601                               (cond
602                                 ((not next)
603                                  (return))
604                                 ((eq (ctran-block next) ,n-block)
605                                  (ctran-next next))
606                                 (t
607                                  (let ((start (block-start ,n-block)))
608                                    (unless (eq (ctran-kind start)
609                                                :block-start)
610                                      (return nil))
611                                    (ctran-next start)))))
612                            `(acond ((node-next ,node-var)
613                                     (ctran-next it))
614                                    (t (return)))))
615            ,@(when lvar-var
616                    `((,lvar-var (when (valued-node-p ,node-var)
617                                   (node-lvar ,node-var))
618                                 (when (valued-node-p ,node-var)
619                                   (node-lvar ,node-var))))))
620           (nil)
621        ,@body
622        ,@(when restart-p
623            `((when (block-delete-p ,n-block)
624                (return)))))))
625
626 ;;; Like DO-NODES, only iterating in reverse order. Should be careful
627 ;;; with block being split under us.
628 (defmacro do-nodes-backwards ((node-var lvar block &key restart-p) &body body)
629   (let ((n-block (gensym))
630         (n-prev (gensym)))
631     `(loop with ,n-block = ,block
632            for ,node-var = (block-last ,n-block) then
633                            ,(if restart-p
634                                 `(if (eq ,n-block (ctran-block ,n-prev))
635                                      (ctran-use ,n-prev)
636                                      (block-last ,n-block))
637                                 `(ctran-use ,n-prev))
638            for ,n-prev = (when ,node-var (node-prev ,node-var))
639            and ,lvar = (when (and ,node-var (valued-node-p ,node-var))
640                          (node-lvar ,node-var))
641            while ,(if restart-p
642                       `(and ,node-var (not (block-to-be-deleted-p ,n-block)))
643                       node-var)
644            do (progn
645                 ,@body))))
646
647 (defmacro do-nodes-carefully ((node-var block) &body body)
648   (with-unique-names (n-block n-ctran)
649     `(loop with ,n-block = ,block
650            for ,n-ctran = (block-start ,n-block) then (node-next ,node-var)
651            for ,node-var = (and ,n-ctran (ctran-next ,n-ctran))
652            while ,node-var
653            do (progn ,@body))))
654
655 ;;; Bind the IR1 context variables to the values associated with NODE,
656 ;;; so that new, extra IR1 conversion related to NODE can be done
657 ;;; after the original conversion pass has finished.
658 (defmacro with-ir1-environment-from-node (node &rest forms)
659   `(flet ((closure-needing-ir1-environment-from-node ()
660             ,@forms))
661      (%with-ir1-environment-from-node
662       ,node
663       #'closure-needing-ir1-environment-from-node)))
664 (defun %with-ir1-environment-from-node (node fun)
665   (declare (type node node) (type function fun))
666   (let ((*current-component* (node-component node))
667         (*lexenv* (node-lexenv node))
668         (*current-path* (node-source-path node)))
669     (aver-live-component *current-component*)
670     (funcall fun)))
671
672 ;;; Bind the hashtables used for keeping track of global variables,
673 ;;; functions, etc. Also establish condition handlers.
674 (defmacro with-ir1-namespace (&body forms)
675   `(let ((*free-vars* (make-hash-table :test 'eq))
676          (*free-funs* (make-hash-table :test 'equal))
677          (*constants* (make-hash-table :test 'equal))
678          (*source-paths* (make-hash-table :test 'eq)))
679      (handler-bind ((compiler-error #'compiler-error-handler)
680                     (style-warning #'compiler-style-warning-handler)
681                     (warning #'compiler-warning-handler))
682        ,@forms)))
683
684 ;;; Look up NAME in the lexical environment namespace designated by
685 ;;; SLOT, returning the <value, T>, or <NIL, NIL> if no entry. The
686 ;;; :TEST keyword may be used to determine the name equality
687 ;;; predicate.
688 (defmacro lexenv-find (name slot &key test)
689   (once-only ((n-res `(assoc ,name (,(let ((*package* (symbol-package 'lexenv-funs)))
690                                           (symbolicate "LEXENV-" slot))
691                                      *lexenv*)
692                              :test ,(or test '#'eq))))
693     `(if ,n-res
694          (values (cdr ,n-res) t)
695          (values nil nil))))
696
697 (defmacro with-component-last-block ((component block) &body body)
698   (with-unique-names (old-last-block)
699     (once-only ((component component)
700                 (block block))
701       `(let ((,old-last-block (component-last-block ,component)))
702          (unwind-protect
703               (progn (setf (component-last-block ,component)
704                            ,block)
705                      ,@body)
706            (setf (component-last-block ,component)
707                  ,old-last-block))))))
708
709 \f
710 ;;;; the EVENT statistics/trace utility
711
712 ;;; FIXME: This seems to be useful for troubleshooting and
713 ;;; experimentation, not for ordinary use, so it should probably
714 ;;; become conditional on SB-SHOW.
715
716 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
717
718 (defstruct (event-info (:copier nil))
719   ;; The name of this event.
720   (name (missing-arg) :type symbol)
721   ;; The string rescribing this event.
722   (description (missing-arg) :type string)
723   ;; The name of the variable we stash this in.
724   (var (missing-arg) :type symbol)
725   ;; The number of times this event has happened.
726   (count 0 :type fixnum)
727   ;; The level of significance of this event.
728   (level (missing-arg) :type unsigned-byte)
729   ;; If true, a function that gets called with the node that the event
730   ;; happened to.
731   (action nil :type (or function null)))
732
733 ;;; A hashtable from event names to event-info structures.
734 (defvar *event-info* (make-hash-table :test 'eq))
735
736 ;;; Return the event info for Name or die trying.
737 (declaim (ftype (function (t) event-info) event-info-or-lose))
738 (defun event-info-or-lose (name)
739   (let ((res (gethash name *event-info*)))
740     (unless res
741       (error "~S is not the name of an event." name))
742     res))
743
744 ) ; EVAL-WHEN
745
746 ;;; Return the number of times that EVENT has happened.
747 (declaim (ftype (function (symbol) fixnum) event-count))
748 (defun event-count (name)
749   (event-info-count (event-info-or-lose name)))
750
751 ;;; Return the function that is called when Event happens. If this is
752 ;;; null, there is no action. The function is passed the node to which
753 ;;; the event happened, or NIL if there is no relevant node. This may
754 ;;; be set with SETF.
755 (declaim (ftype (function (symbol) (or function null)) event-action))
756 (defun event-action (name)
757   (event-info-action (event-info-or-lose name)))
758 (declaim (ftype (function (symbol (or function null)) (or function null))
759                 %set-event-action))
760 (defun %set-event-action (name new-value)
761   (setf (event-info-action (event-info-or-lose name))
762         new-value))
763 (defsetf event-action %set-event-action)
764
765 ;;; Return the non-negative integer which represents the level of
766 ;;; significance of the event Name. This is used to determine whether
767 ;;; to print a message when the event happens. This may be set with
768 ;;; SETF.
769 (declaim (ftype (function (symbol) unsigned-byte) event-level))
770 (defun event-level (name)
771   (event-info-level (event-info-or-lose name)))
772 (declaim (ftype (function (symbol unsigned-byte) unsigned-byte) %set-event-level))
773 (defun %set-event-level (name new-value)
774   (setf (event-info-level (event-info-or-lose name))
775         new-value))
776 (defsetf event-level %set-event-level)
777
778 ;;; Define a new kind of event. NAME is a symbol which names the event
779 ;;; and DESCRIPTION is a string which describes the event. Level
780 ;;; (default 0) is the level of significance associated with this
781 ;;; event; it is used to determine whether to print a Note when the
782 ;;; event happens.
783 (defmacro defevent (name description &optional (level 0))
784   (let ((var-name (symbolicate "*" name "-EVENT-INFO*")))
785     `(eval-when (:compile-toplevel :load-toplevel :execute)
786        (defvar ,var-name
787          (make-event-info :name ',name
788                           :description ',description
789                           :var ',var-name
790                           :level ,level))
791        (setf (gethash ',name *event-info*) ,var-name)
792        ',name)))
793
794 ;;; the lowest level of event that will print a note when it occurs
795 (declaim (type unsigned-byte *event-note-threshold*))
796 (defvar *event-note-threshold* 1)
797
798 ;;; Note that the event with the specified NAME has happened. NODE is
799 ;;; evaluated to determine the node to which the event happened.
800 (defmacro event (name &optional node)
801   ;; Increment the counter and do any action. Mumble about the event if
802   ;; policy indicates.
803   `(%event ,(event-info-var (event-info-or-lose name)) ,node))
804
805 ;;; Print a listing of events and their counts, sorted by the count.
806 ;;; Events that happened fewer than Min-Count times will not be
807 ;;; printed. Stream is the stream to write to.
808 (declaim (ftype (function (&optional unsigned-byte stream) (values)) event-statistics))
809 (defun event-statistics (&optional (min-count 1) (stream *standard-output*))
810   (collect ((info))
811     (maphash (lambda (k v)
812                (declare (ignore k))
813                (when (>= (event-info-count v) min-count)
814                  (info v)))
815              *event-info*)
816     (dolist (event (sort (info) #'> :key #'event-info-count))
817       (format stream "~6D: ~A~%" (event-info-count event)
818               (event-info-description event)))
819     (values))
820   (values))
821
822 (declaim (ftype (function nil (values)) clear-event-statistics))
823 (defun clear-event-statistics ()
824   (maphash (lambda (k v)
825              (declare (ignore k))
826              (setf (event-info-count v) 0))
827            *event-info*)
828   (values))
829 \f
830 ;;;; functions on directly-linked lists (linked through specialized
831 ;;;; NEXT operations)
832
833 #!-sb-fluid (declaim (inline find-in position-in))
834
835 ;;; Find ELEMENT in a null-terminated LIST linked by the accessor
836 ;;; function NEXT. KEY, TEST and TEST-NOT are the same as for generic
837 ;;; sequence functions.
838 (defun find-in (next
839                 element
840                 list
841                 &key
842                 (key #'identity)
843                 (test #'eql test-p)
844                 (test-not #'eql not-p))
845   (declare (type function next key test test-not))
846   (when (and test-p not-p)
847     (error "It's silly to supply both :TEST and :TEST-NOT arguments."))
848   (if not-p
849       (do ((current list (funcall next current)))
850           ((null current) nil)
851         (unless (funcall test-not (funcall key current) element)
852           (return current)))
853       (do ((current list (funcall next current)))
854           ((null current) nil)
855         (when (funcall test (funcall key current) element)
856           (return current)))))
857
858 ;;; Return the position of ELEMENT (or NIL if absent) in a
859 ;;; null-terminated LIST linked by the accessor function NEXT. KEY,
860 ;;; TEST and TEST-NOT are the same as for generic sequence functions.
861 (defun position-in (next
862                     element
863                     list
864                     &key
865                     (key #'identity)
866                     (test #'eql test-p)
867                     (test-not #'eql not-p))
868   (declare (type function next key test test-not))
869   (when (and test-p not-p)
870     (error "It's silly to supply both :TEST and :TEST-NOT arguments."))
871   (if not-p
872       (do ((current list (funcall next current))
873            (i 0 (1+ i)))
874           ((null current) nil)
875         (unless (funcall test-not (funcall key current) element)
876           (return i)))
877       (do ((current list (funcall next current))
878            (i 0 (1+ i)))
879           ((null current) nil)
880         (when (funcall test (funcall key current) element)
881           (return i)))))
882
883
884 ;;; KLUDGE: This is expanded out twice, by cut-and-paste, in a
885 ;;;   (DEF!MACRO FOO (..) .. CL:GET-SETF-EXPANSION ..)
886 ;;;   #+SB-XC-HOST
887 ;;;   (SB!XC:DEFMACRO FOO (..) .. SB!XC:GET-SETF-EXPANSION ..)
888 ;;; arrangement, in order to get it to work in cross-compilation. This
889 ;;; duplication should be removed, perhaps by rewriting the macro in a more
890 ;;; cross-compiler-friendly way, or perhaps just by using some (MACROLET ((FROB
891 ;;; ..)) .. FROB .. FROB) form, or perhaps by completely eliminating this macro
892 ;;; and its partner PUSH-IN, but I don't want to do it now, because the system
893 ;;; isn't running yet, so it'd be too hard to check that my changes were
894 ;;; correct -- WHN 19990806
895 (def!macro deletef-in (next place item &environment env)
896   (multiple-value-bind (temps vals stores store access)
897       (get-setf-expansion place env)
898     (when (cdr stores)
899       (error "multiple store variables for ~S" place))
900     (let ((n-item (gensym))
901           (n-place (gensym))
902           (n-current (gensym))
903           (n-prev (gensym)))
904       `(let* (,@(mapcar #'list temps vals)
905               (,n-place ,access)
906               (,n-item ,item))
907          (if (eq ,n-place ,n-item)
908              (let ((,(first stores) (,next ,n-place)))
909                ,store)
910              (do ((,n-prev ,n-place ,n-current)
911                   (,n-current (,next ,n-place)
912                               (,next ,n-current)))
913                  ((eq ,n-current ,n-item)
914                   (setf (,next ,n-prev)
915                         (,next ,n-current)))))
916          (values)))))
917 ;;; #+SB-XC-HOST SB!XC:DEFMACRO version is in late-macros.lisp. -- WHN 19990806
918
919 ;;; Push ITEM onto a list linked by the accessor function NEXT that is
920 ;;; stored in PLACE.
921 ;;;
922 ;;; KLUDGE: This is expanded out twice, by cut-and-paste, in a
923 ;;;   (DEF!MACRO FOO (..) .. CL:GET-SETF-EXPANSION ..)
924 ;;;   #+SB-XC-HOST
925 ;;;   (SB!XC:DEFMACRO FOO (..) .. SB!XC:GET-SETF-EXPANSION ..)
926 ;;; arrangement, in order to get it to work in cross-compilation. This
927 ;;; duplication should be removed, perhaps by rewriting the macro in a more
928 ;;; cross-compiler-friendly way, or perhaps just by using some (MACROLET ((FROB
929 ;;; ..)) .. FROB .. FROB) form, or perhaps by completely eliminating this macro
930 ;;; and its partner DELETEF-IN, but I don't want to do it now, because the
931 ;;; system isn't running yet, so it'd be too hard to check that my changes were
932 ;;; correct -- WHN 19990806
933 (def!macro push-in (next item place &environment env)
934   (multiple-value-bind (temps vals stores store access)
935       (get-setf-expansion place env)
936     (when (cdr stores)
937       (error "multiple store variables for ~S" place))
938     `(let (,@(mapcar #'list temps vals)
939            (,(first stores) ,item))
940        (setf (,next ,(first stores)) ,access)
941        ,store
942        (values))))
943 ;;; #+SB-XC-HOST SB!XC:DEFMACRO version is in late-macros.lisp. -- WHN 19990806
944
945 (defmacro position-or-lose (&rest args)
946   `(or (position ,@args)
947        (error "shouldn't happen?")))
948
949 ;;; user-definable compiler io syntax
950
951 ;;; We use WITH-SANE-IO-SYNTAX to provide safe defaults, and provide
952 ;;; *COMPILER-PRINT-VARIABLE-ALIST* for user customization.
953 (defvar *compiler-print-variable-alist* nil
954   #!+sb-doc
955   "an association list describing new bindings for special variables
956 to be used by the compiler for error-reporting, etc. Eg.
957
958  ((*PRINT-LENGTH* . 10) (*PRINT-LEVEL* . 6) (*PRINT-PRETTY* . NIL))
959
960 The variables in the CAR positions are bound to the values in the CDR
961 during the execution of some debug commands. When evaluating arbitrary
962 expressions in the debugger, the normal values of the printer control
963 variables are in effect.
964
965 Initially empty, *COMPILER-PRINT-VARIABLE-ALIST* is Typically used to
966 specify bindings for printer control variables.")
967
968 (defmacro with-compiler-io-syntax (&body forms)
969   `(with-sane-io-syntax
970     (progv
971         (nreverse (mapcar #'car *compiler-print-variable-alist*))
972         (nreverse (mapcar #'cdr *compiler-print-variable-alist*))
973       ,@forms)))