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