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