sbcl-0.8.14.11:
[sbcl.git] / src / compiler / stack.lisp
1 ;;;; This file implements the stack analysis phase in the compiler. We
2 ;;;; analyse lifetime of dynamically allocated object packets on stack
3 ;;;; and insert cleanups where necessary.
4 ;;;;
5 ;;;; Currently there are two kinds of interesting stack packets: UVLs,
6 ;;;; whose use and destination lie in different blocks, and LVARs of
7 ;;;; constructors of dynamic-extent objects.
8
9 ;;;; This software is part of the SBCL system. See the README file for
10 ;;;; more information.
11 ;;;;
12 ;;;; This software is derived from the CMU CL system, which was
13 ;;;; written at Carnegie Mellon University and released into the
14 ;;;; public domain. The software is in the public domain and is
15 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
16 ;;;; files for more information.
17
18 (in-package "SB!C")
19 \f
20 ;;; Scan through BLOCK looking for uses of :UNKNOWN lvars that have
21 ;;; their DEST outside of the block. We do some checking to verify the
22 ;;; invariant that all pushes come after the last pop.
23 (defun find-pushed-lvars (block)
24   (let* ((2block (block-info block))
25          (popped (ir2-block-popped 2block))
26          (last-pop (if popped
27                        (lvar-dest (car (last popped)))
28                        nil)))
29     (collect ((pushed))
30       (let ((saw-last nil))
31         (do-nodes (node lvar block)
32           (when (eq node last-pop)
33             (setq saw-last t))
34
35           (when (and lvar
36                      (or (lvar-dynamic-extent lvar)
37                          (let ((dest (lvar-dest lvar))
38                                (2lvar (lvar-info lvar)))
39                            (and (not (eq (node-block dest) block))
40                                 2lvar
41                                 (eq (ir2-lvar-kind 2lvar) :unknown)))))
42             (aver (or saw-last (not last-pop)))
43             (pushed lvar))))
44
45       (setf (ir2-block-pushed 2block) (pushed))))
46   (values))
47 \f
48 ;;;; Computation of live UVL sets
49 (defun nle-block-nlx-info (block)
50   (let* ((start-node (block-start-node block))
51          (nlx-ref (ctran-next (node-next start-node)))
52          (nlx-info (constant-value (ref-leaf nlx-ref))))
53     nlx-info))
54 (defun nle-block-entry-block (block)
55   (let* ((nlx-info (nle-block-nlx-info block))
56          (mess-up (cleanup-mess-up (nlx-info-cleanup nlx-info)))
57          (entry-block (node-block mess-up)))
58     entry-block))
59
60 ;;; Add LVARs from LATE to EARLY; use EQ to check whether EARLY has
61 ;;; been changed.
62 (defun merge-uvl-live-sets (early late)
63   (declare (type list early late))
64   (dolist (e late early)
65     (pushnew e early)))
66
67 ;;; Update information on stacks of unknown-values LVARs on the
68 ;;; boundaries of BLOCK. Return true if the start stack has been
69 ;;; changed.
70 ;;;
71 ;;; An LVAR is live at the end iff it is live at some of blocks, which
72 ;;; BLOCK can transfer control to. There are two kind of control
73 ;;; transfers: normal, expressed with BLOCK-SUCC, and NLX.
74 (defun update-uvl-live-sets (block)
75   (declare (type cblock block))
76   (let* ((2block (block-info block))
77          (original-start (ir2-block-start-stack 2block))
78          (end (ir2-block-end-stack 2block))
79          (new-end end))
80     (dolist (succ (block-succ block))
81       (setq new-end (merge-uvl-live-sets new-end
82                                          (ir2-block-start-stack (block-info succ)))))
83     (map-block-nlxes (lambda (nlx-info)
84                        (let* ((nle (nlx-info-target nlx-info))
85                               (nle-start-stack (ir2-block-start-stack
86                                                 (block-info nle)))
87                               (exit-lvar (nlx-info-lvar nlx-info))
88                               (next-stack (if exit-lvar
89                                               (remove exit-lvar nle-start-stack)
90                                               nle-start-stack)))
91                          (setq new-end (merge-uvl-live-sets
92                                         new-end next-stack))))
93                      block
94                      (lambda (dx-cleanup)
95                        (dolist (lvar (cleanup-info dx-cleanup))
96                          (let* ((generator (lvar-use lvar))
97                                 (block (node-block generator))
98                                 (2block (block-info block)))
99                            (aver (eq generator (block-last block)))
100                            ;; DX objects, living in the LVAR, are
101                            ;; alive in the environment, protected by
102                            ;; the CLEANUP. We also cannot move them
103                            ;; (because, in general, we cannot track
104                            ;; all references to them). Therefore,
105                            ;; everything, allocated deeper than a DX
106                            ;; object, should be kept alive until the
107                            ;; object is deallocated.
108                            (setq new-end (merge-uvl-live-sets
109                                           new-end (ir2-block-end-stack 2block)))
110                            (setq new-end (merge-uvl-live-sets
111                                           new-end (ir2-block-pushed 2block)))))))
112
113     (setf (ir2-block-end-stack 2block) new-end)
114
115     (let ((start new-end))
116       (setq start (set-difference start (ir2-block-pushed 2block)))
117       (setq start (merge-uvl-live-sets start (ir2-block-popped 2block)))
118
119       ;; We cannot delete unused UVLs during NLX, so all UVLs live at
120       ;; ENTRY will be actually live at NLE.
121       ;;
122       ;; BUT, UNWIND-PROTECTor is called in the environment, which has
123       ;; nothing in common with the environment of its entry. So we
124       ;; fictively compute its stack from the containing cleanups, but
125       ;; do not propagate additional LVARs from the entry, thus
126       ;; preveting bogus stack cleanings.
127       ;;
128       ;; TODO: Insert a check that no values are discarded in UWP. Or,
129       ;; maybe, we just don't need to create NLX-ENTRY for UWP?
130       (when (and (eq (component-head (block-component block))
131                      (first (block-pred block)))
132                  (not (bind-p (block-start-node block))))
133         (let* ((nlx-info (nle-block-nlx-info block))
134                (cleanup (nlx-info-cleanup nlx-info)))
135           (unless (eq (cleanup-kind cleanup) :unwind-protect)
136             (let* ((entry-block (node-block (cleanup-mess-up cleanup)))
137                    (entry-stack (ir2-block-start-stack (block-info entry-block))))
138               (setq start (merge-uvl-live-sets start entry-stack))))))
139
140       (when *check-consistency*
141         (aver (subsetp original-start start)))
142       (cond ((subsetp start original-start)
143              nil)
144             (t
145              (setf (ir2-block-start-stack 2block) start)
146              t)))))
147
148 \f
149 ;;;; Ordering of live UVL stacks
150
151 ;;; Put UVLs on the start/end stacks of BLOCK in the right order. PRED
152 ;;; is a predecessor of BLOCK with already sorted stacks; because all
153 ;;; UVLs being live at the BLOCK start are live in PRED, we just need
154 ;;; to delete dead UVLs.
155 (defun order-block-uvl-sets (block pred)
156   (let* ((2block (block-info block))
157          (pred-end-stack (ir2-block-end-stack (block-info pred)))
158          (start (ir2-block-start-stack 2block))
159          (start-stack (loop for lvar in pred-end-stack
160                             when (memq lvar start)
161                             collect lvar))
162          (end (ir2-block-end-stack 2block)))
163     (when *check-consistency*
164       (aver (subsetp start start-stack)))
165     (setf (ir2-block-start-stack 2block) start-stack)
166
167     (let* ((last (block-last block))
168            (tailp-lvar (if (node-tail-p last) (node-lvar last)))
169            (end-stack start-stack))
170       (dolist (pop (ir2-block-popped 2block))
171         (aver (eq pop (car end-stack)))
172         (pop end-stack))
173       (dolist (push (ir2-block-pushed 2block))
174         (aver (not (memq push end-stack)))
175         (push push end-stack))
176       (aver (subsetp end end-stack))
177       (when (and tailp-lvar
178                  (eq (ir2-lvar-kind (lvar-info tailp-lvar)) :unknown))
179         (aver (eq tailp-lvar (first end-stack)))
180         (pop end-stack))
181       (setf (ir2-block-end-stack 2block) end-stack))))
182
183 (defun order-uvl-sets (component)
184   (clear-flags component)
185   (loop with head = (component-head component)
186         with repeat-p do
187         (setq repeat-p nil)
188         (do-blocks (block component)
189           (unless (block-flag block)
190             (let ((pred (find-if #'block-flag (block-pred block))))
191               (when (and (eq pred head)
192                          (not (bind-p (block-start-node block))))
193                 (let ((entry (nle-block-entry-block block)))
194                   (setq pred (if (block-flag entry) entry nil))))
195               (cond (pred
196                      (setf (block-flag block) t)
197                      (order-block-uvl-sets block pred))
198                     (t
199                      (setq repeat-p t))))))
200         while repeat-p))
201 \f
202 ;;; This is called when we discover that the stack-top unknown-values
203 ;;; lvar at the end of BLOCK1 is different from that at the start of
204 ;;; BLOCK2 (its successor).
205 ;;;
206 ;;; We insert a call to a funny function in a new cleanup block
207 ;;; introduced between BLOCK1 and BLOCK2. Since control analysis and
208 ;;; LTN have already run, we must do make an IR2 block, then do
209 ;;; ADD-TO-EMIT-ORDER and LTN-ANALYZE-BELATED-BLOCK on the new
210 ;;; block. The new block is inserted after BLOCK1 in the emit order.
211 ;;;
212 ;;; If the control transfer between BLOCK1 and BLOCK2 represents a
213 ;;; tail-recursive return or a non-local exit, then the cleanup code
214 ;;; will never actually be executed. It doesn't seem to be worth the
215 ;;; risk of trying to optimize this, since this rarely happens and
216 ;;; wastes only space.
217 (defun discard-unused-values (block1 block2)
218   (declare (type cblock block1 block2))
219   (collect ((cleanup-code))
220     (labels ((find-popped (before after)
221                ;; Returns (VALUES popped last-popped rest), where
222                ;; BEFORE = (APPEND popped rest) and
223                ;; (EQ (FIRST rest) (FIRST after))
224                (if (null after)
225                    (values before (first (last before)) nil)
226                    (loop with first-preserved = (car after)
227                          for last-popped = nil then maybe-popped
228                          for rest on before
229                          for maybe-popped = (car rest)
230                          while (neq maybe-popped first-preserved)
231                          collect maybe-popped into popped
232                          finally (return (values popped last-popped rest)))))
233              (discard (before-stack after-stack)
234                (cond
235                  ((eq (car before-stack) (car after-stack))
236                   (binding* ((moved-count (mismatch before-stack after-stack)
237                                           :exit-if-null)
238                              ((moved qmoved)
239                               (loop for moved-lvar in before-stack
240                                     repeat moved-count
241                                     collect moved-lvar into moved
242                                     collect `',moved-lvar into qmoved
243                                     finally (return (values moved qmoved))))
244                              (q-last-moved (car (last qmoved)))
245                              ((nil last-nipped rest)
246                               (find-popped (nthcdr moved-count before-stack)
247                                            (nthcdr moved-count after-stack))))
248                     (cleanup-code
249                      `(%nip-values ',last-nipped ,q-last-moved
250                        ,@qmoved))
251                     (discard (nconc moved rest) after-stack)))
252                  (t
253                   (multiple-value-bind (popped last-popped rest)
254                       (find-popped before-stack after-stack)
255                     (declare (ignore popped))
256                     (cleanup-code `(%pop-values ',last-popped))
257                     (discard rest after-stack))))))
258       (discard (ir2-block-end-stack (block-info block1))
259                (ir2-block-start-stack (block-info block2))))
260     (when (cleanup-code)
261       (let* ((block (insert-cleanup-code block1 block2
262                                          (block-start-node block2)
263                                          `(progn ,@(cleanup-code))))
264              (2block (make-ir2-block block)))
265         (setf (block-info block) 2block)
266         (add-to-emit-order 2block (block-info block1))
267         (ltn-analyze-belated-block block))))
268
269   (values))
270 \f
271 ;;;; stack analysis
272
273 ;;; Return a list of all the blocks containing genuine uses of one of
274 ;;; the RECEIVERS (blocks) and DX-LVARS. Exits are excluded, since
275 ;;; they don't drop through to the receiver.
276 (defun find-pushing-blocks (receivers dx-lvars)
277   (declare (list receivers dx-lvars))
278   (collect ((res nil adjoin))
279     (dolist (rec receivers)
280       (dolist (pop (ir2-block-popped (block-info rec)))
281         (do-uses (use pop)
282           (unless (exit-p use)
283             (res (node-block use))))))
284     (dolist (dx-lvar dx-lvars)
285       (do-uses (use dx-lvar)
286         (res (node-block use))))
287     (res)))
288
289 ;;; Analyze the use of unknown-values and DX lvars in COMPONENT,
290 ;;; inserting cleanup code to discard values that are generated but
291 ;;; never received. This phase doesn't need to be run when
292 ;;; Values-Receivers and Dx-Lvars are null, i.e. there are no
293 ;;; unknown-values lvars used across block boundaries and no DX LVARs.
294 (defun stack-analyze (component)
295   (declare (type component component))
296   (let* ((2comp (component-info component))
297          (receivers (ir2-component-values-receivers 2comp))
298          (generators (find-pushing-blocks receivers
299                                           (component-dx-lvars component))))
300
301     (dolist (block generators)
302       (find-pushed-lvars block))
303
304     ;;; Compute sets of live UVLs and DX LVARs
305     (loop for did-something = nil
306           do (do-blocks-backwards (block component)
307                (when (update-uvl-live-sets block)
308                  (setq did-something t)))
309           while did-something)
310
311     (order-uvl-sets component)
312
313     (do-blocks (block component)
314       (let ((top (ir2-block-end-stack (block-info block))))
315         (dolist (succ (block-succ block))
316           (when (and (block-start succ)
317                      (not (eq (ir2-block-start-stack (block-info succ))
318                               top)))
319             (discard-unused-values block succ))))))
320
321   (values))