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