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