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