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