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