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