0.pre7.113:
[sbcl.git] / src / compiler / dfo.lisp
1 ;;;; This file contains the code that finds the initial components and
2 ;;;; DFO, and recomputes the DFO if it is invalidated.
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 ;;; Find the DFO for a component, deleting any unreached blocks and
16 ;;; merging any other components we reach. We repeatedly iterate over
17 ;;; the entry points, since new ones may show up during the walk.
18 (declaim (ftype (function (component) (values)) find-dfo))
19 (defun find-dfo (component)
20   (clear-flags component)
21   (setf (component-reanalyze component) nil)
22   (let ((head (component-head component)))
23     (do ()
24         ((dolist (ep (block-succ head) t)
25            (unless (block-flag ep)
26              (find-dfo-aux ep head component)
27              (return nil))))))
28   (let ((num 0))
29     (declare (fixnum num))
30     (do-blocks-backwards (block component :both)
31       (if (block-flag block)
32           (setf (block-number block) (incf num))
33           (setf (block-delete-p block) t)))
34     (do-blocks (block component)
35       (unless (block-flag block)
36         (delete-block block))))
37   (values))
38
39 ;;; Move all the code and entry points from OLD to NEW. The code in
40 ;;; OLD is inserted at the head of NEW. This is also called during LET
41 ;;; conversion when we are about in insert the body of a LET in a
42 ;;; different component. [A local call can be to a different component
43 ;;; before FIND-INITIAL-DFO runs.]
44 (declaim (ftype (function (component component) (values)) join-components))
45 (defun join-components (new old)
46   (aver (eq (component-kind new) (component-kind old)))
47   (let ((old-head (component-head old))
48         (old-tail (component-tail old))
49         (head (component-head new))
50         (tail (component-tail new)))
51
52     (do-blocks (block old)
53       (setf (block-flag block) nil)
54       (setf (block-component block) new))
55
56     (let ((old-next (block-next old-head))
57           (old-last (block-prev old-tail))
58           (next (block-next head)))
59       (unless (eq old-next old-tail)
60         (setf (block-next head) old-next)
61         (setf (block-prev old-next) head)
62         
63         (setf (block-prev next) old-last)
64         (setf (block-next old-last) next))
65
66       (setf (block-next old-head) old-tail)
67       (setf (block-prev old-tail) old-head))
68
69     (setf (component-lambdas new)
70           (nconc (component-lambdas old) (component-lambdas new)))
71     (setf (component-lambdas old) nil)
72     (setf (component-new-funs new) (nconc (component-new-funs old)
73                                           (component-new-funs new))
74           (component-new-funs old) nil)
75
76     (dolist (xp (block-pred old-tail))
77       (unlink-blocks xp old-tail)
78       (link-blocks xp tail))
79     (dolist (ep (block-succ old-head))
80       (unlink-blocks old-head ep)
81       (link-blocks head ep)))
82   (values))
83
84 ;;; Do a depth-first walk from BLOCK, inserting ourself in the DFO
85 ;;; after HEAD. If we somehow find ourselves in another component,
86 ;;; then we join that component to our component.
87 (declaim (ftype (function (cblock cblock component) (values)) find-dfo-aux))
88 (defun find-dfo-aux (block head component)
89   (unless (eq (block-component block) component)
90     (join-components component (block-component block)))
91   (unless (block-flag block)
92     (setf (block-flag block) t)
93     (dolist (succ (block-succ block))
94       (find-dfo-aux succ head component))
95     (remove-from-dfo block)
96     (add-to-dfo block head))
97   (values))
98
99 ;;; This function is called on each block by FIND-INITIAL-DFO-AUX
100 ;;; before it walks the successors. It looks at the home CLAMBDA's
101 ;;; BIND block to see whether that block is in some other component:
102 ;;; -- If the block is in the initial component, then do
103 ;;;    DFO-WALK-DEPENDENCY-GRAPH on the home function to move it
104 ;;;    into COMPONENT.
105 ;;; -- If the block is in some other component, join COMPONENT into
106 ;;;    it and return that component.
107 ;;; -- If the home function is deleted, do nothing. BLOCK must
108 ;;;    eventually be discovered to be unreachable as well. This can
109 ;;;    happen when we have a NLX into a function with no references.
110 ;;;    The escape function still has refs (in the deleted function).
111 ;;;
112 ;;; This ensures that all the blocks in a given environment will be in
113 ;;; the same component, even when they might not seem reachable from
114 ;;; the environment entry. Consider the case of code that is only
115 ;;; reachable from a non-local exit.
116 (defun scavenge-home-dependency-graph (block component)
117   (declare (type cblock block) (type component component))
118   (let ((home-lambda (block-home-lambda block)))
119     (if (eq (functional-kind home-lambda) :deleted)
120         component
121         (let ((home-component (lambda-component home-lambda)))
122           (cond ((eq (component-kind home-component) :initial)
123                  (dfo-scavenge-dependency-graph home-lambda component))
124                 ((eq home-component component)
125                  component)
126                 (t
127                  (join-components home-component component)
128                  home-component))))))
129
130 ;;; This is somewhat similar to FIND-DFO-AUX, except that it merges
131 ;;; the current component with any strange component, rather than the
132 ;;; other way around. This is more efficient in the common case where
133 ;;; the current component doesn't have much stuff in it.
134 ;;;
135 ;;; We return the current component as a result, allowing the caller
136 ;;; to detect when the old current component has been merged with
137 ;;; another.
138 ;;;
139 ;;; We walk blocks in initial components as though they were already
140 ;;; in the current component, moving them to the current component in
141 ;;; the process. The blocks are inserted at the head of the current
142 ;;; component.
143 (defun find-initial-dfo-aux (block component)
144   (declare (type cblock block) (type component component))
145   (let ((this (block-component block)))
146     (cond
147      ((not (or (eq this component)
148                (eq (component-kind this) :initial)))
149       (join-components this component)
150       this)
151      ((block-flag block) component)
152      (t
153       (setf (block-flag block) t)
154       (let ((current (scavenge-home-dependency-graph block component)))
155         (dolist (succ (block-succ block))
156           (setq current (find-initial-dfo-aux succ current)))
157         (remove-from-dfo block)
158         (add-to-dfo block (component-head current))
159         current)))))
160
161 ;;; Return a list of all the home lambdas that reference FUN (may
162 ;;; contain duplications).
163 ;;;
164 ;;; References to functions which local call analysis could not (or
165 ;;; were chosen not) to local call convert will appear as references
166 ;;; to XEP lambdas. We can ignore references to XEPs that appear in
167 ;;; :TOPLEVEL components, since environment analysis goes to special
168 ;;; effort to allow closing over of values from a separate top level
169 ;;; component. (And now that HAS-EXTERNAL-REFERENCES-P-ness
170 ;;; generalizes :TOPLEVEL-ness, we ignore those too.) All other
171 ;;; references must cause components to be joined.
172 ;;;
173 ;;; References in deleted functions are also ignored, since this code
174 ;;; will be deleted eventually.
175 (defun find-reference-funs (fun)
176   (collect ((res))
177     (dolist (ref (leaf-refs fun))
178       (let* ((home (node-home-lambda ref))
179              (home-kind (functional-kind home))
180              (home-externally-visible-p
181               (or (eq home-kind :toplevel)
182                   (functional-has-external-references-p home))))
183         (unless (or (and home-externally-visible-p
184                          (eq (functional-kind fun) :external))
185                     (eq home-kind :deleted))
186           (res home))))
187     (res)))
188
189 ;;; If CLAMBDA is not already in COMPONENT, just return that
190 ;;; component. Otherwise, move the code for CLAMBDA and all lambdas it
191 ;;; physically depends on (either because of calls or because of
192 ;;; closure relationships) into COMPONENT, or possibly into another
193 ;;; COMPONENT that we find to be related. Return whatever COMPONENT we
194 ;;; actually merged into.
195 ;;;
196 ;;; (Note: The analogous CMU CL code only scavenged call-based
197 ;;; dependencies, not closure dependencies. That seems to've been by
198 ;;; oversight, not by design, as per the bug reported by WHN on
199 ;;; cmucl-imp ca. 2001-11-29 and explained by DTC shortly after.)
200 ;;;
201 ;;; FIXME: Very likely we should be scavenging NLX-based dependencies
202 ;;; here too. OTOH, there's a lot of global weirdness in NLX handling,
203 ;;; so it might be taken care of some other way that I haven't figured
204 ;;; out yet. Perhaps the best way to address this would be to try to
205 ;;; construct a NLX-based test case which fails in the same way as the
206 ;;; closure-based test case on cmucl-imp 2001-11-29.)
207 ;;;
208 ;;; If the function is in an initial component, then we move its head
209 ;;; and tail to COMPONENT and add it to COMPONENT's lambdas. It is
210 ;;; harmless to move the tail (even though the return might be
211 ;;; unreachable) because if the return is unreachable it (and its
212 ;;; successor link) will be deleted in the post-deletion pass.
213 ;;;
214 ;;; We then do a FIND-DFO-AUX starting at the head of CLAMBDA. If this
215 ;;; flow-graph walk encounters another component (which can only
216 ;;; happen due to a non-local exit), then we move code into that
217 ;;; component instead. We then recurse on all functions called from
218 ;;; CLAMBDA, moving code into whichever component the preceding call
219 ;;; returned.
220 ;;;
221 ;;; If CLAMBDA is in the initial component, but the BLOCK-FLAG is set
222 ;;; in the bind block, then we just return COMPONENT, since we must
223 ;;; have already reached this function in the current walk (or the
224 ;;; component would have been changed).
225 ;;;
226 ;;; If the function is an XEP, then we also walk all functions that
227 ;;; contain references to the XEP. This is done so that environment
228 ;;; analysis doesn't need to cross component boundaries. This also
229 ;;; ensures that conversion of a full call to a local call won't
230 ;;; result in a need to join components, since the components will
231 ;;; already be one.
232 (defun dfo-scavenge-dependency-graph (clambda component)
233   (declare (type clambda clambda) (type component component))
234   (assert (not (eql (lambda-kind clambda) :deleted)))
235   (let* ((bind-block (node-block (lambda-bind clambda)))
236          (old-lambda-component (block-component bind-block))
237          (return (lambda-return clambda)))
238     (cond
239      ((eq old-lambda-component component)
240       component)
241      ((not (eq (component-kind old-lambda-component) :initial))
242       (join-components old-lambda-component component)
243       old-lambda-component)
244      ((block-flag bind-block)
245       component)
246      (t
247       (push clambda (component-lambdas component))
248       (setf (component-lambdas old-lambda-component)
249             (delete clambda (component-lambdas old-lambda-component)))
250       (link-blocks (component-head component) bind-block)
251       (unlink-blocks (component-head old-lambda-component) bind-block)
252       (when return
253         (let ((return-block (node-block return)))
254           (link-blocks return-block (component-tail component))
255           (unlink-blocks return-block (component-tail old-lambda-component))))
256       (let ((res (find-initial-dfo-aux bind-block component)))
257         (declare (type component res))
258         ;; Scavenge related lambdas.
259         (labels ((scavenge-lambda (clambda)
260                    (setf res
261                          (dfo-scavenge-dependency-graph (lambda-home clambda)
262                                                         res)))
263                  (scavenge-possibly-deleted-lambda (clambda)
264                    (unless (eql (lambda-kind clambda) :deleted)
265                      (scavenge-lambda clambda)))
266                  ;; Scavenge call relationship.
267                  (scavenge-call (called-lambda)
268                    (scavenge-lambda called-lambda))
269                  ;; Scavenge closure over a variable: if CLAMBDA
270                  ;; refers to a variable whose home lambda is not
271                  ;; CLAMBDA, then the home lambda should be in the
272                  ;; same component as CLAMBDA. (sbcl-0.6.13, and CMU
273                  ;; CL, didn't do this, leading to the occasional
274                  ;; failure when physenv analysis, which is local to
275                  ;; each component, would bogusly conclude that a
276                  ;; closed-over variable was unused and thus delete
277                  ;; it. See e.g. cmucl-imp 2001-11-29.)
278                  (scavenge-closure-var (var)
279                    (unless (null (lambda-var-refs var)) ; unless var deleted
280                      (let ((var-home-home (lambda-home (lambda-var-home var))))
281                        (scavenge-possibly-deleted-lambda var-home-home))))
282                  ;; Scavenge closure over an entry for nonlocal exit.
283                  ;; This is basically parallel to closure over a
284                  ;; variable above.
285                  (scavenge-entry (entry)
286                    (declare (type entry entry))
287                    (let ((entry-home (node-home-lambda entry)))
288                      (scavenge-possibly-deleted-lambda entry-home))))
289           (dolist (cc (lambda-calls-or-closes clambda))
290             (etypecase cc
291               (clambda (scavenge-call cc))
292               (lambda-var (scavenge-closure-var cc))
293               (entry (scavenge-entry cc))))
294           (when (eq (lambda-kind clambda) :external)
295             (mapc #'scavenge-call (find-reference-funs clambda))))
296         ;; Voila.
297         res)))))
298
299 ;;; Return true if CLAMBDA either is an XEP or has EXITS to some of
300 ;;; its ENTRIES.
301 (defun has-xep-or-nlx (clambda)
302   (declare (type clambda clambda))
303   (or (eq (functional-kind clambda) :external)
304       (let ((entries (lambda-entries clambda)))
305         (and entries
306              (find-if #'entry-exits entries)))))
307
308 ;;; Compute the result of FIND-INITIAL-DFO given the list of all
309 ;;; resulting components. Components with a :TOPLEVEL lambda, but no
310 ;;; normal XEPs or potential non-local exits are marked as :TOPLEVEL.
311 ;;; If there is a :TOPLEVEL lambda, and also a normal XEP, then we
312 ;;; treat the component as normal, but also return such components in
313 ;;; a list as the third value. Components with no entry of any sort
314 ;;; are deleted.
315 (defun separate-toplevelish-components (components)
316   (declare (list components))
317   (collect ((real)
318             (top)
319             (real-top))
320     (dolist (component components)
321       (unless (eq (block-next (component-head component))
322                   (component-tail component))
323         (let* ((funs (component-lambdas component))
324                (has-top (find :toplevel funs :key #'functional-kind))
325                (has-external-references
326                 (some #'functional-has-external-references-p funs)))
327           (cond (;; The FUNCTIONAL-HAS-EXTERNAL-REFERENCES-P concept
328                  ;; is newer than the rest of this function, and
329                  ;; doesn't really seem to fit into its mindset. Here
330                  ;; we mark components which contain such FUNCTIONs
331                  ;; them as :COMPLEX-TOPLEVEL, since they do get
332                  ;; executed at run time, and since it's not valid to
333                  ;; delete them just because they don't have any
334                  ;; references from pure :TOPLEVEL components. -- WHN
335                  has-external-references
336                  (setf (component-kind component) :complex-toplevel)
337                  (real component)
338                  (real-top component))
339                 ((or (some #'has-xep-or-nlx funs)
340                      (and has-top (rest funs)))
341                  (setf (component-name component)
342                        (find-component-name component))
343                  (real component)
344                  (when has-top
345                    (setf (component-kind component) :complex-toplevel)
346                    (real-top component)))
347                 (has-top
348                  (setf (component-kind component) :toplevel)
349                  (setf (component-name component) "top level form")
350                  (top component))
351                 (t
352                  (delete-component component))))))
353
354     (values (real) (top) (real-top))))
355
356 ;; COMPONENTs want strings for names, LEAF-DEBUG-NAMEs mightn't be
357 ;; strings..
358 (defun component-name-from-functional-debug-name (functional)
359   (declare (type functional functional))
360   (let ((leaf-debug-name (leaf-debug-name functional)))
361     (the simple-string
362       (if (stringp leaf-debug-name)
363           leaf-debug-name
364           (debug-namify "function ~S" leaf-debug-name)))))
365
366 ;;; Given a list of top level lambdas, return
367 ;;;   (VALUES NONTOP-COMPONENTS TOP-COMPONENTS HAIRY-TOP-COMPONENTS).
368 ;;; Each of the three values returned is a list of COMPONENTs:
369 ;;;   NONTOP-COMPONENTS = non-top-level-ish COMPONENTs;
370 ;;;   TOP-COMPONENTS = top-level-ish COMPONENTs;
371 ;;;   HAIRY-TOP-COMPONENTS = a subset of NONTOP-COMPONENTS, those
372 ;;;    elements which include a top-level-ish lambda.
373 ;;;
374 ;;; We assign the DFO for each component, and delete any unreachable
375 ;;; blocks. We assume that the FLAGS have already been cleared.
376 (defun find-initial-dfo (toplevel-lambdas)
377   (declare (list toplevel-lambdas))
378   (collect ((components))
379     ;; We iterate over the lambdas in each initial component, trying
380     ;; to put each function in its own component, but joining it to
381     ;; an existing component if we find that there are references
382     ;; between them. Any code that is left in an initial component
383     ;; must be unreachable, so we can delete it. Stray links to the
384     ;; initial component tail (due NIL function terminated blocks)
385     ;; are moved to the appropriate new component tail.
386     (dolist (toplevel-lambda toplevel-lambdas)
387       (let* ((old-component (lambda-component toplevel-lambda))
388              (old-component-lambdas (component-lambdas old-component))
389              (new-component nil))
390         (aver (member toplevel-lambda old-component-lambdas))
391         (dolist (component-lambda old-component-lambdas)
392           (aver (member (functional-kind component-lambda)
393                         '(:optional :external :toplevel nil :escape
394                                     :cleanup)))
395           (unless new-component
396             (setf new-component (make-empty-component))
397             (setf (component-name new-component)
398                   ;; This isn't necessarily an ideal name for the
399                   ;; component, since it might end up with multiple
400                   ;; lambdas in it, not just this one, but it does
401                   ;; seem a better name than just "<unknown>".
402                   (component-name-from-functional-debug-name
403                    component-lambda)))
404           (let ((res (dfo-scavenge-dependency-graph component-lambda
405                                                     new-component)))
406             (when (eq res new-component)
407               (aver (not (position new-component (components))))
408               (components new-component)
409               (setq new-component nil))))
410         (when (eq (component-kind old-component) :initial)
411           (aver (null (component-lambdas old-component)))
412           (let ((tail (component-tail old-component)))
413             (dolist (pred (block-pred tail))
414               (let ((pred-component (block-component pred)))
415                 (unless (eq pred-component old-component)
416                   (unlink-blocks pred tail)
417                   (link-blocks pred (component-tail pred-component))))))
418           (delete-component old-component))))
419
420     ;; When we are done, we assign DFNs.
421     (dolist (component (components))
422       (let ((num 0))
423         (declare (fixnum num))
424         (do-blocks-backwards (block component :both)
425           (setf (block-number block) (incf num)))))
426
427     ;; Pull out top-level-ish code.
428     (separate-toplevelish-components (components))))
429 \f
430 ;;; Insert the code in LAMBDA at the end of RESULT-LAMBDA.
431 (defun merge-1-toplevel-lambda (result-lambda lambda)
432   (declare (type clambda result-lambda lambda))
433
434   ;; Delete the lambda, and combine the LETs and entries.
435   (setf (functional-kind lambda) :deleted)
436   (dolist (let (lambda-lets lambda))
437     (setf (lambda-home let) result-lambda)
438     (setf (lambda-physenv let) (lambda-physenv result-lambda))
439     (push let (lambda-lets result-lambda)))
440   (setf (lambda-entries result-lambda)
441         (nconc (lambda-entries result-lambda)
442                (lambda-entries lambda)))
443
444   (let* ((bind (lambda-bind lambda))
445          (bind-block (node-block bind))
446          (component (block-component bind-block))
447          (result-component (lambda-component result-lambda))
448          (result-return-block (node-block (lambda-return result-lambda))))
449
450     ;; Move blocks into the new COMPONENT, and move any nodes directly
451     ;; in the old LAMBDA into the new one (with LETs implicitly moved
452     ;; by changing their home.)
453     (do-blocks (block component)
454       (do-nodes (node cont block)
455         (let ((lexenv (node-lexenv node)))
456           (when (eq (lexenv-lambda lexenv) lambda)
457             (setf (lexenv-lambda lexenv) result-lambda))))
458       (setf (block-component block) result-component))
459
460     ;; Splice the blocks into the new DFO, and unlink them from the
461     ;; old component head and tail. Non-return blocks that jump to the
462     ;; tail (NIL-returning calls) are switched to go to the new tail.
463     (let* ((head (component-head component))
464            (first (block-next head))
465            (tail (component-tail component))
466            (last (block-prev tail))
467            (prev (block-prev result-return-block)))
468       (setf (block-next prev) first)
469       (setf (block-prev first) prev)
470       (setf (block-next last) result-return-block)
471       (setf (block-prev result-return-block) last)
472       (dolist (succ (block-succ head))
473         (unlink-blocks head succ))
474       (dolist (pred (block-pred tail))
475         (unlink-blocks pred tail)
476         (let ((last (block-last pred)))
477           (unless (return-p last)
478             (aver (basic-combination-p last))
479             (link-blocks pred (component-tail result-component))))))
480
481     (let ((lambdas (component-lambdas component)))
482       (aver (and (null (rest lambdas))
483                  (eq (first lambdas) lambda))))
484
485     ;; Switch the end of the code from the return block to the start of
486     ;; the next chunk.
487     (dolist (pred (block-pred result-return-block))
488       (unlink-blocks pred result-return-block)
489       (link-blocks pred bind-block))
490     (unlink-node bind)
491
492     ;; If there is a return, then delete it (making the preceding node
493     ;; the last node) and link the block to the result return. There
494     ;; is always a preceding REF NIL node in top level lambdas.
495     (let ((return (lambda-return lambda)))
496       (when return
497         (let ((return-block (node-block return))
498               (result (return-result return)))
499           (setf (block-last return-block) (continuation-use result))
500           (flush-dest result)
501           (delete-continuation result)
502           (link-blocks return-block result-return-block))))))
503
504 ;;; Given a non-empty list of top level LAMBDAs, smash them into a
505 ;;; top level lambda and component, returning these as values. We use
506 ;;; the first lambda and its component, putting the other code in that
507 ;;; component and deleting the other lambdas.
508 (defun merge-toplevel-lambdas (lambdas)
509   (declare (cons lambdas))
510   (let* ((result-lambda (first lambdas))
511          (result-return (lambda-return result-lambda)))
512     (cond
513      (result-return
514
515       ;; Make sure the result's return node starts a block so that we
516       ;; can splice code in before it.
517       (let ((prev (node-prev
518                    (continuation-use
519                     (return-result result-return)))))
520         (when (continuation-use prev)
521           (node-ends-block (continuation-use prev)))
522         (do-uses (use prev)
523           (let ((new (make-continuation)))
524             (delete-continuation-use use)
525             (add-continuation-use use new))))
526
527       (dolist (lambda (rest lambdas))
528         (merge-1-toplevel-lambda result-lambda lambda)))
529      (t
530       (dolist (lambda (rest lambdas))
531         (setf (functional-entry-fun lambda) nil)
532         (delete-component (lambda-component lambda)))))
533
534     (values (lambda-component result-lambda) result-lambda)))