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