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