68469c8f2dd921333d71ccf9affccde282bbbb1f
[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 call relationships.
259         (let ((calls (if (eq (lambda-kind clambda) :external)
260                          (append (find-reference-funs clambda)
261                                  (lambda-calls clambda))
262                          (lambda-calls clambda))))
263           (dolist (call calls)
264             (let ((call-home (lambda-home call)))
265               (setf res (dfo-scavenge-dependency-graph call-home res)))))
266         ;; Scavenge closure-over relationships: if FUN refers to a
267         ;; variable whose home lambda is not FUN, then the home lambda
268         ;; should be in the same component as FUN. (sbcl-0.6.13, and
269         ;; CMU CL, didn't do this, leading to the occasional failure
270         ;; when physenv analysis, which is local to each component,
271         ;; would bogusly conclude that a closed-over variable was
272         ;; unused and thus delete it. See e.g. cmucl-imp 2001-11-29.)
273         (dolist (var (lambda-refers-to-vars clambda))
274           (unless (null (lambda-var-refs var)) ; i.e. unless deleted
275             (let ((var-home-home (lambda-home (lambda-var-home var))))
276               (unless (eql (lambda-kind var-home-home) :deleted)
277                 (setf res
278                       (dfo-scavenge-dependency-graph var-home-home res))))))
279         ;; Voila.
280         res)))))
281
282 ;;; Return true if CLAMBDA either is an XEP or has EXITS to some of
283 ;;; its ENTRIES.
284 (defun has-xep-or-nlx (clambda)
285   (declare (type clambda clambda))
286   (or (eq (functional-kind clambda) :external)
287       (let ((entries (lambda-entries clambda)))
288         (and entries
289              (find-if #'entry-exits entries)))))
290
291 ;;; Compute the result of FIND-INITIAL-DFO given the list of all
292 ;;; resulting components. Components with a :TOPLEVEL lambda, but no
293 ;;; normal XEPs or potential non-local exits are marked as :TOPLEVEL.
294 ;;; If there is a :TOPLEVEL lambda, and also a normal XEP, then we
295 ;;; treat the component as normal, but also return such components in
296 ;;; a list as the third value. Components with no entry of any sort
297 ;;; are deleted.
298 (defun separate-toplevelish-components (components)
299   (declare (list components))
300   (collect ((real)
301             (top)
302             (real-top))
303     (dolist (component components)
304       (unless (eq (block-next (component-head component))
305                   (component-tail component))
306         (let* ((funs (component-lambdas component))
307                (has-top (find :toplevel funs :key #'functional-kind))
308                (has-external-references
309                 (some #'functional-has-external-references-p funs)))
310           (cond (;; The FUNCTIONAL-HAS-EXTERNAL-REFERENCES-P concept
311                  ;; is newer than the rest of this function, and
312                  ;; doesn't really seem to fit into its mindset. Here
313                  ;; we mark components which contain such FUNCTIONs
314                  ;; them as :COMPLEX-TOPLEVEL, since they do get
315                  ;; executed at run time, and since it's not valid to
316                  ;; delete them just because they don't have any
317                  ;; references from pure :TOPLEVEL components. -- WHN
318                  has-external-references
319                  (setf (component-kind component) :complex-toplevel)
320                  (real component)
321                  (real-top component))
322                 ((or (some #'has-xep-or-nlx funs)
323                      (and has-top (rest funs)))
324                  (setf (component-name component)
325                        (find-component-name component))
326                  (real component)
327                  (when has-top
328                    (setf (component-kind component) :complex-toplevel)
329                    (real-top component)))
330                 (has-top
331                  (setf (component-kind component) :toplevel)
332                  (setf (component-name component) "top level form")
333                  (top component))
334                 (t
335                  (delete-component component))))))
336
337     (values (real) (top) (real-top))))
338
339 ;; COMPONENTs want strings for names, LEAF-DEBUG-NAMEs mightn't be
340 ;; strings..
341 (defun component-name-from-functional-debug-name (functional)
342   (declare (type functional functional))
343   (let ((leaf-debug-name (leaf-debug-name functional)))
344     (the simple-string
345       (if (stringp leaf-debug-name)
346           leaf-debug-name
347           (debug-namify "function ~S" leaf-debug-name)))))
348
349 ;;; Given a list of top level lambdas, return
350 ;;;   (VALUES NONTOP-COMPONENTS TOP-COMPONENTS HAIRY-TOP-COMPONENTS).
351 ;;; Each of the three values returned is a list of COMPONENTs:
352 ;;;   NONTOP-COMPONENTS = non-top-level-ish COMPONENTs;
353 ;;;   TOP-COMPONENTS = top-level-ish COMPONENTs;
354 ;;;   HAIRY-TOP-COMPONENTS = a subset of NONTOP-COMPONENTS, those
355 ;;;    elements which include a top-level-ish lambda.
356 ;;;
357 ;;; We assign the DFO for each component, and delete any unreachable
358 ;;; blocks. We assume that the FLAGS have already been cleared.
359 (defun find-initial-dfo (toplevel-lambdas)
360   (declare (list toplevel-lambdas))
361   (collect ((components))
362     ;; We iterate over the lambdas in each initial component, trying
363     ;; to put each function in its own component, but joining it to
364     ;; an existing component if we find that there are references
365     ;; between them. Any code that is left in an initial component
366     ;; must be unreachable, so we can delete it. Stray links to the
367     ;; initial component tail (due NIL function terminated blocks)
368     ;; are moved to the appropriate new component tail.
369     (dolist (toplevel-lambda toplevel-lambdas)
370       (let* ((block (lambda-block toplevel-lambda))
371              (old-component (block-component block))
372              (old-component-lambdas (component-lambdas old-component))
373              (new-component nil))
374         (aver (member toplevel-lambda old-component-lambdas))
375         (dolist (component-lambda old-component-lambdas)
376           (aver (member (functional-kind component-lambda)
377                         '(:optional :external :toplevel nil :escape
378                                     :cleanup)))
379           (unless new-component
380             (setf new-component (make-empty-component))
381             (setf (component-name new-component)
382                   ;; This isn't necessarily an ideal name for the
383                   ;; component, since it might end up with multiple
384                   ;; lambdas in it, not just this one, but it does
385                   ;; seem a better name than just "<unknown>".
386                   (component-name-from-functional-debug-name
387                    component-lambda)))
388           (let ((res (dfo-scavenge-dependency-graph component-lambda
389                                                     new-component)))
390             (when (eq res new-component)
391               (aver (not (position new-component (components))))
392               (components new-component)
393               (setq new-component nil))))
394         (when (eq (component-kind old-component) :initial)
395           (aver (null (component-lambdas old-component)))
396           (let ((tail (component-tail old-component)))
397             (dolist (pred (block-pred tail))
398               (let ((pred-component (block-component pred)))
399                 (unless (eq pred-component old-component)
400                   (unlink-blocks pred tail)
401                   (link-blocks pred (component-tail pred-component))))))
402           (delete-component old-component))))
403
404     ;; When we are done, we assign DFNs.
405     (dolist (component (components))
406       (let ((num 0))
407         (declare (fixnum num))
408         (do-blocks-backwards (block component :both)
409           (setf (block-number block) (incf num)))))
410
411     ;; Pull out top-level-ish code.
412     (separate-toplevelish-components (components))))
413 \f
414 ;;; Insert the code in LAMBDA at the end of RESULT-LAMBDA.
415 (defun merge-1-toplevel-lambda (result-lambda lambda)
416   (declare (type clambda result-lambda lambda))
417
418   ;; Delete the lambda, and combine the LETs and entries.
419   (setf (functional-kind lambda) :deleted)
420   (dolist (let (lambda-lets lambda))
421     (setf (lambda-home let) result-lambda)
422     (setf (lambda-physenv let) (lambda-physenv result-lambda))
423     (push let (lambda-lets result-lambda)))
424   (setf (lambda-entries result-lambda)
425         (nconc (lambda-entries result-lambda)
426                (lambda-entries lambda)))
427
428   (let* ((bind (lambda-bind lambda))
429          (bind-block (node-block bind))
430          (component (block-component bind-block))
431          (result-component (lambda-component result-lambda))
432          (result-return-block (node-block (lambda-return result-lambda))))
433
434     ;; Move blocks into the new COMPONENT, and move any nodes directly
435     ;; in the old LAMBDA into the new one (with LETs implicitly moved
436     ;; by changing their home.)
437     (do-blocks (block component)
438       (do-nodes (node cont block)
439         (let ((lexenv (node-lexenv node)))
440           (when (eq (lexenv-lambda lexenv) lambda)
441             (setf (lexenv-lambda lexenv) result-lambda))))
442       (setf (block-component block) result-component))
443
444     ;; Splice the blocks into the new DFO, and unlink them from the
445     ;; old component head and tail. Non-return blocks that jump to the
446     ;; tail (NIL-returning calls) are switched to go to the new tail.
447     (let* ((head (component-head component))
448            (first (block-next head))
449            (tail (component-tail component))
450            (last (block-prev tail))
451            (prev (block-prev result-return-block)))
452       (setf (block-next prev) first)
453       (setf (block-prev first) prev)
454       (setf (block-next last) result-return-block)
455       (setf (block-prev result-return-block) last)
456       (dolist (succ (block-succ head))
457         (unlink-blocks head succ))
458       (dolist (pred (block-pred tail))
459         (unlink-blocks pred tail)
460         (let ((last (block-last pred)))
461           (unless (return-p last)
462             (aver (basic-combination-p last))
463             (link-blocks pred (component-tail result-component))))))
464
465     (let ((lambdas (component-lambdas component)))
466       (aver (and (null (rest lambdas))
467                  (eq (first lambdas) lambda))))
468
469     ;; Switch the end of the code from the return block to the start of
470     ;; the next chunk.
471     (dolist (pred (block-pred result-return-block))
472       (unlink-blocks pred result-return-block)
473       (link-blocks pred bind-block))
474     (unlink-node bind)
475
476     ;; If there is a return, then delete it (making the preceding node
477     ;; the last node) and link the block to the result return. There
478     ;; is always a preceding REF NIL node in top level lambdas.
479     (let ((return (lambda-return lambda)))
480       (when return
481         (let ((return-block (node-block return))
482               (result (return-result return)))
483           (setf (block-last return-block) (continuation-use result))
484           (flush-dest result)
485           (delete-continuation result)
486           (link-blocks return-block result-return-block))))))
487
488 ;;; Given a non-empty list of top level LAMBDAs, smash them into a
489 ;;; top level lambda and component, returning these as values. We use
490 ;;; the first lambda and its component, putting the other code in that
491 ;;; component and deleting the other lambdas.
492 (defun merge-toplevel-lambdas (lambdas)
493   (declare (cons lambdas))
494   (let* ((result-lambda (first lambdas))
495          (result-return (lambda-return result-lambda)))
496     (cond
497      (result-return
498
499       ;; Make sure the result's return node starts a block so that we
500       ;; can splice code in before it.
501       (let ((prev (node-prev
502                    (continuation-use
503                     (return-result result-return)))))
504         (when (continuation-use prev)
505           (node-ends-block (continuation-use prev)))
506         (do-uses (use prev)
507           (let ((new (make-continuation)))
508             (delete-continuation-use use)
509             (add-continuation-use use new))))
510
511       (dolist (lambda (rest lambdas))
512         (merge-1-toplevel-lambda result-lambda lambda)))
513      (t
514       (dolist (lambda (rest lambdas))
515         (setf (functional-entry-fun lambda) nil)
516         (delete-component (lambda-component lambda)))))
517
518     (values (lambda-component result-lambda) result-lambda)))