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