1.0.47.16: more ((LAMBDA ..) ..) and (FUNCALL (LAMBDA ..) ..) equivalence
[sbcl.git] / src / compiler / ir1tran.lisp
1 ;;;; This file contains code which does the translation from Lisp code
2 ;;;; to the first intermediate representation (IR1).
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14
15 (declaim (special *compiler-error-bailout*))
16
17 ;;; *CURRENT-FORM-NUMBER* is used in FIND-SOURCE-PATHS to compute the
18 ;;; form number to associate with a source path. This should be bound
19 ;;; to an initial value of 0 before the processing of each truly
20 ;;; top level form.
21 (declaim (type index *current-form-number*))
22 (defvar *current-form-number*)
23
24 ;;; *SOURCE-PATHS* is a hashtable from source code forms to the path
25 ;;; taken through the source to reach the form. This provides a way to
26 ;;; keep track of the location of original source forms, even when
27 ;;; macroexpansions and other arbitary permutations of the code
28 ;;; happen. This table is initialized by calling FIND-SOURCE-PATHS on
29 ;;; the original source.
30 ;;;
31 ;;; It is fairly useless to store symbols, characters, or fixnums in
32 ;;; this table, as 42 is EQ to 42 no matter where in the source it
33 ;;; appears. GET-SOURCE-PATH and NOTE-SOURCE-PATH functions should be
34 ;;; always used to access this table.
35 (declaim (hash-table *source-paths*))
36 (defvar *source-paths*)
37
38 (declaim (inline source-form-has-path-p))
39 (defun source-form-has-path-p (form)
40   (not (typep form '(or symbol fixnum character))))
41
42 (defun get-source-path (form)
43   (when (source-form-has-path-p form)
44     (gethash form *source-paths*)))
45
46 (defun simplify-source-path-form (form)
47   (if (consp form)
48       (let ((op (car form)))
49         ;; In the compiler functions can be directly represented
50         ;; by leaves. Having leaves in the source path is pretty
51         ;; hard on the poor user, however, so replace with the
52         ;; source-name when possible.
53         (if (and (leaf-p op) (leaf-has-source-name-p op))
54             (cons (leaf-source-name op) (cdr form))
55             form))
56       form))
57
58 (defun note-source-path (form &rest arguments)
59   (when (source-form-has-path-p form)
60     (setf (gethash form *source-paths*)
61           (apply #'list* 'original-source-start *current-form-number* arguments))))
62
63 ;;; *CURRENT-COMPONENT* is the COMPONENT structure which we link
64 ;;; blocks into as we generate them. This just serves to glue the
65 ;;; emitted blocks together until local call analysis and flow graph
66 ;;; canonicalization figure out what is really going on. We need to
67 ;;; keep track of all the blocks generated so that we can delete them
68 ;;; if they turn out to be unreachable.
69 ;;;
70 ;;; FIXME: It's confusing having one variable named *CURRENT-COMPONENT*
71 ;;; and another named *COMPONENT-BEING-COMPILED*. (In CMU CL they
72 ;;; were called *CURRENT-COMPONENT* and *COMPILE-COMPONENT* respectively,
73 ;;; which was also confusing.)
74 (declaim (type (or component null) *current-component*))
75 (defvar *current-component*)
76
77 ;;; *CURRENT-PATH* is the source path of the form we are currently
78 ;;; translating. See NODE-SOURCE-PATH in the NODE structure.
79 (declaim (list *current-path*))
80 (defvar *current-path*)
81
82 (defvar *derive-function-types* nil
83   "Should the compiler assume that function types will never change,
84   so that it can use type information inferred from current definitions
85   to optimize code which uses those definitions? Setting this true
86   gives non-ANSI, early-CMU-CL behavior. It can be useful for improving
87   the efficiency of stable code.")
88
89 (defvar *fun-names-in-this-file* nil)
90
91 (defvar *post-binding-variable-lexenv* nil)
92 \f
93 ;;;; namespace management utilities
94
95 (defun fun-lexically-notinline-p (name)
96   (let ((fun (lexenv-find name funs :test #'equal)))
97     ;; a declaration will trump a proclamation
98     (if (and fun (defined-fun-p fun))
99         (eq (defined-fun-inlinep fun) :notinline)
100         (eq (info :function :inlinep name) :notinline))))
101
102 ;; This will get redefined in PCL boot.
103 (declaim (notinline maybe-update-info-for-gf))
104 (defun maybe-update-info-for-gf (name)
105   (declare (ignore name))
106   nil)
107
108 (defun maybe-defined-here (name where)
109   (if (and (eq :defined where)
110            (member name *fun-names-in-this-file* :test #'equal))
111       :defined-here
112       where))
113
114 ;;; Return a GLOBAL-VAR structure usable for referencing the global
115 ;;; function NAME.
116 (defun find-global-fun (name latep)
117   (unless (info :function :kind name)
118     (setf (info :function :kind name) :function)
119     (setf (info :function :where-from name) :assumed))
120   (let ((where (info :function :where-from name)))
121     (when (and (eq where :assumed)
122                ;; In the ordinary target Lisp, it's silly to report
123                ;; undefinedness when the function is defined in the
124                ;; running Lisp. But at cross-compile time, the current
125                ;; definedness of a function is irrelevant to the
126                ;; definedness at runtime, which is what matters.
127                #-sb-xc-host (not (fboundp name))
128                ;; LATEP is true when the user has indicated that
129                ;; late-late binding is desired by using eg. a quoted
130                ;; symbol -- in which case it makes little sense to
131                ;; complain about undefined functions.
132                (not latep))
133       (note-undefined-reference name :function))
134     (let ((ftype (info :function :type name))
135           (notinline (fun-lexically-notinline-p name)))
136       (make-global-var
137        :kind :global-function
138        :%source-name name
139        :type (if (or (eq where :declared)
140                      (and (not latep)
141                           (not notinline)
142                           *derive-function-types*))
143                  ftype
144                  (specifier-type 'function))
145        :defined-type (if (and (not latep) (not notinline))
146                          (or (maybe-update-info-for-gf name) ftype)
147                          (specifier-type 'function))
148        :where-from (if notinline
149                        where
150                        (maybe-defined-here name where))))))
151
152 ;;; Have some DEFINED-FUN-FUNCTIONALS of a *FREE-FUNS* entry become invalid?
153 ;;; Drop 'em.
154 ;;;
155 ;;; This was added to fix bug 138 in SBCL. It is possible for a *FREE-FUNS*
156 ;;; entry to contain a DEFINED-FUN whose DEFINED-FUN-FUNCTIONAL object
157 ;;; contained IR1 stuff (NODEs, BLOCKs...) referring to an already compiled
158 ;;; (aka "dead") component. When this IR1 stuff was reused in a new component,
159 ;;; under further obscure circumstances it could be used by
160 ;;; WITH-IR1-ENVIRONMENT-FROM-NODE to generate a binding for
161 ;;; *CURRENT-COMPONENT*. At that point things got all confused, since IR1
162 ;;; conversion was sending code to a component which had already been compiled
163 ;;; and would never be compiled again.
164 ;;;
165 ;;; Note: as of 1.0.24.41 this seems to happen only in XC, and the original
166 ;;; BUGS entry also makes it seem like this might not be an issue at all on
167 ;;; target.
168 (defun clear-invalid-functionals (free-fun)
169   ;; There might be other reasons that *FREE-FUN* entries could
170   ;; become invalid, but the only one we've been bitten by so far
171   ;; (sbcl-0.pre7.118) is this one:
172   (when (defined-fun-p free-fun)
173     (setf (defined-fun-functionals free-fun)
174           (delete-if (lambda (functional)
175                        (or (eq (functional-kind functional) :deleted)
176                            (when (lambda-p functional)
177                              (or
178                               ;; (The main reason for this first test is to bail
179                               ;; out early in cases where the LAMBDA-COMPONENT
180                               ;; call in the second test would fail because links
181                               ;; it needs are uninitialized or invalid.)
182                               ;;
183                               ;; If the BIND node for this LAMBDA is null, then
184                               ;; according to the slot comments, the LAMBDA has
185                               ;; been deleted or its call has been deleted. In
186                               ;; that case, it seems rather questionable to reuse
187                               ;; it, and certainly it shouldn't be necessary to
188                               ;; reuse it, so we cheerfully declare it invalid.
189                               (not (lambda-bind functional))
190                               ;; If this IR1 stuff belongs to a dead component,
191                               ;; then we can't reuse it without getting into
192                               ;; bizarre confusion.
193                               (eq (component-info (lambda-component functional))
194                                   :dead)))))
195                      (defined-fun-functionals free-fun)))
196     nil))
197
198 ;;; If NAME already has a valid entry in *FREE-FUNS*, then return
199 ;;; the value. Otherwise, make a new GLOBAL-VAR using information from
200 ;;; the global environment and enter it in *FREE-FUNS*. If NAME
201 ;;; names a macro or special form, then we error out using the
202 ;;; supplied context which indicates what we were trying to do that
203 ;;; demanded a function.
204 (declaim (ftype (sfunction (t string) global-var) find-free-fun))
205 (defun find-free-fun (name context)
206   (or (let ((old-free-fun (gethash name *free-funs*)))
207         (when old-free-fun
208           (clear-invalid-functionals old-free-fun)
209           old-free-fun))
210       (ecase (info :function :kind name)
211         ;; FIXME: The :MACRO and :SPECIAL-FORM cases could be merged.
212         (:macro
213          (compiler-error "The macro name ~S was found ~A." name context))
214         (:special-form
215          (compiler-error "The special form name ~S was found ~A."
216                          name
217                          context))
218         ((:function nil)
219          (check-fun-name name)
220          (note-if-setf-fun-and-macro name)
221          (let ((expansion (fun-name-inline-expansion name))
222                (inlinep (info :function :inlinep name)))
223            (setf (gethash name *free-funs*)
224                  (if (or expansion inlinep)
225                      (let ((where (info :function :where-from name)))
226                        (make-defined-fun
227                         :%source-name name
228                         :inline-expansion expansion
229                         :inlinep inlinep
230                         :where-from (if (eq inlinep :notinline)
231                                         where
232                                         (maybe-defined-here name where))
233                         :type (if (and (eq inlinep :notinline)
234                                        (neq where :declared))
235                                   (specifier-type 'function)
236                                   (info :function :type name))))
237                      (find-global-fun name nil))))))))
238
239 ;;; Return the LEAF structure for the lexically apparent function
240 ;;; definition of NAME.
241 (declaim (ftype (sfunction (t string) leaf) find-lexically-apparent-fun))
242 (defun find-lexically-apparent-fun (name context)
243   (let ((var (lexenv-find name funs :test #'equal)))
244     (cond (var
245            (unless (leaf-p var)
246              (aver (and (consp var) (eq (car var) 'macro)))
247              (compiler-error "found macro name ~S ~A" name context))
248            var)
249           (t
250            (find-free-fun name context)))))
251
252 (defun maybe-find-free-var (name)
253   (gethash name *free-vars*))
254
255 ;;; Return the LEAF node for a global variable reference to NAME. If
256 ;;; NAME is already entered in *FREE-VARS*, then we just return the
257 ;;; corresponding value. Otherwise, we make a new leaf using
258 ;;; information from the global environment and enter it in
259 ;;; *FREE-VARS*. If the variable is unknown, then we emit a warning.
260 (declaim (ftype (sfunction (t) (or leaf cons heap-alien-info)) find-free-var))
261 (defun find-free-var (name)
262   (unless (symbolp name)
263     (compiler-error "Variable name is not a symbol: ~S." name))
264   (or (gethash name *free-vars*)
265       (let ((kind (info :variable :kind name))
266             (type (info :variable :type name))
267             (where-from (info :variable :where-from name)))
268         (when (eq kind :unknown)
269           (note-undefined-reference name :variable))
270         (setf (gethash name *free-vars*)
271               (case kind
272                 (:alien
273                  (info :variable :alien-info name))
274                 ;; FIXME: The return value in this case should really be
275                 ;; of type SB!C::LEAF.  I don't feel too badly about it,
276                 ;; because the MACRO idiom is scattered throughout this
277                 ;; file, but it should be cleaned up so we're not
278                 ;; throwing random conses around.  --njf 2002-03-23
279                 (:macro
280                  (let ((expansion (info :variable :macro-expansion name))
281                        (type (type-specifier (info :variable :type name))))
282                    `(macro . (the ,type ,expansion))))
283                 (:constant
284                  (let ((value (symbol-value name)))
285                    ;; Override the values of standard symbols in XC,
286                    ;; since we can't redefine them.
287                    #+sb-xc-host
288                    (when (eql (find-symbol (symbol-name name) :cl) name)
289                      (multiple-value-bind (xc-value foundp)
290                          (info :variable :xc-constant-value name)
291                        (cond (foundp
292                               (setf value xc-value))
293                              ((not (eq value name))
294                               (compiler-warn
295                                "Using cross-compilation host's definition of ~S: ~A~%"
296                                name (symbol-value name))))))
297                    (find-constant value name)))
298                 (t
299                  (make-global-var :kind kind
300                                   :%source-name name
301                                   :type type
302                                   :where-from where-from)))))))
303 \f
304 ;;; Grovel over CONSTANT checking for any sub-parts that need to be
305 ;;; processed with MAKE-LOAD-FORM. We have to be careful, because
306 ;;; CONSTANT might be circular. We also check that the constant (and
307 ;;; any subparts) are dumpable at all.
308 (defun maybe-emit-make-load-forms (constant &optional (name nil namep))
309   (let ((xset (alloc-xset)))
310     (labels ((trivialp (value)
311                (typep value
312                       '(or
313                         #-sb-xc-host unboxed-array
314                         #+sb-xc-host (simple-array (unsigned-byte 8) (*))
315                         symbol
316                         number
317                         character
318                         string)))
319              (grovel (value)
320                ;; Unless VALUE is an object which which obviously
321                ;; can't contain other objects
322                (unless (trivialp value)
323                  (if (xset-member-p value xset)
324                      (return-from grovel nil)
325                      (add-to-xset value xset))
326                  (typecase value
327                    (cons
328                     (grovel (car value))
329                     (grovel (cdr value)))
330                    (simple-vector
331                     (dotimes (i (length value))
332                       (grovel (svref value i))))
333                    ((vector t)
334                     (dotimes (i (length value))
335                       (grovel (aref value i))))
336                    ((simple-array t)
337                     ;; Even though the (ARRAY T) branch does the exact
338                     ;; same thing as this branch we do this separately
339                     ;; so that the compiler can use faster versions of
340                     ;; array-total-size and row-major-aref.
341                     (dotimes (i (array-total-size value))
342                       (grovel (row-major-aref value i))))
343                    ((array t)
344                     (dotimes (i (array-total-size value))
345                       (grovel (row-major-aref value i))))
346                    (#+sb-xc-host structure!object
347                     #-sb-xc-host instance
348                     ;; In the target SBCL, we can dump any instance, but
349                     ;; in the cross-compilation host, %INSTANCE-FOO
350                     ;; functions don't work on general instances, only on
351                     ;; STRUCTURE!OBJECTs.
352                     ;;
353                     ;; FIXME: What about funcallable instances with
354                     ;; user-defined MAKE-LOAD-FORM methods?
355                     (when (emit-make-load-form value)
356                       (dotimes (i (- (%instance-length value)
357                                      #+sb-xc-host 0
358                                      #-sb-xc-host (layout-n-untagged-slots
359                                                    (%instance-ref value 0))))
360                         (grovel (%instance-ref value i)))))
361                    (t
362                     (compiler-error
363                      "Objects of type ~S can't be dumped into fasl files."
364                      (type-of value)))))))
365       ;; Dump all non-trivial named constants using the name.
366       (if (and namep (not (typep constant '(or symbol character
367                                             ;; FIXME: Cold init breaks if we
368                                             ;; try to reference FP constants
369                                             ;; thru their names.
370                                             #+sb-xc-host number
371                                             #-sb-xc-host fixnum))))
372           (emit-make-load-form constant name)
373           (grovel constant))))
374   (values))
375 \f
376 ;;;; some flow-graph hacking utilities
377
378 ;;; This function sets up the back link between the node and the
379 ;;; ctran which continues at it.
380 (defun link-node-to-previous-ctran (node ctran)
381   (declare (type node node) (type ctran ctran))
382   (aver (not (ctran-next ctran)))
383   (setf (ctran-next ctran) node)
384   (setf (node-prev node) ctran))
385
386 ;;; This function is used to set the ctran for a node, and thus
387 ;;; determine what is evaluated next. If the ctran has no block, then
388 ;;; we make it be in the block that the node is in. If the ctran heads
389 ;;; its block, we end our block and link it to that block.
390 #!-sb-fluid (declaim (inline use-ctran))
391 (defun use-ctran (node ctran)
392   (declare (type node node) (type ctran ctran))
393   (if (eq (ctran-kind ctran) :unused)
394       (let ((node-block (ctran-block (node-prev node))))
395         (setf (ctran-block ctran) node-block)
396         (setf (ctran-kind ctran) :inside-block)
397         (setf (ctran-use ctran) node)
398         (setf (node-next node) ctran))
399       (%use-ctran node ctran)))
400 (defun %use-ctran (node ctran)
401   (declare (type node node) (type ctran ctran) (inline member))
402   (let ((block (ctran-block ctran))
403         (node-block (ctran-block (node-prev node))))
404     (aver (eq (ctran-kind ctran) :block-start))
405     (when (block-last node-block)
406       (error "~S has already ended." node-block))
407     (setf (block-last node-block) node)
408     (when (block-succ node-block)
409       (error "~S already has successors." node-block))
410     (setf (block-succ node-block) (list block))
411     (when (memq node-block (block-pred block))
412       (error "~S is already a predecessor of ~S." node-block block))
413     (push node-block (block-pred block))))
414
415 ;;; Insert NEW before OLD in the flow-graph.
416 (defun insert-node-before (old new)
417   (let ((prev (node-prev old))
418         (temp (make-ctran)))
419     (ensure-block-start prev)
420     (setf (ctran-next prev) nil)
421     (link-node-to-previous-ctran new prev)
422     (use-ctran new temp)
423     (link-node-to-previous-ctran old temp))
424   (values))
425
426 ;;; This function is used to set the ctran for a node, and thus
427 ;;; determine what receives the value.
428 (defun use-lvar (node lvar)
429   (declare (type valued-node node) (type (or lvar null) lvar))
430   (aver (not (node-lvar node)))
431   (when lvar
432     (setf (node-lvar node) lvar)
433     (cond ((null (lvar-uses lvar))
434            (setf (lvar-uses lvar) node))
435           ((listp (lvar-uses lvar))
436            (aver (not (memq node (lvar-uses lvar))))
437            (push node (lvar-uses lvar)))
438           (t
439            (aver (neq node (lvar-uses lvar)))
440            (setf (lvar-uses lvar) (list node (lvar-uses lvar)))))
441     (reoptimize-lvar lvar)))
442
443 #!-sb-fluid(declaim (inline use-continuation))
444 (defun use-continuation (node ctran lvar)
445   (use-ctran node ctran)
446   (use-lvar node lvar))
447 \f
448 ;;;; exported functions
449
450 ;;; This function takes a form and the top level form number for that
451 ;;; form, and returns a lambda representing the translation of that
452 ;;; form in the current global environment. The returned lambda is a
453 ;;; top level lambda that can be called to cause evaluation of the
454 ;;; forms. This lambda is in the initial component. If FOR-VALUE is T,
455 ;;; then the value of the form is returned from the function,
456 ;;; otherwise NIL is returned.
457 ;;;
458 ;;; This function may have arbitrary effects on the global environment
459 ;;; due to processing of EVAL-WHENs. All syntax error checking is
460 ;;; done, with erroneous forms being replaced by a proxy which signals
461 ;;; an error if it is evaluated. Warnings about possibly inconsistent
462 ;;; or illegal changes to the global environment will also be given.
463 ;;;
464 ;;; We make the initial component and convert the form in a PROGN (and
465 ;;; an optional NIL tacked on the end.) We then return the lambda. We
466 ;;; bind all of our state variables here, rather than relying on the
467 ;;; global value (if any) so that IR1 conversion will be reentrant.
468 ;;; This is necessary for EVAL-WHEN processing, etc.
469 ;;;
470 ;;; The hashtables used to hold global namespace info must be
471 ;;; reallocated elsewhere. Note also that *LEXENV* is not bound, so
472 ;;; that local macro definitions can be introduced by enclosing code.
473 (defun ir1-toplevel (form path for-value &optional (allow-instrumenting t))
474   (declare (list path))
475   (let* ((*current-path* path)
476          (component (make-empty-component))
477          (*current-component* component)
478          (*allow-instrumenting* allow-instrumenting))
479     (setf (component-name component) 'initial-component)
480     (setf (component-kind component) :initial)
481     (let* ((forms (if for-value `(,form) `(,form nil)))
482            (res (ir1-convert-lambda-body
483                  forms ()
484                  :debug-name (debug-name 'top-level-form #+sb-xc-host nil #-sb-xc-host form))))
485       (setf (functional-entry-fun res) res
486             (functional-arg-documentation res) ()
487             (functional-kind res) :toplevel)
488       res)))
489
490 ;;; This function is called on freshly read forms to record the
491 ;;; initial location of each form (and subform.) Form is the form to
492 ;;; find the paths in, and TLF-NUM is the top level form number of the
493 ;;; truly top level form.
494 ;;;
495 ;;; This gets a bit interesting when the source code is circular. This
496 ;;; can (reasonably?) happen in the case of circular list constants.
497 (defun find-source-paths (form tlf-num)
498   (declare (type index tlf-num))
499   (let ((*current-form-number* 0))
500     (sub-find-source-paths form (list tlf-num)))
501   (values))
502 (defun sub-find-source-paths (form path)
503   (unless (get-source-path form)
504     (note-source-path form path)
505     (incf *current-form-number*)
506     (let ((pos 0)
507           (subform form)
508           (trail form))
509       (declare (fixnum pos))
510       (macrolet ((frob ()
511                    `(progn
512                       (when (atom subform) (return))
513                       (let ((fm (car subform)))
514                         (cond ((consp fm)
515                                ;; If it's a cons, recurse.
516                                (sub-find-source-paths fm (cons pos path)))
517                               ((eq 'quote fm)
518                                ;; Don't look into quoted constants.
519                                (return))
520                               ((not (zerop pos))
521                                ;; Otherwise store the containing form. It's not
522                                ;; perfect, but better than nothing.
523                                (note-source-path subform pos path)))
524                         (incf pos))
525                       (setq subform (cdr subform))
526                       (when (eq subform trail) (return)))))
527         (loop
528           (frob)
529           (frob)
530           (setq trail (cdr trail)))))))
531 \f
532 ;;;; IR1-CONVERT, macroexpansion and special form dispatching
533
534 (declaim (ftype (sfunction (ctran ctran (or lvar null) t) (values))
535                 ir1-convert))
536 (macrolet (;; Bind *COMPILER-ERROR-BAILOUT* to a function that throws
537            ;; out of the body and converts a condition signalling form
538            ;; instead. The source form is converted to a string since it
539            ;; may contain arbitrary non-externalizable objects.
540            (ir1-error-bailout ((start next result form) &body body)
541              (with-unique-names (skip condition)
542                `(block ,skip
543                  (let ((,condition (catch 'ir1-error-abort
544                                      (let ((*compiler-error-bailout*
545                                             (lambda (&optional e)
546                                               (throw 'ir1-error-abort e))))
547                                        ,@body
548                                        (return-from ,skip nil)))))
549                    (ir1-convert ,start ,next ,result
550                                 (make-compiler-error-form ,condition
551                                                           ,form)))))))
552
553   ;; Translate FORM into IR1. The code is inserted as the NEXT of the
554   ;; CTRAN START. RESULT is the LVAR which receives the value of the
555   ;; FORM to be translated. The translators call this function
556   ;; recursively to translate their subnodes.
557   ;;
558   ;; As a special hack to make life easier in the compiler, a LEAF
559   ;; IR1-converts into a reference to that LEAF structure. This allows
560   ;; the creation using backquote of forms that contain leaf
561   ;; references, without having to introduce dummy names into the
562   ;; namespace.
563   (defun ir1-convert (start next result form)
564     (ir1-error-bailout (start next result form)
565       (let* ((*current-path* (or (get-source-path form)
566                                  (cons (simplify-source-path-form form)
567                                        *current-path*)))
568              (start (instrument-coverage start nil form)))
569         (cond ((atom form)
570                (cond ((and (symbolp form) (not (keywordp form)))
571                       (ir1-convert-var start next result form))
572                      ((leaf-p form)
573                       (reference-leaf start next result form))
574                      (t
575                       (reference-constant start next result form))))
576               (t
577                (ir1-convert-functoid start next result form)))))
578     (values))
579
580   ;; Generate a reference to a manifest constant, creating a new leaf
581   ;; if necessary.
582   (defun reference-constant (start next result value)
583     (declare (type ctran start next)
584              (type (or lvar null) result))
585     (ir1-error-bailout (start next result value)
586       (let* ((leaf (find-constant value))
587              (res (make-ref leaf)))
588         (push res (leaf-refs leaf))
589         (link-node-to-previous-ctran res start)
590         (use-continuation res next result)))
591     (values)))
592
593 ;;; Add FUNCTIONAL to the COMPONENT-REANALYZE-FUNCTIONALS, unless it's
594 ;;; some trivial type for which reanalysis is a trivial no-op, or
595 ;;; unless it doesn't belong in this component at all.
596 ;;;
597 ;;; FUNCTIONAL is returned.
598 (defun maybe-reanalyze-functional (functional)
599
600   (aver (not (eql (functional-kind functional) :deleted))) ; bug 148
601   (aver-live-component *current-component*)
602
603   ;; When FUNCTIONAL is of a type for which reanalysis isn't a trivial
604   ;; no-op
605   (when (typep functional '(or optional-dispatch clambda))
606
607     ;; When FUNCTIONAL knows its component
608     (when (lambda-p functional)
609       (aver (eql (lambda-component functional) *current-component*)))
610
611     (pushnew functional
612              (component-reanalyze-functionals *current-component*)))
613
614   functional)
615
616 ;;; Generate a REF node for LEAF, frobbing the LEAF structure as
617 ;;; needed. If LEAF represents a defined function which has already
618 ;;; been converted, and is not :NOTINLINE, then reference the
619 ;;; functional instead.
620 (defun reference-leaf (start next result leaf &optional (name '.anonymous.))
621   (declare (type ctran start next) (type (or lvar null) result) (type leaf leaf))
622   (assure-leaf-live-p leaf)
623   (let* ((type (lexenv-find leaf type-restrictions))
624          (leaf (or (and (defined-fun-p leaf)
625                         (not (eq (defined-fun-inlinep leaf)
626                                  :notinline))
627                         (let ((functional (defined-fun-functional leaf)))
628                           (when (and functional (not (functional-kind functional)))
629                             (maybe-reanalyze-functional functional))))
630                    (when (and (lambda-p leaf)
631                               (memq (functional-kind leaf)
632                                     '(nil :optional)))
633                      (maybe-reanalyze-functional leaf))
634                    leaf))
635          (ref (make-ref leaf name)))
636     (push ref (leaf-refs leaf))
637     (setf (leaf-ever-used leaf) t)
638     (link-node-to-previous-ctran ref start)
639     (cond (type (let* ((ref-ctran (make-ctran))
640                        (ref-lvar (make-lvar))
641                        (cast (make-cast ref-lvar
642                                         (make-single-value-type type)
643                                         (lexenv-policy *lexenv*))))
644                   (setf (lvar-dest ref-lvar) cast)
645                   (use-continuation ref ref-ctran ref-lvar)
646                   (link-node-to-previous-ctran cast ref-ctran)
647                   (use-continuation cast next result)))
648           (t (use-continuation ref next result)))))
649
650 ;;; Convert a reference to a symbolic constant or variable. If the
651 ;;; symbol is entered in the LEXENV-VARS we use that definition,
652 ;;; otherwise we find the current global definition. This is also
653 ;;; where we pick off symbol macro and alien variable references.
654 (defun ir1-convert-var (start next result name)
655   (declare (type ctran start next) (type (or lvar null) result) (symbol name))
656   (let ((var (or (lexenv-find name vars) (find-free-var name))))
657     (if (and (global-var-p var) (not result))
658         ;; KLUDGE: If the reference is dead, convert using SYMBOL-VALUE
659         ;; which is not flushable, so that unbound dead variables signal
660         ;; an error (bug 412).
661         (ir1-convert start next result
662                      (if (eq (global-var-kind var) :global)
663                          `(symbol-global-value ',name)
664                          `(symbol-value ',name)))
665         (etypecase var
666           (leaf
667            (when (lambda-var-p var)
668              (let ((home (ctran-home-lambda-or-null start)))
669                (when home
670                  (sset-adjoin var (lambda-calls-or-closes home))))
671              (when (lambda-var-ignorep var)
672                ;; (ANSI's specification for the IGNORE declaration requires
673                ;; that this be a STYLE-WARNING, not a full WARNING.)
674                #-sb-xc-host
675                (compiler-style-warn "reading an ignored variable: ~S" name)
676                ;; there's no need for us to accept ANSI's lameness when
677                ;; processing our own code, though.
678                #+sb-xc-host
679                (warn "reading an ignored variable: ~S" name)))
680            (reference-leaf start next result var name))
681           (cons
682            (aver (eq (car var) 'macro))
683            ;; FIXME: [Free] type declarations. -- APD, 2002-01-26
684            (ir1-convert start next result (cdr var)))
685           (heap-alien-info
686            (ir1-convert start next result `(%heap-alien ',var))))))
687   (values))
688
689 ;;; Find a compiler-macro for a form, taking FUNCALL into account.
690 (defun find-compiler-macro (opname form)
691   (if (eq opname 'funcall)
692       (let ((fun-form (cadr form)))
693         (cond ((and (consp fun-form) (eq 'function (car fun-form)))
694                (let ((real-fun (cadr fun-form)))
695                  (if (legal-fun-name-p real-fun)
696                      (values (sb!xc:compiler-macro-function real-fun *lexenv*)
697                              real-fun)
698                      (values nil nil))))
699               ((sb!xc:constantp fun-form *lexenv*)
700                (let ((fun (constant-form-value fun-form *lexenv*)))
701                  (if (legal-fun-name-p fun)
702                      ;; CLHS tells us that local functions must shadow
703                      ;; compiler-macro-functions, but since the call is
704                      ;; through a name, we are obviously interested
705                      ;; in the global function.
706                      (values (sb!xc:compiler-macro-function fun nil) fun)
707                      (values nil nil))))
708               (t
709                (values nil nil))))
710       (if (legal-fun-name-p opname)
711           (values (sb!xc:compiler-macro-function opname *lexenv*) opname)
712           (values nil nil))))
713
714 ;;; Picks of special forms and compiler-macro expansions, and hands
715 ;;; the rest to IR1-CONVERT-COMMON-FUNCTOID
716 (defun ir1-convert-functoid (start next result form)
717   (let* ((op (car form))
718          (translator (and (symbolp op) (info :function :ir1-convert op))))
719     (cond (translator
720            (when (sb!xc:compiler-macro-function op *lexenv*)
721              (compiler-warn "ignoring compiler macro for special form"))
722            (funcall translator start next result form))
723           (t
724            (multiple-value-bind (cmacro-fun cmacro-fun-name)
725                (find-compiler-macro op form)
726              (if (and cmacro-fun
727                       ;; CLHS 3.2.2.1.3 specifies that NOTINLINE
728                       ;; suppresses compiler-macros.
729                       (not (fun-lexically-notinline-p cmacro-fun-name)))
730                  (let ((res (careful-expand-macro cmacro-fun form t)))
731                    (cond ((eq res form)
732                           (ir1-convert-common-functoid start next result form op))
733                          (t
734                           (unless (policy *lexenv* (zerop store-xref-data))
735                             (record-call cmacro-fun-name (ctran-block start) *current-path*))
736                           (ir1-convert start next result res))))
737                  (ir1-convert-common-functoid start next result form op)))))))
738
739 ;;; Handles the "common" cases: any other forms except special forms
740 ;;; and compiler-macros.
741 (defun ir1-convert-common-functoid (start next result form op)
742   (cond ((or (symbolp op) (leaf-p op))
743          (let ((lexical-def (if (leaf-p op) op (lexenv-find op funs))))
744            (typecase lexical-def
745              (null
746               (ir1-convert-global-functoid start next result form op))
747              (functional
748               (ir1-convert-local-combination start next result form
749                                              lexical-def))
750              (global-var
751               (ir1-convert-srctran start next result lexical-def form))
752              (t
753               (aver (and (consp lexical-def) (eq (car lexical-def) 'macro)))
754               (ir1-convert start next result
755                            (careful-expand-macro (cdr lexical-def) form))))))
756         ((or (atom op) (not (eq (car op) 'lambda)))
757          (compiler-error "illegal function call"))
758         (t
759          ;; implicitly (LAMBDA ..) because the LAMBDA expression is
760          ;; the CAR of an executed form.
761          (ir1-convert start next result `(%funcall ,@form)))))
762
763 ;;; Convert anything that looks like a global function call.
764 (defun ir1-convert-global-functoid (start next result form fun)
765   (declare (type ctran start next) (type (or lvar null) result)
766            (list form))
767   ;; FIXME: Couldn't all the INFO calls here be converted into
768   ;; standard CL functions, like MACRO-FUNCTION or something? And what
769   ;; happens with lexically-defined (MACROLET) macros here, anyway?
770   (ecase (info :function :kind fun)
771     (:macro
772      (ir1-convert start next result
773                   (careful-expand-macro (info :function :macro-function fun)
774                                         form))
775      (unless (policy *lexenv* (zerop store-xref-data))
776        (record-macroexpansion fun (ctran-block start) *current-path*)))
777     ((nil :function)
778      (ir1-convert-srctran start next result
779                           (find-free-fun fun "shouldn't happen! (no-cmacro)")
780                           form))))
781
782 (defun muffle-warning-or-die ()
783   (muffle-warning)
784   (bug "no MUFFLE-WARNING restart"))
785
786 ;;; Expand FORM using the macro whose MACRO-FUNCTION is FUN, trapping
787 ;;; errors which occur during the macroexpansion.
788 (defun careful-expand-macro (fun form &optional cmacro)
789   (flet (;; Return a string to use as a prefix in error reporting,
790          ;; telling something about which form caused the problem.
791          (wherestring ()
792            (let (;; We rely on the printer to abbreviate FORM.
793                  (*print-length* 3)
794                  (*print-level* 3))
795              (format
796               nil
797               #-sb-xc-host "~@<~;during ~A of ~S. Use ~S to intercept:~%~:@>"
798               ;; longer message to avoid ambiguity "Was it the xc host
799               ;; or the cross-compiler which encountered the problem?"
800               #+sb-xc-host "~@<~;during cross-compiler ~A of ~S. Use ~S to intercept:~%~:@>"
801               (if cmacro "compiler-macroexpansion" "macroexpansion")
802               form
803               '*break-on-signals*))))
804     (handler-bind (;; KLUDGE: CMU CL in its wisdom (version 2.4.6 for Debian
805                    ;; Linux, anyway) raises a CL:WARNING condition (not a
806                    ;; CL:STYLE-WARNING) for undefined symbols when converting
807                    ;; interpreted functions, causing COMPILE-FILE to think the
808                    ;; file has a real problem, causing COMPILE-FILE to return
809                    ;; FAILURE-P set (not just WARNINGS-P set). Since undefined
810                    ;; symbol warnings are often harmless forward references,
811                    ;; and since it'd be inordinately painful to try to
812                    ;; eliminate all such forward references, these warnings
813                    ;; are basically unavoidable. Thus, we need to coerce the
814                    ;; system to work through them, and this code does so, by
815                    ;; crudely suppressing all warnings in cross-compilation
816                    ;; macroexpansion. -- WHN 19990412
817                    #+(and cmu sb-xc-host)
818                    (warning (lambda (c)
819                               (compiler-notify
820                                "~@<~A~:@_~
821                                 ~A~:@_~
822                                 ~@<(KLUDGE: That was a non-STYLE WARNING. ~
823                                    Ordinarily that would cause compilation to ~
824                                    fail. However, since we're running under ~
825                                    CMU CL, and since CMU CL emits non-STYLE ~
826                                    warnings for safe, hard-to-fix things (e.g. ~
827                                    references to not-yet-defined functions) ~
828                                    we're going to have to ignore it and ~
829                                    proceed anyway. Hopefully we're not ~
830                                    ignoring anything  horrible here..)~:@>~:>"
831                                (wherestring)
832                                c)
833                               (muffle-warning-or-die)))
834                    (error (lambda (c)
835                             (compiler-error "~@<~A~@:_ ~A~:>"
836                                             (wherestring) c))))
837       (funcall sb!xc:*macroexpand-hook* fun form *lexenv*))))
838 \f
839 ;;;; conversion utilities
840
841 ;;; Convert a bunch of forms, discarding all the values except the
842 ;;; last. If there aren't any forms, then translate a NIL.
843 (declaim (ftype (sfunction (ctran ctran (or lvar null) list) (values))
844                 ir1-convert-progn-body))
845 (defun ir1-convert-progn-body (start next result body)
846   (if (endp body)
847       (reference-constant start next result nil)
848       (let ((this-start start)
849             (forms body))
850         (loop
851           (let ((form (car forms)))
852             (setf this-start
853                   (maybe-instrument-progn-like this-start forms form))
854             (when (endp (cdr forms))
855               (ir1-convert this-start next result form)
856               (return))
857             (let ((this-ctran (make-ctran)))
858               (ir1-convert this-start this-ctran nil form)
859               (setq this-start this-ctran
860                     forms (cdr forms)))))))
861   (values))
862
863 \f
864 ;;;; code coverage
865
866 ;;; Check the policy for whether we should generate code coverage
867 ;;; instrumentation. If not, just return the original START
868 ;;; ctran. Otherwise insert code coverage instrumentation after
869 ;;; START, and return the new ctran.
870 (defun instrument-coverage (start mode form)
871   ;; We don't actually use FORM for anything, it's just convenient to
872   ;; have around when debugging the instrumentation.
873   (declare (ignore form))
874   (if (and (policy *lexenv* (> store-coverage-data 0))
875            *code-coverage-records*
876            *allow-instrumenting*)
877       (let ((path (source-path-original-source *current-path*)))
878         (when mode
879           (push mode path))
880         (if (member (ctran-block start)
881                     (gethash path *code-coverage-blocks*))
882             ;; If this source path has already been instrumented in
883             ;; this block, don't instrument it again.
884             start
885             (let ((store
886                    ;; Get an interned record cons for the path. A cons
887                    ;; with the same object identity must be used for
888                    ;; each instrument for the same block.
889                    (or (gethash path *code-coverage-records*)
890                        (setf (gethash path *code-coverage-records*)
891                              (cons path +code-coverage-unmarked+))))
892                   (next (make-ctran))
893                   (*allow-instrumenting* nil))
894               (push (ctran-block start)
895                     (gethash path *code-coverage-blocks*))
896               (let ((*allow-instrumenting* nil))
897                 (ir1-convert start next nil
898                              `(locally
899                                   (declare (optimize speed
900                                                      (safety 0)
901                                                      (debug 0)
902                                                      (check-constant-modification 0)))
903                                 ;; We're being naughty here, and
904                                 ;; modifying constant data. That's ok,
905                                 ;; we know what we're doing.
906                                 (%rplacd ',store t))))
907               next)))
908       start))
909
910 ;;; In contexts where we don't have a source location for FORM
911 ;;; e.g. due to it not being a cons, but where we have a source
912 ;;; location for the enclosing cons, use the latter source location if
913 ;;; available. This works pretty well in practice, since many PROGNish
914 ;;; macroexpansions will just directly splice a block of forms into
915 ;;; some enclosing form with `(progn ,@body), thus retaining the
916 ;;; EQness of the conses.
917 (defun maybe-instrument-progn-like (start forms form)
918   (or (when (and *allow-instrumenting*
919                  (not (get-source-path form)))
920         (let ((*current-path* (get-source-path forms)))
921           (when *current-path*
922             (instrument-coverage start nil form))))
923       start))
924
925 (defun record-code-coverage (info cc)
926   (setf (gethash info *code-coverage-info*) cc))
927
928 (defun clear-code-coverage ()
929   (clrhash *code-coverage-info*))
930
931 (defun reset-code-coverage ()
932   (maphash (lambda (info cc)
933              (declare (ignore info))
934              (dolist (cc-entry cc)
935                (setf (cdr cc-entry) +code-coverage-unmarked+)))
936            *code-coverage-info*))
937
938 (defun code-coverage-record-marked (record)
939   (aver (consp record))
940   (ecase (cdr record)
941     ((#.+code-coverage-unmarked+) nil)
942     ((t) t)))
943
944 \f
945 ;;;; converting combinations
946
947 ;;; Does this form look like something that we should add single-stepping
948 ;;; instrumentation for?
949 (defun step-form-p (form)
950   (flet ((step-symbol-p (symbol)
951            (not (member (symbol-package symbol)
952                         (load-time-value
953                          ;; KLUDGE: packages we're not interested in
954                          ;; stepping.
955                          (mapcar #'find-package '(sb!c sb!int sb!impl
956                                                   sb!kernel sb!pcl)))))))
957     (and *allow-instrumenting*
958          (policy *lexenv* (= insert-step-conditions 3))
959          (listp form)
960          (symbolp (car form))
961          (step-symbol-p (car form)))))
962
963 ;;; Convert a function call where the function FUN is a LEAF. FORM is
964 ;;; the source for the call. We return the COMBINATION node so that
965 ;;; the caller can poke at it if it wants to.
966 (declaim (ftype (sfunction (ctran ctran (or lvar null) list leaf) combination)
967                 ir1-convert-combination))
968 (defun ir1-convert-combination (start next result form fun)
969   (let ((ctran (make-ctran))
970         (fun-lvar (make-lvar)))
971     (ir1-convert start ctran fun-lvar `(the (or function symbol) ,fun))
972     (let ((combination
973            (ir1-convert-combination-args fun-lvar ctran next result
974                                          (cdr form))))
975       (when (step-form-p form)
976         ;; Store a string representation of the form in the
977         ;; combination node. This will let the IR2 translator know
978         ;; that we want stepper instrumentation for this node. The
979         ;; string will be stored in the debug-info by DUMP-1-LOCATION.
980         (setf (combination-step-info combination)
981               (let ((*print-pretty* t)
982                     (*print-circle* t)
983                     (*print-readably* nil))
984                 (prin1-to-string form))))
985       combination)))
986
987 ;;; Convert the arguments to a call and make the COMBINATION
988 ;;; node. FUN-LVAR yields the function to call. ARGS is the list of
989 ;;; arguments for the call, which defaults to the cdr of source. We
990 ;;; return the COMBINATION node.
991 (defun ir1-convert-combination-args (fun-lvar start next result args)
992   (declare (type ctran start next)
993            (type lvar fun-lvar)
994            (type (or lvar null) result)
995            (list args))
996   (let ((node (make-combination fun-lvar)))
997     (setf (lvar-dest fun-lvar) node)
998     (collect ((arg-lvars))
999       (let ((this-start start)
1000             (forms args))
1001         (dolist (arg args)
1002           (setf this-start
1003                 (maybe-instrument-progn-like this-start forms arg))
1004           (setf forms (cdr forms))
1005           (let ((this-ctran (make-ctran))
1006                 (this-lvar (make-lvar node)))
1007             (ir1-convert this-start this-ctran this-lvar arg)
1008             (setq this-start this-ctran)
1009             (arg-lvars this-lvar)))
1010         (link-node-to-previous-ctran node this-start)
1011         (use-continuation node next result)
1012         (setf (combination-args node) (arg-lvars))))
1013     node))
1014
1015 ;;; Convert a call to a global function. If not :NOTINLINE, then we do
1016 ;;; source transforms and try out any inline expansion. If there is no
1017 ;;; expansion, but is :INLINE, then give an efficiency note (unless a
1018 ;;; known function which will quite possibly be open-coded.) Next, we
1019 ;;; go to ok-combination conversion.
1020 (defun ir1-convert-srctran (start next result var form)
1021   (declare (type ctran start next) (type (or lvar null) result)
1022            (type global-var var))
1023   (let ((inlinep (when (defined-fun-p var)
1024                    (defined-fun-inlinep var))))
1025     (if (eq inlinep :notinline)
1026         (ir1-convert-combination start next result form var)
1027         (let* ((name (leaf-source-name var))
1028                (transform (info :function :source-transform name)))
1029           (if transform
1030               (multiple-value-bind (transformed pass) (funcall transform form)
1031                 (cond (pass
1032                        (ir1-convert-maybe-predicate start next result form var))
1033                       (t
1034                        (unless (policy *lexenv* (zerop store-xref-data))
1035                          (record-call name (ctran-block start) *current-path*))
1036                        (ir1-convert start next result transformed))))
1037               (ir1-convert-maybe-predicate start next result form var))))))
1038
1039 ;;; KLUDGE: If we insert a synthetic IF for a function with the PREDICATE
1040 ;;; attribute, don't generate any branch coverage instrumentation for it.
1041 (defvar *instrument-if-for-code-coverage* t)
1042
1043 ;;; If the function has the PREDICATE attribute, and the RESULT's DEST
1044 ;;; isn't an IF, then we convert (IF <form> T NIL), ensuring that a
1045 ;;; predicate always appears in a conditional context.
1046 ;;;
1047 ;;; If the function isn't a predicate, then we call
1048 ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE.
1049 (defun ir1-convert-maybe-predicate (start next result form var)
1050   (declare (type ctran start next)
1051            (type (or lvar null) result)
1052            (list form)
1053            (type global-var var))
1054   (let ((info (info :function :info (leaf-source-name var))))
1055     (if (and info
1056              (ir1-attributep (fun-info-attributes info) predicate)
1057              (not (if-p (and result (lvar-dest result)))))
1058         (let ((*instrument-if-for-code-coverage* nil))
1059           (ir1-convert start next result `(if ,form t nil)))
1060         (ir1-convert-combination-checking-type start next result form var))))
1061
1062 ;;; Actually really convert a global function call that we are allowed
1063 ;;; to early-bind.
1064 ;;;
1065 ;;; If we know the function type of the function, then we check the
1066 ;;; call for syntactic legality with respect to the declared function
1067 ;;; type. If it is impossible to determine whether the call is correct
1068 ;;; due to non-constant keywords, then we give up, marking the call as
1069 ;;; :FULL to inhibit further error messages. We return true when the
1070 ;;; call is legal.
1071 ;;;
1072 ;;; If the call is legal, we also propagate type assertions from the
1073 ;;; function type to the arg and result lvars. We do this now so that
1074 ;;; IR1 optimize doesn't have to redundantly do the check later so
1075 ;;; that it can do the type propagation.
1076 (defun ir1-convert-combination-checking-type (start next result form var)
1077   (declare (type ctran start next) (type (or lvar null) result)
1078            (list form)
1079            (type leaf var))
1080   (let* ((node (ir1-convert-combination start next result form var))
1081          (fun-lvar (basic-combination-fun node))
1082          (type (leaf-type var)))
1083     (when (validate-call-type node type var t)
1084       (setf (lvar-%derived-type fun-lvar)
1085             (make-single-value-type type))
1086       (setf (lvar-reoptimize fun-lvar) nil)))
1087   (values))
1088
1089 ;;; Convert a call to a local function, or if the function has already
1090 ;;; been LET converted, then throw FUNCTIONAL to
1091 ;;; LOCALL-ALREADY-LET-CONVERTED. The THROW should only happen when we
1092 ;;; are converting inline expansions for local functions during
1093 ;;; optimization.
1094 (defun ir1-convert-local-combination (start next result form functional)
1095   (assure-functional-live-p functional)
1096   (ir1-convert-combination start next result
1097                            form
1098                            (maybe-reanalyze-functional functional)))
1099 \f
1100 ;;;; PROCESS-DECLS
1101
1102 ;;; Given a list of LAMBDA-VARs and a variable name, return the
1103 ;;; LAMBDA-VAR for that name, or NIL if it isn't found. We return the
1104 ;;; *last* variable with that name, since LET* bindings may be
1105 ;;; duplicated, and declarations always apply to the last.
1106 (declaim (ftype (sfunction (list symbol) (or lambda-var list))
1107                 find-in-bindings))
1108 (defun find-in-bindings (vars name)
1109   (let ((found nil))
1110     (dolist (var vars)
1111       (cond ((leaf-p var)
1112              (when (eq (leaf-source-name var) name)
1113                (setq found var))
1114              (let ((info (lambda-var-arg-info var)))
1115                (when info
1116                  (let ((supplied-p (arg-info-supplied-p info)))
1117                    (when (and supplied-p
1118                               (eq (leaf-source-name supplied-p) name))
1119                      (setq found supplied-p))))))
1120             ((and (consp var) (eq (car var) name))
1121              (setf found (cdr var)))))
1122     found))
1123
1124 ;;; Called by PROCESS-DECLS to deal with a variable type declaration.
1125 ;;; If a LAMBDA-VAR being bound, we intersect the type with the var's
1126 ;;; type, otherwise we add a type restriction on the var. If a symbol
1127 ;;; macro, we just wrap a THE around the expansion.
1128 (defun process-type-decl (decl res vars context)
1129   (declare (list decl vars) (type lexenv res))
1130   (let ((type (compiler-specifier-type (first decl))))
1131     (collect ((restr nil cons)
1132              (new-vars nil cons))
1133       (dolist (var-name (rest decl))
1134         (when (boundp var-name)
1135           (program-assert-symbol-home-package-unlocked
1136            context var-name "declaring the type of ~A"))
1137         (let* ((bound-var (find-in-bindings vars var-name))
1138                (var (or bound-var
1139                         (lexenv-find var-name vars)
1140                         (find-free-var var-name))))
1141           (etypecase var
1142             (leaf
1143              (flet
1144                  ((process-var (var bound-var)
1145                     (let* ((old-type (or (lexenv-find var type-restrictions)
1146                                          (leaf-type var)))
1147                            (int (if (or (fun-type-p type)
1148                                         (fun-type-p old-type))
1149                                     type
1150                                     (type-approx-intersection2
1151                                      old-type type))))
1152                       (cond ((eq int *empty-type*)
1153                              (unless (policy *lexenv* (= inhibit-warnings 3))
1154                                (warn
1155                                 'type-warning
1156                                 :format-control
1157                                 "The type declarations ~S and ~S for ~S conflict."
1158                                 :format-arguments
1159                                 (list
1160                                  (type-specifier old-type)
1161                                  (type-specifier type)
1162                                  var-name))))
1163                             (bound-var
1164                              (setf (leaf-type bound-var) int
1165                                    (leaf-where-from bound-var) :declared))
1166                             (t
1167                              (restr (cons var int)))))))
1168                (process-var var bound-var)
1169                (awhen (and (lambda-var-p var)
1170                            (lambda-var-specvar var))
1171                       (process-var it nil))))
1172             (cons
1173              ;; FIXME: non-ANSI weirdness
1174              (aver (eq (car var) 'macro))
1175              (new-vars `(,var-name . (macro . (the ,(first decl)
1176                                                 ,(cdr var))))))
1177             (heap-alien-info
1178              (compiler-error
1179               "~S is an alien variable, so its type can't be declared."
1180               var-name)))))
1181
1182       (if (or (restr) (new-vars))
1183           (make-lexenv :default res
1184                        :type-restrictions (restr)
1185                        :vars (new-vars))
1186           res))))
1187
1188 ;;; This is somewhat similar to PROCESS-TYPE-DECL, but handles
1189 ;;; declarations for function variables. In addition to allowing
1190 ;;; declarations for functions being bound, we must also deal with
1191 ;;; declarations that constrain the type of lexically apparent
1192 ;;; functions.
1193 (defun process-ftype-decl (spec res names fvars context)
1194   (declare (type list names fvars)
1195            (type lexenv res))
1196   (let ((type (compiler-specifier-type spec)))
1197     (collect ((res nil cons))
1198       (dolist (name names)
1199         (when (fboundp name)
1200           (program-assert-symbol-home-package-unlocked
1201            context name "declaring the ftype of ~A"))
1202         (let ((found (find name fvars :key #'leaf-source-name :test #'equal)))
1203           (cond
1204            (found
1205             (setf (leaf-type found) type)
1206             (assert-definition-type found type
1207                                     :unwinnage-fun #'compiler-notify
1208                                     :where "FTYPE declaration"))
1209            (t
1210             (res (cons (find-lexically-apparent-fun
1211                         name "in a function type declaration")
1212                        type))))))
1213       (if (res)
1214           (make-lexenv :default res :type-restrictions (res))
1215           res))))
1216
1217 ;;; Process a special declaration, returning a new LEXENV. A non-bound
1218 ;;; special declaration is instantiated by throwing a special variable
1219 ;;; into the variables if BINDING-FORM-P is NIL, or otherwise into
1220 ;;; *POST-BINDING-VARIABLE-LEXENV*.
1221 (defun process-special-decl (spec res vars binding-form-p context)
1222   (declare (list spec vars) (type lexenv res))
1223   (collect ((new-venv nil cons))
1224     (dolist (name (cdr spec))
1225       ;; While CLHS seems to allow local SPECIAL declarations for constants,
1226       ;; whatever the semantics are supposed to be is not at all clear to me
1227       ;; -- since constants aren't allowed to be bound it should be a no-op as
1228       ;; no-one can observe the difference portably, but specials are allowed
1229       ;; to be bound... yet nowhere does it say that the special declaration
1230       ;; removes the constantness. Call it a spec bug and prohibit it. Same
1231       ;; for GLOBAL variables.
1232       (let ((kind (info :variable :kind name)))
1233         (unless (member kind '(:special :unknown))
1234           (error "Can't declare ~(~A~) variable locally special: ~S" kind name)))
1235       (program-assert-symbol-home-package-unlocked
1236        context name "declaring ~A special")
1237       (let ((var (find-in-bindings vars name)))
1238         (etypecase var
1239           (cons
1240            (aver (eq (car var) 'macro))
1241            (compiler-error
1242             "~S is a symbol-macro and thus can't be declared special."
1243             name))
1244           (lambda-var
1245            (when (lambda-var-ignorep var)
1246              ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1247              ;; requires that this be a STYLE-WARNING, not a full WARNING.
1248              (compiler-style-warn
1249               "The ignored variable ~S is being declared special."
1250               name))
1251            (setf (lambda-var-specvar var)
1252                  (specvar-for-binding name)))
1253           (null
1254            (unless (or (assoc name (new-venv) :test #'eq))
1255              (new-venv (cons name (specvar-for-binding name))))))))
1256     (cond (binding-form-p
1257            (setf *post-binding-variable-lexenv*
1258                  (append (new-venv) *post-binding-variable-lexenv*))
1259            res)
1260           ((new-venv)
1261            (make-lexenv :default res :vars (new-venv)))
1262           (t
1263            res))))
1264
1265 ;;; Return a DEFINED-FUN which copies a GLOBAL-VAR but for its INLINEP
1266 ;;; (and TYPE if notinline), plus type-restrictions from the lexenv.
1267 (defun make-new-inlinep (var inlinep local-type)
1268   (declare (type global-var var) (type inlinep inlinep))
1269   (let* ((type (if (and (eq inlinep :notinline)
1270                         (not (eq (leaf-where-from var) :declared)))
1271                    (specifier-type 'function)
1272                    (leaf-type var)))
1273          (res (make-defined-fun
1274                :%source-name (leaf-source-name var)
1275                :where-from (leaf-where-from var)
1276                :type (if local-type
1277                          (type-intersection local-type type)
1278                          type)
1279                :inlinep inlinep)))
1280     (when (defined-fun-p var)
1281       (setf (defined-fun-inline-expansion res)
1282             (defined-fun-inline-expansion var))
1283       (setf (defined-fun-functionals res)
1284             (defined-fun-functionals var)))
1285     ;; FIXME: Is this really right? Needs we not set the FUNCTIONAL
1286     ;; to the original global-var?
1287     res))
1288
1289 ;;; Parse an inline/notinline declaration. If it's a local function we're
1290 ;;; defining, set its INLINEP. If a global function, add a new FENV entry.
1291 (defun process-inline-decl (spec res fvars)
1292   (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq)))
1293         (new-fenv ()))
1294     (dolist (name (rest spec))
1295       (let ((fvar (find name fvars :key #'leaf-source-name :test #'equal)))
1296         (if fvar
1297             (setf (functional-inlinep fvar) sense)
1298             (let ((found (find-lexically-apparent-fun
1299                           name "in an inline or notinline declaration")))
1300               (etypecase found
1301                 (functional
1302                  (when (policy *lexenv* (>= speed inhibit-warnings))
1303                    (compiler-notify "ignoring ~A declaration not at ~
1304                                      definition of local function:~%  ~S"
1305                                     sense name)))
1306                 (global-var
1307                  (let ((type
1308                         (cdr (assoc found (lexenv-type-restrictions res)))))
1309                    (push (cons name (make-new-inlinep found sense type))
1310                          new-fenv))))))))
1311     (if new-fenv
1312         (make-lexenv :default res :funs new-fenv)
1313         res)))
1314
1315 ;;; like FIND-IN-BINDINGS, but looks for #'FOO in the FVARS
1316 (defun find-in-bindings-or-fbindings (name vars fvars)
1317   (declare (list vars fvars))
1318   (if (consp name)
1319       (destructuring-bind (wot fn-name) name
1320         (unless (eq wot 'function)
1321           (compiler-error "The function or variable name ~S is unrecognizable."
1322                           name))
1323         (find fn-name fvars :key #'leaf-source-name :test #'equal))
1324       (find-in-bindings vars name)))
1325
1326 ;;; Process an ignore/ignorable declaration, checking for various losing
1327 ;;; conditions.
1328 (defun process-ignore-decl (spec vars fvars)
1329   (declare (list spec vars fvars))
1330   (dolist (name (rest spec))
1331     (let ((var (find-in-bindings-or-fbindings name vars fvars)))
1332       (cond
1333         ((not var)
1334          ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1335          ;; requires that this be a STYLE-WARNING, not a full WARNING.
1336          (multiple-value-call #'compiler-style-warn
1337            "~A declaration for ~A: ~A"
1338            (first spec)
1339            (if (symbolp name)
1340                (values
1341                 (case (info :variable :kind name)
1342                   (:special "a special variable")
1343                   (:global "a global lexical variable")
1344                   (:alien "a global alien variable")
1345                   (t "an unknown variable"))
1346                 name)
1347                (values
1348                 (if (info :function :kind (second name))
1349                     "a global function"
1350                     "an unknown function")
1351                 (second name)))))
1352         ((and (consp var) (eq (car var) 'macro))
1353          ;; Just ignore the IGNORE decl: we don't currently signal style-warnings
1354          ;; for unused symbol-macros, so there's no need to do anything.
1355          )
1356         ((functional-p var)
1357          (setf (leaf-ever-used var) t))
1358         ((and (lambda-var-specvar var) (eq (first spec) 'ignore))
1359          ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1360          ;; requires that this be a STYLE-WARNING, not a full WARNING.
1361          (compiler-style-warn "Declaring special variable ~S to be ~A"
1362                               name
1363                               (first spec)))
1364         ((eq (first spec) 'ignorable)
1365          (setf (leaf-ever-used var) t))
1366         (t
1367          (setf (lambda-var-ignorep var) t)))))
1368   (values))
1369
1370 (defun process-dx-decl (names vars fvars kind)
1371   (let ((dx (cond ((eq 'truly-dynamic-extent kind)
1372                    :truly)
1373                   ((and (eq 'dynamic-extent kind)
1374                         *stack-allocate-dynamic-extent*)
1375                    t))))
1376     (if dx
1377         (dolist (name names)
1378           (cond
1379             ((symbolp name)
1380              (let* ((bound-var (find-in-bindings vars name))
1381                     (var (or bound-var
1382                              (lexenv-find name vars)
1383                              (maybe-find-free-var name))))
1384                (etypecase var
1385                  (leaf
1386                   (if bound-var
1387                       (setf (leaf-dynamic-extent var) dx)
1388                       (compiler-notify
1389                        "Ignoring free DYNAMIC-EXTENT declaration: ~S" name)))
1390                  (cons
1391                   (compiler-error "DYNAMIC-EXTENT on symbol-macro: ~S" name))
1392                  (heap-alien-info
1393                   (compiler-error "DYNAMIC-EXTENT on alien-variable: ~S"
1394                                   name))
1395                  (null
1396                   (compiler-style-warn
1397                    "Unbound variable declared DYNAMIC-EXTENT: ~S" name)))))
1398             ((and (consp name)
1399                   (eq (car name) 'function)
1400                   (null (cddr name))
1401                   (valid-function-name-p (cadr name)))
1402              (let* ((fname (cadr name))
1403                     (bound-fun (find fname fvars
1404                                      :key #'leaf-source-name
1405                                      :test #'equal))
1406                     (fun (or bound-fun (lexenv-find fname funs))))
1407                (etypecase fun
1408                  (leaf
1409                   (if bound-fun
1410                       #!+stack-allocatable-closures
1411                       (setf (leaf-dynamic-extent bound-fun) dx)
1412                       #!-stack-allocatable-closures
1413                       (compiler-notify
1414                        "Ignoring DYNAMIC-EXTENT declaration on function ~S ~
1415                         (not supported on this platform)." fname)
1416                       (compiler-notify
1417                        "Ignoring free DYNAMIC-EXTENT declaration: ~S" name)))
1418                  (cons
1419                   (compiler-error "DYNAMIC-EXTENT on macro: ~S" name))
1420                  (null
1421                   (compiler-style-warn
1422                    "Unbound function declared DYNAMIC-EXTENT: ~S" name)))))
1423             (t
1424              (compiler-error "DYNAMIC-EXTENT on a weird thing: ~S" name))))
1425         (when (policy *lexenv* (= speed 3))
1426           (compiler-notify "Ignoring DYNAMIC-EXTENT declarations: ~S" names)))))
1427
1428 ;;; FIXME: This is non-ANSI, so the default should be T, or it should
1429 ;;; go away, I think.
1430 (defvar *suppress-values-declaration* nil
1431   #!+sb-doc
1432   "If true, processing of the VALUES declaration is inhibited.")
1433
1434 ;;; Process a single declaration spec, augmenting the specified LEXENV
1435 ;;; RES. Return RES and result type. VARS and FVARS are as described
1436 ;;; PROCESS-DECLS.
1437 (defun process-1-decl (raw-spec res vars fvars binding-form-p context)
1438   (declare (type list raw-spec vars fvars))
1439   (declare (type lexenv res))
1440   (let ((spec (canonized-decl-spec raw-spec))
1441         (result-type *wild-type*))
1442     (values
1443      (case (first spec)
1444        (special (process-special-decl spec res vars binding-form-p context))
1445        (ftype
1446         (unless (cdr spec)
1447           (compiler-error "no type specified in FTYPE declaration: ~S" spec))
1448         (process-ftype-decl (second spec) res (cddr spec) fvars context))
1449        ((inline notinline maybe-inline)
1450         (process-inline-decl spec res fvars))
1451        ((ignore ignorable)
1452         (process-ignore-decl spec vars fvars)
1453         res)
1454        (optimize
1455         (make-lexenv
1456          :default res
1457          :policy (process-optimize-decl spec (lexenv-policy res))))
1458        (muffle-conditions
1459         (make-lexenv
1460          :default res
1461          :handled-conditions (process-muffle-conditions-decl
1462                               spec (lexenv-handled-conditions res))))
1463        (unmuffle-conditions
1464         (make-lexenv
1465          :default res
1466          :handled-conditions (process-unmuffle-conditions-decl
1467                               spec (lexenv-handled-conditions res))))
1468        (type
1469         (process-type-decl (cdr spec) res vars context))
1470        (values
1471         (unless *suppress-values-declaration*
1472           (let ((types (cdr spec)))
1473             (setq result-type
1474                   (compiler-values-specifier-type
1475                    (if (singleton-p types)
1476                        (car types)
1477                        `(values ,@types)))))
1478           res))
1479        ((dynamic-extent truly-dynamic-extent)
1480         (process-dx-decl (cdr spec) vars fvars (first spec))
1481         res)
1482        ((disable-package-locks enable-package-locks)
1483         (make-lexenv
1484          :default res
1485          :disabled-package-locks (process-package-lock-decl
1486                                   spec (lexenv-disabled-package-locks res))))
1487        (t
1488         (unless (info :declaration :recognized (first spec))
1489           (compiler-warn "unrecognized declaration ~S" raw-spec))
1490         (let ((fn (info :declaration :handler (first spec))))
1491           (if fn
1492               (funcall fn res spec vars fvars)
1493               res))))
1494      result-type)))
1495
1496 ;;; Use a list of DECLARE forms to annotate the lists of LAMBDA-VAR
1497 ;;; and FUNCTIONAL structures which are being bound. In addition to
1498 ;;; filling in slots in the leaf structures, we return a new LEXENV,
1499 ;;; which reflects pervasive special and function type declarations,
1500 ;;; (NOT)INLINE declarations and OPTIMIZE declarations, and type of
1501 ;;; VALUES declarations. If BINDING-FORM-P is true, the third return
1502 ;;; value is a list of VARs that should not apply to the lexenv of the
1503 ;;; initialization forms for the bindings, but should apply to the body.
1504 ;;;
1505 ;;; This is also called in main.lisp when PROCESS-FORM handles a use
1506 ;;; of LOCALLY.
1507 (defun process-decls (decls vars fvars &key
1508                       (lexenv *lexenv*) (binding-form-p nil) (context :compile))
1509   (declare (list decls vars fvars))
1510   (let ((result-type *wild-type*)
1511         (*post-binding-variable-lexenv* nil))
1512     (dolist (decl decls)
1513       (dolist (spec (rest decl))
1514         (progv
1515             ;; Kludge: EVAL calls this function to deal with LOCALLY.
1516             (when (eq context :compile) (list '*current-path*))
1517             (when (eq context :compile) (list (or (get-source-path spec)
1518                                                   (get-source-path decl)
1519                                                   *current-path*)))
1520           (unless (consp spec)
1521             (compiler-error "malformed declaration specifier ~S in ~S" spec decl))
1522           (multiple-value-bind (new-env new-result-type)
1523               (process-1-decl spec lexenv vars fvars binding-form-p context)
1524             (setq lexenv new-env)
1525             (unless (eq new-result-type *wild-type*)
1526               (setq result-type
1527                     (values-type-intersection result-type new-result-type)))))))
1528     (values lexenv result-type *post-binding-variable-lexenv*)))
1529
1530 (defun %processing-decls (decls vars fvars ctran lvar binding-form-p fun)
1531   (multiple-value-bind (*lexenv* result-type post-binding-lexenv)
1532       (process-decls decls vars fvars :binding-form-p binding-form-p)
1533     (cond ((eq result-type *wild-type*)
1534            (funcall fun ctran lvar post-binding-lexenv))
1535           (t
1536            (let ((value-ctran (make-ctran))
1537                  (value-lvar (make-lvar)))
1538              (multiple-value-prog1
1539                  (funcall fun value-ctran value-lvar post-binding-lexenv)
1540                (let ((cast (make-cast value-lvar result-type
1541                                       (lexenv-policy *lexenv*))))
1542                  (link-node-to-previous-ctran cast value-ctran)
1543                  (setf (lvar-dest value-lvar) cast)
1544                  (use-continuation cast ctran lvar))))))))
1545 (defmacro processing-decls ((decls vars fvars ctran lvar
1546                                    &optional post-binding-lexenv)
1547                             &body forms)
1548   (check-type ctran symbol)
1549   (check-type lvar symbol)
1550   (let ((post-binding-lexenv-p (not (null post-binding-lexenv)))
1551         (post-binding-lexenv (or post-binding-lexenv (sb!xc:gensym "LEXENV"))))
1552     `(%processing-decls ,decls ,vars ,fvars ,ctran ,lvar
1553                         ,post-binding-lexenv-p
1554                         (lambda (,ctran ,lvar ,post-binding-lexenv)
1555                           (declare (ignorable ,post-binding-lexenv))
1556                           ,@forms))))
1557
1558 ;;; Return the SPECVAR for NAME to use when we see a local SPECIAL
1559 ;;; declaration. If there is a global variable of that name, then
1560 ;;; check that it isn't a constant and return it. Otherwise, create an
1561 ;;; anonymous GLOBAL-VAR.
1562 (defun specvar-for-binding (name)
1563   (cond ((not (eq (info :variable :where-from name) :assumed))
1564          (let ((found (find-free-var name)))
1565            (when (heap-alien-info-p found)
1566              (compiler-error
1567               "~S is an alien variable and so can't be declared special."
1568               name))
1569            (unless (global-var-p found)
1570              (compiler-error
1571               "~S is a constant and so can't be declared special."
1572               name))
1573            found))
1574         (t
1575          (make-global-var :kind :special
1576                           :%source-name name
1577                           :where-from :declared))))