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