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