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