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