Fix make-array transforms.
[sbcl.git] / src / compiler / node.lisp
1 ;;;; structures for the first intermediate representation in the
2 ;;;; compiler, 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 ;;; The front-end data structure (IR1) is composed of nodes,
16 ;;; representing actual evaluations. Linear sequences of nodes in
17 ;;; control-flow order are combined into blocks (but see
18 ;;; JOIN-SUCCESSOR-IF-POSSIBLE for precise conditions); control
19 ;;; transfers inside a block are represented with CTRANs and between
20 ;;; blocks -- with BLOCK-SUCC/BLOCK-PRED lists; data transfers are
21 ;;; represented with LVARs.
22
23 ;;; "Lead-in" Control TRANsfer [to some node]
24 (def!struct (ctran
25              (:make-load-form-fun ignore-it)
26              (:constructor make-ctran))
27   ;; an indication of the way that this continuation is currently used
28   ;;
29   ;; :UNUSED
30   ;;    A continuation for which all control-related slots have the
31   ;;    default values. A continuation is unused during IR1 conversion
32   ;;    until it is assigned a block, and may be also be temporarily
33   ;;    unused during later manipulations of IR1. In a consistent
34   ;;    state there should never be any mention of :UNUSED
35   ;;    continuations. NEXT can have a non-null value if the next node
36   ;;    has already been determined.
37   ;;
38   ;; :BLOCK-START
39   ;;    The continuation that is the START of BLOCK.
40   ;;
41   ;; :INSIDE-BLOCK
42   ;;    A continuation that is the NEXT of some node in BLOCK.
43   (kind :unused :type (member :unused :inside-block :block-start))
44   ;; A NODE which is to be evaluated next. Null only temporary.
45   (next nil :type (or node null))
46   ;; the node where this CTRAN is used, if unique. This is always null
47   ;; in :UNUSED and :BLOCK-START CTRANs, and is never null in
48   ;; :INSIDE-BLOCK continuations.
49   (use nil :type (or node null))
50   ;; the basic block this continuation is in. This is null only in
51   ;; :UNUSED continuations.
52   (block nil :type (or cblock null)))
53
54 (def!method print-object ((x ctran) stream)
55   (print-unreadable-object (x stream :type t :identity t)
56     (format stream "~D" (cont-num x))))
57
58 ;;; Linear VARiable. Multiple-value (possibly of unknown number)
59 ;;; temporal storage.
60 (def!struct (lvar
61              (:make-load-form-fun ignore-it)
62              (:constructor make-lvar (&optional dest)))
63   ;; The node which receives this value. NIL only temporarily.
64   (dest nil :type (or node null))
65   ;; cached type of this lvar's value. If NIL, then this must be
66   ;; recomputed: see LVAR-DERIVED-TYPE.
67   (%derived-type nil :type (or ctype null))
68   ;; the node (if unique) or a list of nodes where this lvar is used.
69   (uses nil :type (or node list))
70   ;; set to true when something about this lvar's value has
71   ;; changed. See REOPTIMIZE-LVAR. This provides a way for IR1
72   ;; optimize to determine which operands to a node have changed. If
73   ;; the optimizer for this node type doesn't care, it can elect not
74   ;; to clear this flag.
75   (reoptimize t :type boolean)
76   ;; Cached type which is checked by DEST. If NIL, then this must be
77   ;; recomputed: see LVAR-EXTERNALLY-CHECKABLE-TYPE.
78   (%externally-checkable-type nil :type (or null ctype))
79   ;; if the LVAR value is DYNAMIC-EXTENT, CLEANUP protecting it.
80   (dynamic-extent nil :type (or null cleanup))
81   ;; something or other that the back end annotates this lvar with
82   (info nil))
83
84 (def!method print-object ((x lvar) stream)
85   (print-unreadable-object (x stream :type t :identity t)
86     (format stream "~D" (cont-num x))))
87
88 (def!struct (node (:constructor nil)
89                   (:include sset-element (number (incf *compiler-sset-counter*)))
90                   (:copier nil))
91   ;; unique ID for debugging
92   #!+sb-show (id (new-object-id) :read-only t)
93   ;; True if this node needs to be optimized. This is set to true
94   ;; whenever something changes about the value of an lvar whose DEST
95   ;; is this node.
96   (reoptimize t :type boolean)
97   ;; the ctran indicating what we do controlwise after evaluating this
98   ;; node. This is null if the node is the last in its block.
99   (next nil :type (or ctran null))
100   ;; the ctran that this node is the NEXT of. This is null during IR1
101   ;; conversion when we haven't linked the node in yet or in nodes
102   ;; that have been deleted from the IR1 by UNLINK-NODE.
103   (prev nil :type (or ctran null))
104   ;; the lexical environment this node was converted in
105   (lexenv *lexenv* :type lexenv)
106   ;; a representation of the source code responsible for generating
107   ;; this node
108   ;;
109   ;; For a form introduced by compilation (does not appear in the
110   ;; original source), the path begins with a list of all the
111   ;; enclosing introduced forms. This list is from the inside out,
112   ;; with the form immediately responsible for this node at the head
113   ;; of the list.
114   ;;
115   ;; Following the introduced forms is a representation of the
116   ;; location of the enclosing original source form. This transition
117   ;; is indicated by the magic ORIGINAL-SOURCE-START marker. The first
118   ;; element of the original source is the "form number", which is the
119   ;; ordinal number of this form in a depth-first, left-to-right walk
120   ;; of the truly-top-level form in which this appears.
121   ;;
122   ;; Following is a list of integers describing the path taken through
123   ;; the source to get to this point:
124   ;;     (K L M ...) => (NTH K (NTH L (NTH M ...)))
125   ;;
126   ;; The last element in the list is the top level form number, which
127   ;; is the ordinal number (in this call to the compiler) of the truly
128   ;; top level form containing the original source.
129   (source-path *current-path* :type list)
130   ;; If this node is in a tail-recursive position, then this is set to
131   ;; T. At the end of IR1 (in physical environment analysis) this is
132   ;; computed for all nodes (after cleanup code has been emitted).
133   ;; Before then, a non-null value indicates that IR1 optimization has
134   ;; converted a tail local call to a direct transfer.
135   ;;
136   ;; If the back-end breaks tail-recursion for some reason, then it
137   ;; can null out this slot.
138   (tail-p nil :type boolean))
139
140 (def!struct (valued-node (:conc-name node-)
141                          (:include node)
142                          (:constructor nil)
143                          (:copier nil))
144   ;; the bottom-up derived type for this node.
145   (derived-type *wild-type* :type ctype)
146   ;; Lvar, receiving the values, produced by this node. May be NIL if
147   ;; the value is unused.
148   (lvar nil :type (or lvar null)))
149
150 ;;; Flags that are used to indicate various things about a block, such
151 ;;; as what optimizations need to be done on it:
152 ;;; -- REOPTIMIZE is set when something interesting happens the uses of a
153 ;;;    lvar whose DEST is in this block. This indicates that the
154 ;;;    value-driven (forward) IR1 optimizations should be done on this block.
155 ;;; -- FLUSH-P is set when code in this block becomes potentially flushable,
156 ;;;    usually due to an lvar's DEST becoming null.
157 ;;; -- TYPE-CHECK is true when the type check phase should be run on this
158 ;;;    block. IR1 optimize can introduce new blocks after type check has
159 ;;;    already run. We need to check these blocks, but there is no point in
160 ;;;    checking blocks we have already checked.
161 ;;; -- DELETE-P is true when this block is used to indicate that this block
162 ;;;    has been determined to be unreachable and should be deleted. IR1
163 ;;;    phases should not attempt to examine or modify blocks with DELETE-P
164 ;;;    set, since they may:
165 ;;;     - be in the process of being deleted, or
166 ;;;     - have no successors.
167 ;;; -- TYPE-ASSERTED, TEST-MODIFIED
168 ;;;    These flags are used to indicate that something in this block
169 ;;;    might be of interest to constraint propagation. TYPE-ASSERTED
170 ;;;    is set when an lvar type assertion is strengthened.
171 ;;;    TEST-MODIFIED is set whenever the test for the ending IF has
172 ;;;    changed (may be true when there is no IF.)
173 (!def-boolean-attribute block
174   reoptimize flush-p type-check delete-p type-asserted test-modified)
175
176 (macrolet ((defattr (block-slot)
177              `(defmacro ,block-slot (block)
178                 `(block-attributep
179                   (block-flags ,block)
180                   ,(symbolicate (subseq (string ',block-slot) 6))))))
181   (defattr block-reoptimize)
182   (defattr block-flush-p)
183   (defattr block-type-check)
184   (defattr block-delete-p)
185   (defattr block-type-asserted)
186   (defattr block-test-modified))
187
188 ;;; The CBLOCK structure represents a basic block. We include
189 ;;; SSET-ELEMENT so that we can have sets of blocks. Initially the
190 ;;; SSET-ELEMENT-NUMBER is null, DFO analysis numbers in reverse DFO.
191 ;;; During IR2 conversion, IR1 blocks are re-numbered in forward emit
192 ;;; order. This latter numbering also forms the basis of the block
193 ;;; numbering in the debug-info (though that is relative to the start
194 ;;; of the function.)
195 (def!struct (cblock (:include sset-element)
196                     (:constructor make-block (start))
197                     (:constructor make-block-key)
198                     (:conc-name block-)
199                     (:predicate block-p))
200   ;; a list of all the blocks that are predecessors/successors of this
201   ;; block. In well-formed IR1, most blocks will have one successor.
202   ;; The only exceptions are:
203   ;;  1. component head blocks (any number)
204   ;;  2. blocks ending in an IF (1 or 2)
205   ;;  3. blocks with DELETE-P set (zero)
206   (pred nil :type list)
207   (succ nil :type list)
208   ;; the ctran which heads this block (a :BLOCK-START), or NIL when we
209   ;; haven't made the start ctran yet (and in the dummy component head
210   ;; and tail blocks)
211   (start nil :type (or ctran null))
212   ;; the last node in this block. This is NIL when we are in the
213   ;; process of building a block (and in the dummy component head and
214   ;; tail blocks.)
215   (last nil :type (or node null))
216   ;; the forward and backward links in the depth-first ordering of the
217   ;; blocks. These slots are NIL at beginning/end.
218   (next nil :type (or null cblock))
219   (prev nil :type (or null cblock))
220   ;; This block's attributes: see above.
221   (flags (block-attributes reoptimize flush-p type-check type-asserted
222                            test-modified)
223          :type attributes)
224   ;; in constraint propagation: list of LAMBDA-VARs killed in this block
225   ;; in copy propagation: list of killed TNs
226   (kill nil)
227   ;; other sets used in constraint propagation and/or copy propagation
228   (gen nil)
229   (in nil)
230   (out nil)
231   ;; Set of all blocks that dominate this block. NIL is interpreted
232   ;; as "all blocks in component".
233   (dominators nil :type (or null sset))
234   ;; the LOOP that this block belongs to
235   (loop nil :type (or null cloop))
236   ;; next block in the loop.
237   (loop-next nil :type (or null cblock))
238   ;; the component this block is in, or NIL temporarily during IR1
239   ;; conversion and in deleted blocks
240   (component (progn
241                (aver-live-component *current-component*)
242                *current-component*)
243              :type (or component null))
244   ;; a flag used by various graph-walking code to determine whether
245   ;; this block has been processed already or what. We make this
246   ;; initially NIL so that FIND-INITIAL-DFO doesn't have to scan the
247   ;; entire initial component just to clear the flags.
248   (flag nil)
249   ;; some kind of info used by the back end
250   (info nil)
251   ;; what macroexpansions and source transforms happened "in" this block, used
252   ;; for xref
253   (xrefs nil :type list)
254   ;; Cache the physenv of a block during lifetime analysis. :NONE if
255   ;; no cached value has been stored yet.
256   (physenv-cache :none :type (or null physenv (member :none))))
257 (def!method print-object ((cblock cblock) stream)
258   (print-unreadable-object (cblock stream :type t :identity t)
259     (format stream "~W :START c~W"
260             (block-number cblock)
261             (cont-num (block-start cblock)))))
262
263 ;;; The BLOCK-ANNOTATION class is inherited (via :INCLUDE) by
264 ;;; different BLOCK-INFO annotation structures so that code
265 ;;; (specifically control analysis) can be shared.
266 (def!struct (block-annotation (:constructor nil)
267                               (:copier nil))
268   ;; The IR1 block that this block is in the INFO for.
269   (block (missing-arg) :type cblock)
270   ;; the next and previous block in emission order (not DFO). This
271   ;; determines which block we drop though to, and is also used to
272   ;; chain together overflow blocks that result from splitting of IR2
273   ;; blocks in lifetime analysis.
274   (next nil :type (or block-annotation null))
275   (prev nil :type (or block-annotation null)))
276
277 ;;; A COMPONENT structure provides a handle on a connected piece of
278 ;;; the flow graph. Most of the passes in the compiler operate on
279 ;;; COMPONENTs rather than on the entire flow graph.
280 ;;;
281 ;;; According to the CMU CL internals/front.tex, the reason for
282 ;;; separating compilation into COMPONENTs is
283 ;;;   to increase the efficiency of large block compilations. In
284 ;;;   addition to improving locality of reference and reducing the
285 ;;;   size of flow analysis problems, this allows back-end data
286 ;;;   structures to be reclaimed after the compilation of each
287 ;;;   component.
288 (def!struct (component (:copier nil)
289                        (:constructor
290                         make-component
291                         (head
292                          tail &aux
293                          (last-block tail)
294                          (outer-loop (make-loop :kind :outer :head head)))))
295   ;; unique ID for debugging
296   #!+sb-show (id (new-object-id) :read-only t)
297   ;; the kind of component
298   ;;
299   ;; (The terminology here is left over from before
300   ;; sbcl-0.pre7.34.flaky5.2, when there was no such thing as
301   ;; FUNCTIONAL-HAS-EXTERNAL-REFERENCES-P, so that Python was
302   ;; incapable of building standalone :EXTERNAL functions, but instead
303   ;; had to implement things like #'CL:COMPILE as FUNCALL of a little
304   ;; toplevel stub whose sole purpose was to return an :EXTERNAL
305   ;; function.)
306   ;;
307   ;; The possibilities are:
308   ;;   NIL
309   ;;     an ordinary component, containing non-top-level code
310   ;;   :TOPLEVEL
311   ;;     a component containing only load-time code
312   ;;   :COMPLEX-TOPLEVEL
313   ;;     In the old system, before FUNCTIONAL-HAS-EXTERNAL-REFERENCES-P
314   ;;     was defined, this was necessarily a component containing both
315   ;;     top level and run-time code. Now this state is also used for
316   ;;     a component with HAS-EXTERNAL-REFERENCES-P functionals in it.
317   ;;   :INITIAL
318   ;;     the result of initial IR1 conversion, on which component
319   ;;     analysis has not been done
320   ;;   :DELETED
321   ;;     debris left over from component analysis
322   ;;
323   ;; See also COMPONENT-TOPLEVELISH-P.
324   (kind nil :type (member nil :toplevel :complex-toplevel :initial :deleted))
325   ;; the blocks that are the dummy head and tail of the DFO
326   ;;
327   ;; Entry/exit points have these blocks as their
328   ;; predecessors/successors. The start and return from each
329   ;; non-deleted function is linked to the component head and
330   ;; tail. Until physical environment analysis links NLX entry stubs
331   ;; to the component head, every successor of the head is a function
332   ;; start (i.e. begins with a BIND node.)
333   (head (missing-arg) :type cblock)
334   (tail (missing-arg) :type cblock)
335   ;; New blocks are inserted before this.
336   (last-block (missing-arg) :type cblock)
337   ;; This becomes a list of the CLAMBDA structures for all functions
338   ;; in this component. OPTIONAL-DISPATCHes are represented only by
339   ;; their XEP and other associated lambdas. This doesn't contain any
340   ;; deleted or LET lambdas.
341   ;;
342   ;; Note that logical associations between CLAMBDAs and COMPONENTs
343   ;; seem to exist for a while before this is initialized. See e.g.
344   ;; the NEW-FUNCTIONALS slot. In particular, I got burned by writing
345   ;; some code to use this value to decide which components need
346   ;; LOCALL-ANALYZE-COMPONENT, when it turns out that
347   ;; LOCALL-ANALYZE-COMPONENT had a role in initializing this value
348   ;; (and DFO stuff does too, maybe). Also, even after it's
349   ;; initialized, it might change as CLAMBDAs are deleted or merged.
350   ;; -- WHN 2001-09-30
351   (lambdas () :type list)
352   ;; a list of FUNCTIONALs for functions that are newly converted, and
353   ;; haven't been local-call analyzed yet. Initially functions are not
354   ;; in the LAMBDAS list. Local call analysis moves them there
355   ;; (possibly as LETs, or implicitly as XEPs if an OPTIONAL-DISPATCH.)
356   ;; Between runs of local call analysis there may be some debris of
357   ;; converted or even deleted functions in this list.
358   (new-functionals () :type list)
359   ;; If this is :MAYBE, then there is stuff in this component that
360   ;; could benefit from further IR1 optimization. T means that
361   ;; reoptimization is necessary.
362   (reoptimize t :type (member nil :maybe t))
363   ;; If this is true, then the control flow in this component was
364   ;; messed up by IR1 optimizations, so the DFO should be recomputed.
365   (reanalyze nil :type boolean)
366   ;; some sort of name for the code in this component
367   (name "<unknown>" :type t)
368   ;; When I am a child, this is :NO-IR2-YET.
369   ;; In my adulthood, IR2 stores notes to itself here.
370   ;; After I have left the great wheel and am staring into the GC, this
371   ;;   is set to :DEAD to indicate that it's a gruesome error to operate
372   ;;   on me (e.g. by using me as *CURRENT-COMPONENT*, or by pushing
373   ;;   LAMBDAs onto my NEW-FUNCTIONALS, as in sbcl-0.pre7.115).
374   (info :no-ir2-yet :type (or ir2-component (member :no-ir2-yet :dead)))
375   ;; count of the number of inline expansions we have done while
376   ;; compiling this component, to detect infinite or exponential
377   ;; blowups
378   (inline-expansions 0 :type index)
379   ;; a map from combination nodes to things describing how an
380   ;; optimization of the node failed. The description is an alist
381   ;; (TRANSFORM . ARGS), where TRANSFORM is the structure describing
382   ;; the transform that failed, and ARGS is either a list of format
383   ;; arguments for the note, or the FUN-TYPE that would have
384   ;; enabled the transformation but failed to match.
385   (failed-optimizations (make-hash-table :test 'eq) :type hash-table)
386   ;; This is similar to NEW-FUNCTIONALS, but is used when a function
387   ;; has already been analyzed, but new references have been added by
388   ;; inline expansion. Unlike NEW-FUNCTIONALS, this is not disjoint
389   ;; from COMPONENT-LAMBDAS.
390   (reanalyze-functionals nil :type list)
391   (delete-blocks nil :type list)
392   (nlx-info-generated-p nil :type boolean)
393   ;; this is filled by physical environment analysis
394   (dx-lvars nil :type list)
395   ;; The default LOOP in the component.
396   (outer-loop (missing-arg) :type cloop)
397   ;; The current sset index
398   (sset-number 0 :type fixnum))
399 (defprinter (component :identity t)
400   name
401   #!+sb-show id
402   (reanalyze :test reanalyze))
403
404 ;;; Check that COMPONENT is suitable for roles which involve adding
405 ;;; new code. (gotta love imperative programming with lotso in-place
406 ;;; side effects...)
407 (defun aver-live-component (component)
408   ;; FIXME: As of sbcl-0.pre7.115, we're asserting that
409   ;; COMPILE-COMPONENT hasn't happened yet. Might it be even better
410   ;; (certainly stricter, possibly also correct...) to assert that
411   ;; IR1-FINALIZE hasn't happened yet?
412   (aver (not (eql (component-info component) :dead))))
413
414 ;;; Before sbcl-0.7.0, there were :TOPLEVEL things which were magical
415 ;;; in multiple ways. That's since been refactored into the orthogonal
416 ;;; properties "optimized for locall with no arguments" and "externally
417 ;;; visible/referenced (so don't delete it)". The code <0.7.0 did a lot
418 ;;; of tests a la (EQ KIND :TOP_LEVEL) in the "don't delete it?" sense;
419 ;;; this function is a sort of literal translation of those tests into
420 ;;; the new world.
421 ;;;
422 ;;; FIXME: After things settle down, bare :TOPLEVEL might go away, at
423 ;;; which time it might be possible to replace the COMPONENT-KIND
424 ;;; :TOPLEVEL mess with a flag COMPONENT-HAS-EXTERNAL-REFERENCES-P
425 ;;; along the lines of FUNCTIONAL-HAS-EXTERNAL-REFERENCES-P.
426 (defun lambda-toplevelish-p (clambda)
427   (or (eql (lambda-kind clambda) :toplevel)
428       (lambda-has-external-references-p clambda)))
429 (defun component-toplevelish-p (component)
430   (member (component-kind component)
431           '(:toplevel :complex-toplevel)))
432
433 ;;; A CLEANUP structure represents some dynamic binding action. Blocks
434 ;;; are annotated with the current CLEANUP so that dynamic bindings
435 ;;; can be removed when control is transferred out of the binding
436 ;;; environment. We arrange for changes in dynamic bindings to happen
437 ;;; at block boundaries, so that cleanup code may easily be inserted.
438 ;;; The "mess-up" action is explicitly represented by a funny function
439 ;;; call or ENTRY node.
440 ;;;
441 ;;; We guarantee that CLEANUPs only need to be done at block
442 ;;; boundaries by requiring that the exit ctrans initially head their
443 ;;; blocks, and then by not merging blocks when there is a cleanup
444 ;;; change.
445 (def!struct (cleanup (:copier nil))
446   ;; the kind of thing that has to be cleaned up
447   (kind (missing-arg)
448         :type (member :special-bind :catch :unwind-protect
449                       :block :tagbody :dynamic-extent))
450   ;; the node that messes things up. This is the last node in the
451   ;; non-messed-up environment. Null only temporarily. This could be
452   ;; deleted due to unreachability.
453   (mess-up nil :type (or node null))
454   ;; For all kinds, except :DYNAMIC-EXTENT: a list of all the NLX-INFO
455   ;; structures whose NLX-INFO-CLEANUP is this cleanup. This is filled
456   ;; in by physical environment analysis.
457   ;;
458   ;; For :DYNAMIC-EXTENT: a list of all DX LVARs, preserved by this
459   ;; cleanup. This is filled when the cleanup is created (now by
460   ;; locall call analysis) and is rechecked by physical environment
461   ;; analysis. (For closures this is a list of the allocating node -
462   ;; during IR1, and a list of the argument LVAR of the allocator -
463   ;; after physical environment analysis.)
464   (info nil :type list))
465 (defprinter (cleanup :identity t)
466   kind
467   mess-up
468   (info :test info))
469
470 ;;; A PHYSENV represents the result of physical environment analysis.
471 ;;;
472 ;;; As far as I can tell from reverse engineering, this IR1 structure
473 ;;; represents the physical environment (which is probably not the
474 ;;; standard Lispy term for this concept, but I dunno what is the
475 ;;; standard term): those things in the lexical environment which a
476 ;;; LAMBDA actually interacts with. Thus in
477 ;;;   (DEFUN FROB-THINGS (THINGS)
478 ;;;     (DOLIST (THING THINGS)
479 ;;;       (BLOCK FROBBING-ONE-THING
480 ;;;         (MAPCAR (LAMBDA (PATTERN)
481 ;;;                   (WHEN (FITS-P THING PATTERN)
482 ;;;                     (RETURN-FROM FROB-THINGS (LIST :FIT THING PATTERN))))
483 ;;;                 *PATTERNS*))))
484 ;;; the variables THINGS, THING, and PATTERN and the block names
485 ;;; FROB-THINGS and FROBBING-ONE-THING are all in the inner LAMBDA's
486 ;;; lexical environment, but of those only THING, PATTERN, and
487 ;;; FROB-THINGS are in its physical environment. In IR1, we largely
488 ;;; just collect the names of these things; in IR2 an IR2-PHYSENV
489 ;;; structure is attached to INFO and used to keep track of
490 ;;; associations between these names and less-abstract things (like
491 ;;; TNs, or eventually stack slots and registers). -- WHN 2001-09-29
492 (def!struct (physenv (:copier nil))
493   ;; the function that allocates this physical environment
494   (lambda (missing-arg) :type clambda :read-only t)
495   ;; This ultimately converges to a list of all the LAMBDA-VARs and
496   ;; NLX-INFOs needed from enclosing environments by code in this
497   ;; physical environment. In the meantime, it may be
498   ;;   * NIL at object creation time
499   ;;   * a superset of the correct result, generated somewhat later
500   ;;   * smaller and smaller sets converging to the correct result as
501   ;;     we notice and delete unused elements in the superset
502   (closure nil :type list)
503   ;; a list of NLX-INFO structures describing all the non-local exits
504   ;; into this physical environment
505   (nlx-info nil :type list)
506   ;; some kind of info used by the back end
507   (info nil))
508 (defprinter (physenv :identity t)
509   lambda
510   (closure :test closure)
511   (nlx-info :test nlx-info))
512
513 ;;; An TAIL-SET structure is used to accumulate information about
514 ;;; tail-recursive local calls. The "tail set" is effectively the
515 ;;; transitive closure of the "is called tail-recursively by"
516 ;;; relation.
517 ;;;
518 ;;; All functions in the same tail set share the same TAIL-SET
519 ;;; structure. Initially each function has its own TAIL-SET, but when
520 ;;; IR1-OPTIMIZE-RETURN notices a tail local call, it joins the tail
521 ;;; sets of the called function and the calling function.
522 ;;;
523 ;;; The tail set is somewhat approximate, because it is too early to
524 ;;; be sure which calls will be tail-recursive. Any call that *might*
525 ;;; end up tail-recursive causes TAIL-SET merging.
526 (def!struct (tail-set)
527   ;; a list of all the LAMBDAs in this tail set
528   (funs nil :type list)
529   ;; our current best guess of the type returned by these functions.
530   ;; This is the union across all the functions of the return node's
531   ;; RESULT-TYPE, excluding local calls.
532   (type *wild-type* :type ctype)
533   ;; some info used by the back end
534   (info nil))
535 (defprinter (tail-set :identity t)
536   funs
537   type
538   (info :test info))
539
540 ;;; An NLX-INFO structure is used to collect various information about
541 ;;; non-local exits. This is effectively an annotation on the
542 ;;; continuation, although it is accessed by searching in the
543 ;;; PHYSENV-NLX-INFO.
544 (def!struct (nlx-info
545              (:constructor make-nlx-info (cleanup
546                                           exit
547                                           &aux
548                                           (block (first (block-succ
549                                                          (node-block exit))))))
550              (:make-load-form-fun ignore-it))
551   ;; the cleanup associated with this exit. In a catch or
552   ;; unwind-protect, this is the :CATCH or :UNWIND-PROTECT cleanup,
553   ;; and not the cleanup for the escape block. The CLEANUP-KIND of
554   ;; this thus provides a good indication of what kind of exit is
555   ;; being done.
556   (cleanup (missing-arg) :type cleanup)
557   ;; the ``continuation'' exited to (the block, succeeding the EXIT
558   ;; nodes). If this exit is from an escape function (CATCH or
559   ;; UNWIND-PROTECT), then physical environment analysis deletes the
560   ;; escape function and instead has the %NLX-ENTRY use this
561   ;; continuation.
562   ;;
563   ;; This slot is used as a sort of name to allow us to find the
564   ;; NLX-INFO that corresponds to a given exit. For this purpose, the
565   ;; ENTRY must also be used to disambiguate, since exits to different
566   ;; places may deliver their result to the same continuation.
567   (block (missing-arg) :type cblock)
568   ;; the entry stub inserted by physical environment analysis. This is
569   ;; a block containing a call to the %NLX-ENTRY funny function that
570   ;; has the original exit destination as its successor. Null only
571   ;; temporarily.
572   (target nil :type (or cblock null))
573   ;; for a lexical exit it determines whether tag existence check is
574   ;; needed
575   (safe-p nil :type boolean)
576   ;; some kind of info used by the back end
577   info)
578 (defprinter (nlx-info :identity t)
579   block
580   target
581   info)
582 \f
583 ;;;; LEAF structures
584
585 ;;; Variables, constants and functions are all represented by LEAF
586 ;;; structures. A reference to a LEAF is indicated by a REF node. This
587 ;;; allows us to easily substitute one for the other without actually
588 ;;; hacking the flow graph.
589 (def!struct (leaf (:make-load-form-fun ignore-it)
590                   (:include sset-element (number (incf *compiler-sset-counter*)))
591                   (:constructor nil))
592   ;; unique ID for debugging
593   #!+sb-show (id (new-object-id) :read-only t)
594   ;; (For public access to this slot, use LEAF-SOURCE-NAME.)
595   ;;
596   ;; the name of LEAF as it appears in the source, e.g. 'FOO or '(SETF
597   ;; FOO) or 'N or '*Z*, or the special .ANONYMOUS. value if there's
598   ;; no name for this thing in the source (as can happen for
599   ;; FUNCTIONALs, e.g. for anonymous LAMBDAs or for functions for
600   ;; top-level forms; and can also happen for anonymous constants) or
601   ;; perhaps also if the match between the name and the thing is
602   ;; skewed enough (e.g. for macro functions or method functions) that
603   ;; we don't want to have that name affect compilation
604   ;;
605   ;; (We use .ANONYMOUS. here more or less the way we'd ordinarily use
606   ;; NIL, but we're afraid to use NIL because it's a symbol which could
607   ;; be the name of a leaf, if only the constant named NIL.)
608   ;;
609   ;; The value of this slot in can affect ordinary runtime behavior,
610   ;; e.g. of special variables and known functions, not just debugging.
611   ;;
612   ;; See also the LEAF-DEBUG-NAME function and the
613   ;; FUNCTIONAL-%DEBUG-NAME slot.
614   (%source-name (missing-arg)
615                 :type (or symbol (and cons (satisfies legal-fun-name-p)))
616                 :read-only t)
617   ;; the type which values of this leaf must have
618   (type *universal-type* :type ctype)
619   ;; the type which values of this leaf have last been defined to have
620   ;; (but maybe won't have in future, in case of redefinition)
621   (defined-type *universal-type* :type ctype)
622   ;; where the TYPE information came from (in order, from strongest to weakest):
623   ;;  :DECLARED, from a declaration.
624   ;;  :DEFINED-HERE, from examination of the definition in the same file.
625   ;;  :DEFINED, from examination of the definition elsewhere.
626   ;;  :DEFINED-METHOD, implicit, piecemeal declarations from CLOS.
627   ;;  :ASSUMED, from uses of the object.
628   (where-from :assumed :type (member :declared :assumed :defined-here :defined :defined-method))
629   ;; list of the REF nodes for this leaf
630   (refs () :type list)
631   ;; true if there was ever a REF or SET node for this leaf. This may
632   ;; be true when REFS and SETS are null, since code can be deleted.
633   (ever-used nil :type boolean)
634   ;; is it declared dynamic-extent, or truly-dynamic-extent?
635   (extent nil :type (member nil :maybe-dynamic :always-dynamic :indefinite))
636   ;; some kind of info used by the back end
637   (info nil))
638
639 (defun leaf-dynamic-extent (leaf)
640   (let ((extent (leaf-extent leaf)))
641     (unless (member extent '(nil :indefinite))
642       extent)))
643
644 ;;; LEAF name operations
645 ;;;
646 ;;; KLUDGE: wants CLOS..
647 (defun leaf-has-source-name-p (leaf)
648   (not (eq (leaf-%source-name leaf)
649            '.anonymous.)))
650 (defun leaf-source-name (leaf)
651   (aver (leaf-has-source-name-p leaf))
652   (leaf-%source-name leaf))
653 (defun leaf-debug-name (leaf)
654   (if (functional-p leaf)
655       ;; FUNCTIONALs have additional %DEBUG-NAME behavior.
656       (functional-debug-name leaf)
657       ;; Other objects just use their source name.
658       ;;
659       ;; (As of sbcl-0.pre7.85, there are a few non-FUNCTIONAL
660       ;; anonymous objects, (anonymous constants..) and those would
661       ;; fail here if we ever tried to get debug names from them, but
662       ;; it looks as though it's never interesting to get debug names
663       ;; from them, so it's moot. -- WHN)
664       (leaf-source-name leaf)))
665 (defun leaf-%debug-name (leaf)
666   (when (functional-p leaf)
667     (functional-%debug-name leaf)))
668
669 ;;; The CONSTANT structure is used to represent known constant values.
670 ;;; Since the same constant leaf may be shared between named and anonymous
671 ;;; constants, %SOURCE-NAME is never used.
672 (def!struct (constant (:constructor make-constant (value
673                                                    &aux
674                                                    (type (ctype-of value))
675                                                    (%source-name '.anonymous.)
676                                                    (where-from :defined)))
677                       (:include leaf))
678   ;; the value of the constant
679   (value (missing-arg) :type t)
680   ;; Boxed TN for this constant, if any.
681   (boxed-tn nil :type (or null tn)))
682 (defprinter (constant :identity t)
683   value)
684
685 ;;; The BASIC-VAR structure represents information common to all
686 ;;; variables which don't correspond to known local functions.
687 (def!struct (basic-var (:include leaf)
688                        (:constructor nil))
689   ;; Lists of the set nodes for this variable.
690   (sets () :type list))
691
692 ;;; The GLOBAL-VAR structure represents a value hung off of the symbol
693 ;;; NAME.
694 (def!struct (global-var (:include basic-var))
695   ;; kind of variable described
696   (kind (missing-arg)
697         :type (member :special :global-function :global :unknown)))
698 (defprinter (global-var :identity t)
699   %source-name
700   #!+sb-show id
701   (type :test (not (eq type *universal-type*)))
702   (defined-type :test (not (eq defined-type *universal-type*)))
703   (where-from :test (not (eq where-from :assumed)))
704   kind)
705
706 ;;; A DEFINED-FUN represents a function that is defined in the same
707 ;;; compilation block, or that has an inline expansion, or that has a
708 ;;; non-NIL INLINEP value. Whenever we change the INLINEP state (i.e.
709 ;;; an inline proclamation) we copy the structure so that former
710 ;;; INLINEP values are preserved.
711 (def!struct (defined-fun (:include global-var
712                                    (where-from :defined)
713                                    (kind :global-function)))
714   ;; The values of INLINEP and INLINE-EXPANSION initialized from the
715   ;; global environment.
716   (inlinep nil :type inlinep)
717   (inline-expansion nil :type (or cons null))
718   ;; List of functionals corresponding to this DEFINED-FUN: either from the
719   ;; conversion of a NAMED-LAMBDA, or from inline-expansion (see
720   ;; RECOGNIZE-KNOWN-CALL) - we need separate functionals for each policy in
721   ;; which the function is used.
722   (functionals nil :type list))
723 (defprinter (defined-fun :identity t)
724   %source-name
725   #!+sb-show id
726   inlinep
727   (functionals :test functionals))
728 \f
729 ;;;; function stuff
730
731 ;;; We default the WHERE-FROM and TYPE slots to :DEFINED and FUNCTION.
732 ;;; We don't normally manipulate function types for defined functions,
733 ;;; but if someone wants to know, an approximation is there.
734 (def!struct (functional (:include leaf
735                                   (%source-name '.anonymous.)
736                                   (where-from :defined)
737                                   (type (specifier-type 'function))))
738   ;; (For public access to this slot, use LEAF-DEBUG-NAME.)
739   ;;
740   ;; the name of FUNCTIONAL for debugging purposes, or NIL if we
741   ;; should just let the SOURCE-NAME fall through
742   ;;
743   ;; Unlike the SOURCE-NAME slot, this slot's value should never
744   ;; affect ordinary code behavior, only debugging/diagnostic behavior.
745   ;;
746   ;; Ha.  Ah, the starry-eyed idealism of the writer of the above
747   ;; paragraph.  FUNCTION-LAMBDA-EXPRESSION's behaviour, as of
748   ;; sbcl-0.7.11.x, differs if the name of the a function is a string
749   ;; or not, as if it is a valid function name then it can look for an
750   ;; inline expansion.
751   ;;
752   ;; E.g. for the function which implements (DEFUN FOO ...), we could
753   ;; have
754   ;;   %SOURCE-NAME=FOO
755   ;;   %DEBUG-NAME=NIL
756   ;; for the function which implements the top level form
757   ;; (IN-PACKAGE :FOO) we could have
758   ;;   %SOURCE-NAME=NIL
759   ;;   %DEBUG-NAME=(TOP-LEVEL-FORM (IN-PACKAGE :FOO)
760   ;; for the function which implements FOO in
761   ;;   (DEFUN BAR (...) (FLET ((FOO (...) ...)) ...))
762   ;; we could have
763   ;;   %SOURCE-NAME=FOO
764   ;;   %DEBUG-NAME=(FLET FOO)
765   ;; and for the function which implements FOO in
766   ;;   (DEFMACRO FOO (...) ...)
767   ;; we could have
768   ;;   %SOURCE-NAME=FOO (or maybe .ANONYMOUS.?)
769   ;;   %DEBUG-NAME=(MACRO-FUNCTION FOO)
770   (%debug-name nil
771                :type (or null (not (satisfies legal-fun-name-p)))
772                :read-only t)
773   ;; some information about how this function is used. These values
774   ;; are meaningful:
775   ;;
776   ;;    NIL
777   ;;    an ordinary function, callable using local call
778   ;;
779   ;;    :LET
780   ;;    a lambda that is used in only one local call, and has in
781   ;;    effect been substituted directly inline. The return node is
782   ;;    deleted, and the result is computed with the actual result
783   ;;    lvar for the call.
784   ;;
785   ;;    :MV-LET
786   ;;    Similar to :LET (as per FUNCTIONAL-LETLIKE-P), but the call
787   ;;    is an MV-CALL.
788   ;;
789   ;;    :ASSIGNMENT
790   ;;    similar to a LET (as per FUNCTIONAL-SOMEWHAT-LETLIKE-P), but
791   ;;    can have other than one call as long as there is at most
792   ;;    one non-tail call.
793   ;;
794   ;;    :OPTIONAL
795   ;;    a lambda that is an entry point for an OPTIONAL-DISPATCH.
796   ;;    Similar to NIL, but requires greater caution, since local call
797   ;;    analysis may create new references to this function. Also, the
798   ;;    function cannot be deleted even if it has *no* references. The
799   ;;    OPTIONAL-DISPATCH is in the LAMDBA-OPTIONAL-DISPATCH.
800   ;;
801   ;;    :EXTERNAL
802   ;;    an external entry point lambda. The function it is an entry
803   ;;    for is in the ENTRY-FUN slot.
804   ;;
805   ;;    :TOPLEVEL
806   ;;    a top level lambda, holding a compiled top level form.
807   ;;    Compiled very much like NIL, but provides an indication of
808   ;;    top level context. A :TOPLEVEL lambda should have *no*
809   ;;    references. Its ENTRY-FUN is a self-pointer.
810   ;;
811   ;;    :TOPLEVEL-XEP
812   ;;    After a component is compiled, we clobber any top level code
813   ;;    references to its non-closure XEPs with dummy FUNCTIONAL
814   ;;    structures having this kind. This prevents the retained
815   ;;    top level code from holding onto the IR for the code it
816   ;;    references.
817   ;;
818   ;;    :ESCAPE
819   ;;    :CLEANUP
820   ;;    special functions used internally by CATCH and UNWIND-PROTECT.
821   ;;    These are pretty much like a normal function (NIL), but are
822   ;;    treated specially by local call analysis and stuff. Neither
823   ;;    kind should ever be given an XEP even though they appear as
824   ;;    args to funny functions. An :ESCAPE function is never actually
825   ;;    called, and thus doesn't need to have code generated for it.
826   ;;
827   ;;    :DELETED
828   ;;    This function has been found to be uncallable, and has been
829   ;;    marked for deletion.
830   ;;
831   ;;    :ZOMBIE
832   ;;    Effectless [MV-]LET; has no BIND node.
833   (kind nil :type (member nil :optional :deleted :external :toplevel
834                           :escape :cleanup :let :mv-let :assignment
835                           :zombie :toplevel-xep))
836   ;; Is this a function that some external entity (e.g. the fasl dumper)
837   ;; refers to, so that even when it appears to have no references, it
838   ;; shouldn't be deleted? In the old days (before
839   ;; sbcl-0.pre7.37.flaky5.2) this was sort of implicitly true when
840   ;; KIND was :TOPLEVEL. Now it must be set explicitly, both for
841   ;; :TOPLEVEL functions and for any other kind of functions that we
842   ;; want to dump or return from #'CL:COMPILE or whatever.
843   (has-external-references-p nil)
844   ;; In a normal function, this is the external entry point (XEP)
845   ;; lambda for this function, if any. Each function that is used
846   ;; other than in a local call has an XEP, and all of the
847   ;; non-local-call references are replaced with references to the
848   ;; XEP.
849   ;;
850   ;; In an XEP lambda (indicated by the :EXTERNAL kind), this is the
851   ;; function that the XEP is an entry-point for. The body contains
852   ;; local calls to all the actual entry points in the function. In a
853   ;; :TOPLEVEL lambda (which is its own XEP) this is a self-pointer.
854   ;;
855   ;; With all other kinds, this is null.
856   (entry-fun nil :type (or functional null))
857   ;; the value of any inline/notinline declaration for a local
858   ;; function (or NIL in any case if no inline expansion is available)
859   (inlinep nil :type inlinep)
860   ;; If we have a lambda that can be used as in inline expansion for
861   ;; this function, then this is it. If there is no source-level
862   ;; lambda corresponding to this function then this is null (but then
863   ;; INLINEP will always be NIL as well.)
864   (inline-expansion nil :type list)
865   ;; the lexical environment that the INLINE-EXPANSION should be converted in
866   (lexenv *lexenv* :type lexenv)
867   ;; the original function or macro lambda list, or :UNSPECIFIED if
868   ;; this is a compiler created function
869   (arg-documentation nil :type (or list (member :unspecified)))
870   ;; the documentation string for the lambda
871   (documentation nil :type (or null string))
872   ;; Node, allocating closure for this lambda. May be NIL when we are
873   ;; sure that no closure is needed.
874   (allocator nil :type (or null combination))
875   ;; various rare miscellaneous info that drives code generation & stuff
876   (plist () :type list)
877   ;; xref information for this functional (only used for functions with an
878   ;; XEP)
879   (xref () :type list)
880   ;; True if this functional was created from an inline expansion. This
881   ;; is either T, or the GLOBAL-VAR for which it is an expansion.
882   (inline-expanded nil))
883 (defprinter (functional :identity t)
884   %source-name
885   %debug-name
886   #!+sb-show id)
887
888 ;;; Is FUNCTIONAL LET-converted? (where we're indifferent to whether
889 ;;; it returns one value or multiple values)
890 (defun functional-letlike-p (functional)
891   (member (functional-kind functional)
892           '(:let :mv-let)))
893
894 ;;; Is FUNCTIONAL sorta LET-converted? (where even an :ASSIGNMENT counts)
895 ;;;
896 ;;; FIXME: I (WHN) don't understand this one well enough to give a good
897 ;;; definition or even a good function name, it's just a literal copy
898 ;;; of a CMU CL idiom. Does anyone have a better name or explanation?
899 (defun functional-somewhat-letlike-p (functional)
900   (or (functional-letlike-p functional)
901       (eql (functional-kind functional) :assignment)))
902
903 ;;; FUNCTIONAL name operations
904 (defun functional-debug-name (functional)
905   ;; FUNCTIONAL-%DEBUG-NAME takes precedence over FUNCTIONAL-SOURCE-NAME
906   ;; here because we want different debug names for the functions in
907   ;; DEFUN FOO and FLET FOO even though they have the same source name.
908   (or (functional-%debug-name functional)
909       ;; Note that this will cause an error if the function is
910       ;; anonymous. In SBCL (as opposed to CMU CL) we make all
911       ;; FUNCTIONALs have debug names. The CMU CL code didn't bother
912       ;; in many FUNCTIONALs, especially those which were likely to be
913       ;; optimized away before the user saw them. However, getting
914       ;; that right requires a global understanding of the code,
915       ;; which seems bad, so we just require names for everything.
916       (leaf-source-name functional)))
917
918 ;;; The CLAMBDA only deals with required lexical arguments. Special,
919 ;;; optional, keyword and rest arguments are handled by transforming
920 ;;; into simpler stuff.
921 (def!struct (clambda (:include functional)
922                      (:conc-name lambda-)
923                      (:predicate lambda-p)
924                      (:constructor make-lambda)
925                      (:copier copy-lambda))
926   ;; list of LAMBDA-VAR descriptors for arguments
927   (vars nil :type list :read-only t)
928   ;; If this function was ever a :OPTIONAL function (an entry-point
929   ;; for an OPTIONAL-DISPATCH), then this is that OPTIONAL-DISPATCH.
930   ;; The optional dispatch will be :DELETED if this function is no
931   ;; longer :OPTIONAL.
932   (optional-dispatch nil :type (or optional-dispatch null))
933   ;; the BIND node for this LAMBDA. This node marks the beginning of
934   ;; the lambda, and serves to explicitly represent the lambda binding
935   ;; semantics within the flow graph representation. This is null in
936   ;; deleted functions, and also in LETs where we deleted the call and
937   ;; bind (because there are no variables left), but have not yet
938   ;; actually deleted the LAMBDA yet.
939   (bind nil :type (or bind null))
940   ;; the RETURN node for this LAMBDA, or NIL if it has been
941   ;; deleted. This marks the end of the lambda, receiving the result
942   ;; of the body. In a LET, the return node is deleted, and the body
943   ;; delivers the value to the actual lvar. The return may also be
944   ;; deleted if it is unreachable.
945   (return nil :type (or creturn null))
946   ;; If this CLAMBDA is a LET, then this slot holds the LAMBDA whose
947   ;; LETS list we are in, otherwise it is a self-pointer.
948   (home nil :type (or clambda null))
949   ;; all the lambdas that have been LET-substituted in this lambda.
950   ;; This is only non-null in lambdas that aren't LETs.
951   (lets nil :type list)
952   ;; all the ENTRY nodes in this function and its LETs, or null in a LET
953   (entries nil :type list)
954   ;; CLAMBDAs which are locally called by this lambda, and other
955   ;; objects (closed-over LAMBDA-VARs and XEPs) which this lambda
956   ;; depends on in such a way that DFO shouldn't put them in separate
957   ;; components.
958   (calls-or-closes (make-sset) :type (or null sset))
959   ;; the TAIL-SET that this LAMBDA is in. This is null during creation.
960   ;;
961   ;; In CMU CL, and old SBCL, this was also NILed out when LET
962   ;; conversion happened. That caused some problems, so as of
963   ;; sbcl-0.pre7.37.flaky5.2 when I was trying to get the compiler to
964   ;; emit :EXTERNAL functions directly, and so now the value
965   ;; is no longer NILed out in LET conversion, but instead copied
966   ;; (so that any further optimizations on the rest of the tail
967   ;; set won't modify the value) if necessary.
968   (tail-set nil :type (or tail-set null))
969   ;; the structure which represents the phsical environment that this
970   ;; function's variables are allocated in. This is filled in by
971   ;; physical environment analysis. In a LET, this is EQ to our home's
972   ;; physical environment.
973   (physenv nil :type (or physenv null))
974   ;; In a LET, this is the NODE-LEXENV of the combination node. We
975   ;; retain it so that if the LET is deleted (due to a lack of vars),
976   ;; we will still have caller's lexenv to figure out which cleanup is
977   ;; in effect.
978   (call-lexenv nil :type (or lexenv null))
979   ;; list of embedded lambdas
980   (children nil :type list)
981   (parent nil :type (or clambda null))
982   (allow-instrumenting *allow-instrumenting* :type boolean)
983   ;; True if this is a system introduced lambda: it may contain user code, but
984   ;; the lambda itself is not, and the bindings introduced by it are considered
985   ;; transparent by the nested DX analysis.
986   (system-lambda-p nil :type boolean))
987 (defprinter (clambda :conc-name lambda- :identity t)
988   %source-name
989   %debug-name
990   #!+sb-show id
991   kind
992   (type :test (not (eq type *universal-type*)))
993   (where-from :test (not (eq where-from :assumed)))
994   (vars :prin1 (mapcar #'leaf-source-name vars)))
995
996 ;;; The OPTIONAL-DISPATCH leaf is used to represent hairy lambdas. It
997 ;;; is a FUNCTIONAL, like LAMBDA. Each legal number of arguments has a
998 ;;; function which is called when that number of arguments is passed.
999 ;;; The function is called with all the arguments actually passed. If
1000 ;;; additional arguments are legal, then the LEXPR style MORE-ENTRY
1001 ;;; handles them. The value returned by the function is the value
1002 ;;; which results from calling the OPTIONAL-DISPATCH.
1003 ;;;
1004 ;;; The theory is that each entry-point function calls the next entry
1005 ;;; point tail-recursively, passing all the arguments passed in and
1006 ;;; the default for the argument the entry point is for. The last
1007 ;;; entry point calls the real body of the function. In the presence
1008 ;;; of SUPPLIED-P args and other hair, things are more complicated. In
1009 ;;; general, there is a distinct internal function that takes the
1010 ;;; SUPPLIED-P args as parameters. The preceding entry point calls
1011 ;;; this function with NIL filled in for the SUPPLIED-P args, while
1012 ;;; the current entry point calls it with T in the SUPPLIED-P
1013 ;;; positions.
1014 ;;;
1015 ;;; Note that it is easy to turn a call with a known number of
1016 ;;; arguments into a direct call to the appropriate entry-point
1017 ;;; function, so functions that are compiled together can avoid doing
1018 ;;; the dispatch.
1019 (def!struct (optional-dispatch (:include functional))
1020   ;; the original parsed argument list, for anyone who cares
1021   (arglist nil :type list)
1022   ;; true if &ALLOW-OTHER-KEYS was supplied
1023   (allowp nil :type boolean)
1024   ;; true if &KEY was specified (which doesn't necessarily mean that
1025   ;; there are any &KEY arguments..)
1026   (keyp nil :type boolean)
1027   ;; the number of required arguments. This is the smallest legal
1028   ;; number of arguments.
1029   (min-args 0 :type unsigned-byte)
1030   ;; the total number of required and optional arguments. Args at
1031   ;; positions >= to this are &REST, &KEY or illegal args.
1032   (max-args 0 :type unsigned-byte)
1033   ;; list of the (maybe delayed) LAMBDAs which are the entry points
1034   ;; for non-rest, non-key calls. The entry for MIN-ARGS is first,
1035   ;; MIN-ARGS+1 second, ... MAX-ARGS last. The last entry-point always
1036   ;; calls the main entry; in simple cases it may be the main entry.
1037   (entry-points nil :type list)
1038   ;; an entry point which takes MAX-ARGS fixed arguments followed by
1039   ;; an argument context pointer and an argument count. This entry
1040   ;; point deals with listifying rest args and parsing keywords. This
1041   ;; is null when extra arguments aren't legal.
1042   (more-entry nil :type (or clambda null))
1043   ;; the main entry-point into the function, which takes all arguments
1044   ;; including keywords as fixed arguments. The format of the
1045   ;; arguments must be determined by examining the arglist. This may
1046   ;; be used by callers that supply at least MAX-ARGS arguments and
1047   ;; know what they are doing.
1048   (main-entry nil :type (or clambda null)))
1049 (defprinter (optional-dispatch :identity t)
1050   %source-name
1051   %debug-name
1052   #!+sb-show id
1053   (type :test (not (eq type *universal-type*)))
1054   (where-from :test (not (eq where-from :assumed)))
1055   arglist
1056   allowp
1057   keyp
1058   min-args
1059   max-args
1060   (entry-points :test entry-points)
1061   (more-entry :test more-entry)
1062   main-entry)
1063
1064 ;;; The ARG-INFO structure allows us to tack various information onto
1065 ;;; LAMBDA-VARs during IR1 conversion. If we use one of these things,
1066 ;;; then the var will have to be massaged a bit before it is simple
1067 ;;; and lexical.
1068 (def!struct arg-info
1069   ;; true if this arg is to be specially bound
1070   (specialp nil :type boolean)
1071   ;; the kind of argument being described. Required args only have arg
1072   ;; info structures if they are special.
1073   (kind (missing-arg)
1074         :type (member :required :optional :keyword :rest
1075                       :more-context :more-count))
1076   ;; If true, this is the VAR for SUPPLIED-P variable of a keyword or
1077   ;; optional arg. This is true for keywords with non-constant
1078   ;; defaults even when there is no user-specified supplied-p var.
1079   (supplied-p nil :type (or lambda-var null))
1080   ;; the default for a keyword or optional, represented as the
1081   ;; original Lisp code. This is set to NIL in &KEY arguments that are
1082   ;; defaulted using the SUPPLIED-P arg.
1083   ;;
1084   ;; For &REST arguments this may contain information about more context
1085   ;; the rest list comes from.
1086   (default nil :type t)
1087   ;; the actual key for a &KEY argument. Note that in ANSI CL this is
1088   ;; not necessarily a keyword: (DEFUN FOO (&KEY ((BAR BAR))) ...).
1089   (key nil :type symbol))
1090 (defprinter (arg-info :identity t)
1091   (specialp :test specialp)
1092   kind
1093   (supplied-p :test supplied-p)
1094   (default :test default)
1095   (key :test key))
1096
1097 ;;; The LAMBDA-VAR structure represents a lexical lambda variable.
1098 ;;; This structure is also used during IR1 conversion to describe
1099 ;;; lambda arguments which may ultimately turn out not to be simple
1100 ;;; and lexical.
1101 ;;;
1102 ;;; LAMBDA-VARs with no REFs are considered to be deleted; physical
1103 ;;; environment analysis isn't done on these variables, so the back
1104 ;;; end must check for and ignore unreferenced variables. Note that a
1105 ;;; deleted LAMBDA-VAR may have sets; in this case the back end is
1106 ;;; still responsible for propagating the SET-VALUE to the set's CONT.
1107 (!def-boolean-attribute lambda-var
1108   ;; true if this variable has been declared IGNORE
1109   ignore
1110   ;; This is set by physical environment analysis if it chooses an
1111   ;; indirect (value cell) representation for this variable because it
1112   ;; is both set and closed over.
1113   indirect
1114   ;; true if the last reference has been deleted (and new references
1115   ;; should not be made)
1116   deleted
1117   ;; This is set by physical environment analysis if, should it be an
1118   ;; indirect lambda-var, an actual value cell object must be
1119   ;; allocated for this variable because one or more of the closures
1120   ;; that refer to it are not dynamic-extent.  Note that both
1121   ;; attributes must be set for the value-cell object to be created.
1122   explicit-value-cell
1123   )
1124
1125 (def!struct (lambda-var (:include basic-var))
1126   (flags (lambda-var-attributes)
1127          :type attributes)
1128   ;; the CLAMBDA that this var belongs to. This may be null when we are
1129   ;; building a lambda during IR1 conversion.
1130   (home nil :type (or null clambda))
1131   ;; The following two slots are only meaningful during IR1 conversion
1132   ;; of hairy lambda vars:
1133   ;;
1134   ;; The ARG-INFO structure which holds information obtained from
1135   ;; &keyword parsing.
1136   (arg-info nil :type (or arg-info null))
1137   ;; if true, the GLOBAL-VAR structure for the special variable which
1138   ;; is to be bound to the value of this argument
1139   (specvar nil :type (or global-var null))
1140   ;; Set of the CONSTRAINTs on this variable. Used by constraint
1141   ;; propagation. This is left null by the lambda pre-pass if it
1142   ;; determine that this is a set closure variable, and is thus not a
1143   ;; good subject for flow analysis.
1144   (constraints nil :type (or null t #| FIXME: conset |#))
1145   ;; Content-addressed indices for the CONSTRAINTs on this variable.
1146   ;; These are solely used by FIND-CONSTRAINT
1147   (ctype-constraints nil :type (or null hash-table))
1148   (eq-constraints    nil :type (or null hash-table))
1149   ;; sorted sets of constraints we like to iterate over
1150   (eql-var-constraints     nil :type (or null (array t 1)))
1151   (inheritable-constraints nil :type (or null (array t 1)))
1152   (private-constraints     nil :type (or null (array t 1)))
1153   ;; Initial type of a LET variable as last seen by PROPAGATE-FROM-SETS.
1154   (last-initial-type *universal-type* :type ctype)
1155   ;; The FOP handle of the lexical variable represented by LAMBDA-VAR
1156   ;; in the fopcompiler.
1157   (fop-value nil))
1158 (defprinter (lambda-var :identity t)
1159   %source-name
1160   #!+sb-show id
1161   (type :test (not (eq type *universal-type*)))
1162   (where-from :test (not (eq where-from :assumed)))
1163   (flags :test (not (zerop flags))
1164          :prin1 (decode-lambda-var-attributes flags))
1165   (arg-info :test arg-info)
1166   (specvar :test specvar))
1167
1168 (defmacro lambda-var-ignorep (var)
1169   `(lambda-var-attributep (lambda-var-flags ,var) ignore))
1170 (defmacro lambda-var-indirect (var)
1171   `(lambda-var-attributep (lambda-var-flags ,var) indirect))
1172 (defmacro lambda-var-deleted (var)
1173   `(lambda-var-attributep (lambda-var-flags ,var) deleted))
1174 (defmacro lambda-var-explicit-value-cell (var)
1175   `(lambda-var-attributep (lambda-var-flags ,var) explicit-value-cell))
1176 \f
1177 ;;;; basic node types
1178
1179 ;;; A REF represents a reference to a LEAF. REF-REOPTIMIZE is
1180 ;;; initially (and forever) NIL, since REFs don't receive any values
1181 ;;; and don't have any IR1 optimizer.
1182 (def!struct (ref (:include valued-node (reoptimize nil))
1183                  (:constructor make-ref
1184                                (leaf
1185                                 &optional (%source-name '.anonymous.)
1186                                 &aux (leaf-type (leaf-type leaf))
1187                                 (derived-type
1188                                  (make-single-value-type leaf-type))))
1189                  (:copier nil))
1190   ;; The leaf referenced.
1191   (leaf nil :type leaf)
1192   ;; CONSTANT nodes are always anonymous, since we wish to coalesce named and
1193   ;; unnamed constants that are equivalent, we need to keep track of the
1194   ;; reference name for XREF.
1195   (%source-name (missing-arg) :type symbol :read-only t))
1196 (defprinter (ref :identity t)
1197   #!+sb-show id
1198   (%source-name :test (neq %source-name '.anonymous.))
1199   leaf)
1200
1201 ;;; Naturally, the IF node always appears at the end of a block.
1202 (def!struct (cif (:include node)
1203                  (:conc-name if-)
1204                  (:predicate if-p)
1205                  (:constructor make-if)
1206                  (:copier copy-if))
1207   ;; LVAR for the predicate
1208   (test (missing-arg) :type lvar)
1209   ;; the blocks that we execute next in true and false case,
1210   ;; respectively (may be the same)
1211   (consequent (missing-arg) :type cblock)
1212   (consequent-constraints nil :type (or null t #| FIXME: conset |#))
1213   (alternative (missing-arg) :type cblock)
1214   (alternative-constraints nil :type (or null t #| FIXME: conset |#)))
1215 (defprinter (cif :conc-name if- :identity t)
1216   (test :prin1 (lvar-uses test))
1217   consequent
1218   alternative)
1219
1220 (def!struct (cset (:include valued-node
1221                            (derived-type (make-single-value-type
1222                                           *universal-type*)))
1223                   (:conc-name set-)
1224                   (:predicate set-p)
1225                   (:constructor make-set)
1226                   (:copier copy-set))
1227   ;; descriptor for the variable set
1228   (var (missing-arg) :type basic-var)
1229   ;; LVAR for the value form
1230   (value (missing-arg) :type lvar))
1231 (defprinter (cset :conc-name set- :identity t)
1232   var
1233   (value :prin1 (lvar-uses value)))
1234
1235 ;;; The BASIC-COMBINATION structure is used to represent both normal
1236 ;;; and multiple value combinations. In a let-like function call, this
1237 ;;; node appears at the end of its block and the body of the called
1238 ;;; function appears as the successor; the NODE-LVAR is null.
1239 (def!struct (basic-combination (:include valued-node)
1240                                (:constructor nil)
1241                                (:copier nil))
1242   ;; LVAR for the function
1243   (fun (missing-arg) :type lvar)
1244   ;; list of LVARs for the args. In a local call, an argument lvar may
1245   ;; be replaced with NIL to indicate that the corresponding variable
1246   ;; is unreferenced, and thus no argument value need be passed.
1247   (args nil :type list)
1248   ;; the kind of function call being made. :LOCAL means that this is a
1249   ;; local call to a function in the same component, and that argument
1250   ;; syntax checking has been done, etc.  Calls to known global
1251   ;; functions are represented by storing :KNOWN in this slot and the
1252   ;; FUN-INFO for that function in the FUN-INFO slot.  :FULL is a call
1253   ;; to an (as yet) unknown function, or to a known function declared
1254   ;; NOTINLINE. :ERROR is like :FULL, but means that we have
1255   ;; discovered that the call contains an error, and should not be
1256   ;; reconsidered for optimization.
1257   (kind :full :type (member :local :full :error :known))
1258   ;; if a call to a known global function, contains the FUN-INFO.
1259   (fun-info nil :type (or fun-info null))
1260   ;; Untrusted type we have asserted for this combination.
1261   (type-validated-for-leaf nil)
1262   ;; some kind of information attached to this node by the back end
1263   (info nil)
1264   (step-info))
1265
1266 ;;; The COMBINATION node represents all normal function calls,
1267 ;;; including FUNCALL. This is distinct from BASIC-COMBINATION so that
1268 ;;; an MV-COMBINATION isn't COMBINATION-P.
1269 (def!struct (combination (:include basic-combination)
1270                          (:constructor make-combination (fun))
1271                          (:copier nil)))
1272 (defprinter (combination :identity t)
1273   #!+sb-show id
1274   (fun :prin1 (lvar-uses fun))
1275   (args :prin1 (mapcar (lambda (x)
1276                          (if x
1277                              (lvar-uses x)
1278                              "<deleted>"))
1279                        args)))
1280
1281 ;;; An MV-COMBINATION is to MULTIPLE-VALUE-CALL as a COMBINATION is to
1282 ;;; FUNCALL. This is used to implement all the multiple-value
1283 ;;; receiving forms.
1284 (def!struct (mv-combination (:include basic-combination)
1285                             (:constructor make-mv-combination (fun))
1286                             (:copier nil)))
1287 (defprinter (mv-combination)
1288   (fun :prin1 (lvar-uses fun))
1289   (args :prin1 (mapcar #'lvar-uses args)))
1290
1291 ;;; The BIND node marks the beginning of a lambda body and represents
1292 ;;; the creation and initialization of the variables.
1293 (def!struct (bind (:include node)
1294                   (:copier nil))
1295   ;; the lambda we are binding variables for. Null when we are
1296   ;; creating the LAMBDA during IR1 translation.
1297   (lambda nil :type (or clambda null)))
1298 (defprinter (bind)
1299   lambda)
1300
1301 ;;; The RETURN node marks the end of a lambda body. It collects the
1302 ;;; return values and represents the control transfer on return. This
1303 ;;; is also where we stick information used for TAIL-SET type
1304 ;;; inference.
1305 (def!struct (creturn (:include node)
1306                      (:conc-name return-)
1307                      (:predicate return-p)
1308                      (:constructor make-return)
1309                      (:copier copy-return))
1310   ;; the lambda we are returning from. Null temporarily during
1311   ;; ir1tran.
1312   (lambda nil :type (or clambda null))
1313   ;; the lvar which yields the value of the lambda
1314   (result (missing-arg) :type lvar)
1315   ;; the union of the node-derived-type of all uses of the result
1316   ;; other than by a local call, intersected with the result's
1317   ;; asserted-type. If there are no non-call uses, this is
1318   ;; *EMPTY-TYPE*
1319   (result-type *wild-type* :type ctype))
1320 (defprinter (creturn :conc-name return- :identity t)
1321   lambda
1322   result-type)
1323
1324 ;;; The CAST node represents type assertions. The check for
1325 ;;; TYPE-TO-CHECK is performed and then the VALUE is declared to be of
1326 ;;; type ASSERTED-TYPE.
1327 (def!struct (cast (:include valued-node)
1328                   (:constructor %make-cast))
1329   (asserted-type (missing-arg) :type ctype)
1330   (type-to-check (missing-arg) :type ctype)
1331   ;; an indication of what we have proven about how this type
1332   ;; assertion is satisfied:
1333   ;;
1334   ;; NIL
1335   ;;    No type check is necessary (VALUE type is a subtype of the TYPE-TO-CHECK.)
1336   ;;
1337   ;; :EXTERNAL
1338   ;;    Type check will be performed by NODE-DEST.
1339   ;;
1340   ;; T
1341   ;;    A type check is needed.
1342   (%type-check t :type (member t :external nil))
1343   ;; the lvar which is checked
1344   (value (missing-arg) :type lvar))
1345 (defprinter (cast :identity t)
1346   %type-check
1347   value
1348   asserted-type
1349   type-to-check)
1350 \f
1351 ;;;; non-local exit support
1352 ;;;;
1353 ;;;; In IR1, we insert special nodes to mark potentially non-local
1354 ;;;; lexical exits.
1355
1356 ;;; The ENTRY node serves to mark the start of the dynamic extent of a
1357 ;;; lexical exit. It is the mess-up node for the corresponding :ENTRY
1358 ;;; cleanup.
1359 (def!struct (entry (:include node)
1360                    (:copier nil))
1361   ;; All of the EXIT nodes for potential non-local exits to this point.
1362   (exits nil :type list)
1363   ;; The cleanup for this entry. NULL only temporarily.
1364   (cleanup nil :type (or cleanup null)))
1365 (defprinter (entry :identity t)
1366   #!+sb-show id)
1367
1368 ;;; The EXIT node marks the place at which exit code would be emitted,
1369 ;;; if necessary. This is interposed between the uses of the exit
1370 ;;; continuation and the exit continuation's DEST. Instead of using
1371 ;;; the returned value being delivered directly to the exit
1372 ;;; continuation, it is delivered to our VALUE lvar. The original exit
1373 ;;; lvar is the exit node's LVAR; physenv analysis also makes it the
1374 ;;; lvar of %NLX-ENTRY call.
1375 (def!struct (exit (:include valued-node)
1376                   (:copier nil))
1377   ;; the ENTRY node that this is an exit for. If null, this is a
1378   ;; degenerate exit. A degenerate exit is used to "fill" an empty
1379   ;; block (which isn't allowed in IR1.) In a degenerate exit, Value
1380   ;; is always also null.
1381   (entry nil :type (or entry null))
1382   ;; the lvar yielding the value we are to exit with. If NIL, then no
1383   ;; value is desired (as in GO).
1384   (value nil :type (or lvar null))
1385   (nlx-info nil :type (or nlx-info null)))
1386 (defprinter (exit :identity t)
1387   #!+sb-show id
1388   (entry :test entry)
1389   (value :test value))
1390 \f
1391 ;;;; miscellaneous IR1 structures
1392
1393 (def!struct (undefined-warning
1394             #-no-ansi-print-object
1395             (:print-object (lambda (x s)
1396                              (print-unreadable-object (x s :type t)
1397                                (prin1 (undefined-warning-name x) s))))
1398             (:copier nil))
1399   ;; the name of the unknown thing
1400   (name nil :type (or symbol list))
1401   ;; the kind of reference to NAME
1402   (kind (missing-arg) :type (member :function :type :variable))
1403   ;; the number of times this thing was used
1404   (count 0 :type unsigned-byte)
1405   ;; a list of COMPILER-ERROR-CONTEXT structures describing places
1406   ;; where this thing was used. Note that we only record the first
1407   ;; *UNDEFINED-WARNING-LIMIT* calls.
1408   (warnings () :type list))
1409 \f
1410 ;;; a helper for the POLICY macro, defined late here so that the
1411 ;;; various type tests can be inlined
1412 (declaim (ftype (function ((or list lexenv node functional)) list)
1413                 %coerce-to-policy))
1414 (defun %coerce-to-policy (thing)
1415   (let ((result (etypecase thing
1416                   (list thing)
1417                   (lexenv (lexenv-policy thing))
1418                   (node (lexenv-policy (node-lexenv thing)))
1419                   (functional (lexenv-policy (functional-lexenv thing))))))
1420     ;; Test the first element of the list as a rudimentary sanity
1421     ;; that it really does look like a valid policy.
1422     (aver (or (null result) (policy-quality-name-p (caar result))))
1423     ;; Voila.
1424     result))
1425 \f
1426 ;;;; Freeze some structure types to speed type testing.
1427
1428 #!-sb-fluid
1429 (declaim (freeze-type node leaf lexenv ctran lvar cblock component cleanup
1430                       physenv tail-set nlx-info))