0.7.12.16:
[sbcl.git] / src / compiler / pack.lisp
1 ;;;; This file contains the implementation-independent code for Pack
2 ;;;; phase in the compiler. Pack is responsible for assigning TNs to
3 ;;;; storage allocations or "register allocation".
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15
16 ;;; for debugging: some parameters controlling which optimizations we
17 ;;; attempt
18 (defvar *pack-assign-costs* t)
19 (defvar *pack-optimize-saves* t)
20 ;;; FIXME: Perhaps SB-FLUID should be renamed to SB-TWEAK and these
21 ;;; should be made conditional on SB-TWEAK.
22
23 (declaim (ftype (function (component) index) ir2-block-count))
24 \f
25 ;;;; conflict determination
26
27 ;;; Return true if the element at the specified offset in SB has a
28 ;;; conflict with TN:
29 ;;; -- If a component-live TN (:COMPONENT kind), then iterate over
30 ;;;    all the blocks. If the element at OFFSET is used anywhere in
31 ;;;    any of the component's blocks (always-live /= 0), then there
32 ;;;    is a conflict.
33 ;;; -- If TN is global (Confs true), then iterate over the blocks TN
34 ;;;    is live in (using TN-GLOBAL-CONFLICTS). If the TN is live
35 ;;;    everywhere in the block (:LIVE), then there is a conflict
36 ;;;    if the element at offset is used anywhere in the block
37 ;;;    (Always-Live /= 0). Otherwise, we use the local TN number for
38 ;;;    TN in block to find whether TN has a conflict at Offset in
39 ;;;    that block.
40 ;;; -- If TN is local, then we just check for a conflict in the block
41 ;;;    it is local to.
42 (defun offset-conflicts-in-sb (tn sb offset)
43   (declare (type tn tn) (type finite-sb sb) (type index offset))
44   (let ((confs (tn-global-conflicts tn))
45         (kind (tn-kind tn)))
46     (cond
47      ((eq kind :component)
48       (let ((loc-live (svref (finite-sb-always-live sb) offset)))
49         (dotimes (i (ir2-block-count *component-being-compiled*) nil)
50           (when (/= (sbit loc-live i) 0)
51             (return t)))))
52      (confs
53       (let ((loc-confs (svref (finite-sb-conflicts sb) offset))
54             (loc-live (svref (finite-sb-always-live sb) offset)))
55         (do ((conf confs (global-conflicts-next-tnwise conf)))
56             ((null conf)
57              nil)
58           (let* ((block (global-conflicts-block conf))
59                  (num (ir2-block-number block)))
60             (if (eq (global-conflicts-kind conf) :live)
61                 (when (/= (sbit loc-live num) 0)
62                   (return t))
63                 (when (/= (sbit (svref loc-confs num)
64                                 (global-conflicts-number conf))
65                           0)
66                   (return t)))))))
67      (t
68       (/= (sbit (svref (svref (finite-sb-conflicts sb) offset)
69                        (ir2-block-number (tn-local tn)))
70                 (tn-local-number tn))
71           0)))))
72
73 ;;; Return true if TN has a conflict in SC at the specified offset.
74 (defun conflicts-in-sc (tn sc offset)
75   (declare (type tn tn) (type sc sc) (type index offset))
76   (let ((sb (sc-sb sc)))
77     (dotimes (i (sc-element-size sc) nil)
78       (when (offset-conflicts-in-sb tn sb (+ offset i))
79         (return t)))))
80
81 ;;; Add TN's conflicts into the conflicts for the location at OFFSET
82 ;;; in SC. We iterate over each location in TN, adding to the
83 ;;; conflicts for that location:
84 ;;; -- If TN is a :COMPONENT TN, then iterate over all the blocks,
85 ;;;    setting all of the local conflict bits and the always-live bit.
86 ;;;    This records a conflict with any TN that has a LTN number in
87 ;;;    the block, as well as with :ALWAYS-LIVE and :ENVIRONMENT TNs.
88 ;;; -- If TN is global, then iterate over the blocks TN is live in. In
89 ;;;    addition to setting the always-live bit to represent the conflict
90 ;;;    with TNs live throughout the block, we also set bits in the
91 ;;;    local conflicts. If TN is :ALWAYS-LIVE in the block, we set all
92 ;;;    the bits, otherwise we OR in the local conflict bits.
93 ;;; -- If the TN is local, then we just do the block it is local to,
94 ;;;    setting always-live and OR'ing in the local conflicts.
95 (defun add-location-conflicts (tn sc offset)
96   (declare (type tn tn) (type sc sc) (type index offset))
97   (let ((confs (tn-global-conflicts tn))
98         (sb (sc-sb sc))
99         (kind (tn-kind tn)))
100     (dotimes (i (sc-element-size sc))
101       (declare (type index i))
102       (let* ((this-offset (+ offset i))
103              (loc-confs (svref (finite-sb-conflicts sb) this-offset))
104              (loc-live (svref (finite-sb-always-live sb) this-offset)))
105         (cond
106          ((eq kind :component)
107           (dotimes (num (ir2-block-count *component-being-compiled*))
108             (declare (type index num))
109             (setf (sbit loc-live num) 1)
110             (set-bit-vector (svref loc-confs num))))
111          (confs
112           (do ((conf confs (global-conflicts-next-tnwise conf)))
113               ((null conf))
114             (let* ((block (global-conflicts-block conf))
115                    (num (ir2-block-number block))
116                    (local-confs (svref loc-confs num)))
117               (declare (type local-tn-bit-vector local-confs))
118               (setf (sbit loc-live num) 1)
119               (if (eq (global-conflicts-kind conf) :live)
120                   (set-bit-vector local-confs)
121                   (bit-ior local-confs (global-conflicts-conflicts conf) t)))))
122          (t
123           (let ((num (ir2-block-number (tn-local tn))))
124             (setf (sbit loc-live num) 1)
125             (bit-ior (the local-tn-bit-vector (svref loc-confs num))
126                      (tn-local-conflicts tn) t))))))))
127
128 ;;; Return the total number of IR2-BLOCKs in COMPONENT.
129 (defun ir2-block-count (component)
130   (declare (type component component))
131   (do ((2block (block-info (block-next (component-head component)))
132                (ir2-block-next 2block)))
133       ((null 2block)
134        (error "What?  No ir2 blocks have a non-nil number?"))
135     (when (ir2-block-number 2block)
136       (return (1+ (ir2-block-number 2block))))))
137
138 ;;; Ensure that the conflicts vectors for each :FINITE SB are large
139 ;;; enough for the number of blocks allocated. Also clear any old
140 ;;; conflicts and reset the current size to the initial size.
141 (defun init-sb-vectors (component)
142   (let ((nblocks (ir2-block-count component)))
143     (dolist (sb *backend-sb-list*)
144       (unless (eq (sb-kind sb) :non-packed)
145         (let* ((conflicts (finite-sb-conflicts sb))
146                (always-live (finite-sb-always-live sb))
147                (max-locs (length conflicts))
148                (last-count (finite-sb-last-block-count sb)))
149           (unless (zerop max-locs)
150             (let ((current-size (length (the simple-vector
151                                              (svref conflicts 0)))))
152               (cond
153                ((> nblocks current-size)
154                 (let ((new-size (max nblocks (* current-size 2))))
155                   (declare (type index new-size))
156                   (dotimes (i max-locs)
157                     (declare (type index i))
158                     (let ((new-vec (make-array new-size)))
159                       (let ((old (svref conflicts i)))
160                         (declare (simple-vector old))
161                         (dotimes (j current-size)
162                           (declare (type index j))
163                           (setf (svref new-vec j)
164                                 (clear-bit-vector (svref old j)))))
165
166                       (do ((j current-size (1+ j)))
167                           ((= j new-size))
168                         (declare (type index j))
169                         (setf (svref new-vec j)
170                               (make-array local-tn-limit :element-type 'bit
171                                           :initial-element 0)))
172                       (setf (svref conflicts i) new-vec))
173                     (setf (svref always-live i)
174                           (make-array new-size :element-type 'bit
175                                       :initial-element 0)))))
176                (t
177                 (dotimes (i (finite-sb-current-size sb))
178                   (declare (type index i))
179                   (let ((conf (svref conflicts i)))
180                     (declare (simple-vector conf))
181                     (dotimes (j last-count)
182                       (declare (type index j))
183                       (clear-bit-vector (svref conf j))))
184                   (clear-bit-vector (svref always-live i)))))))
185
186           (setf (finite-sb-last-block-count sb) nblocks)
187           (setf (finite-sb-current-size sb) (sb-size sb))
188           (setf (finite-sb-last-offset sb) 0))))))
189
190 ;;; Expand the :UNBOUNDED SB backing SC by either the initial size or
191 ;;; the SC element size, whichever is larger. If NEEDED-SIZE is
192 ;;; larger, then use that size.
193 (defun grow-sc (sc &optional (needed-size 0))
194   (declare (type sc sc) (type index needed-size))
195   (let* ((sb (sc-sb sc))
196          (size (finite-sb-current-size sb))
197          (align-mask (1- (sc-alignment sc)))
198          (inc (max (sb-size sb)
199                    (+ (sc-element-size sc)
200                       (- (logandc2 (+ size align-mask) align-mask)
201                          size))
202                    (- needed-size size)))
203          (new-size (+ size inc))
204          (conflicts (finite-sb-conflicts sb))
205          (block-size (if (zerop (length conflicts))
206                          (ir2-block-count *component-being-compiled*)
207                          (length (the simple-vector (svref conflicts 0))))))
208     (declare (type index inc new-size))
209     (aver (eq (sb-kind sb) :unbounded))
210
211     (when (> new-size (length conflicts))
212       (let ((new-conf (make-array new-size)))
213         (replace new-conf conflicts)
214         (do ((i size (1+ i)))
215             ((= i new-size))
216           (declare (type index i))
217           (let ((loc-confs (make-array block-size)))
218             (dotimes (j block-size)
219               (setf (svref loc-confs j)
220                     (make-array local-tn-limit
221                                 :initial-element 0
222                                 :element-type 'bit)))
223             (setf (svref new-conf i) loc-confs)))
224         (setf (finite-sb-conflicts sb) new-conf))
225
226       (let ((new-live (make-array new-size)))
227         (replace new-live (finite-sb-always-live sb))
228         (do ((i size (1+ i)))
229             ((= i new-size))
230           (setf (svref new-live i)
231                 (make-array block-size
232                             :initial-element 0
233                             :element-type 'bit)))
234         (setf (finite-sb-always-live sb) new-live))
235
236       (let ((new-tns (make-array new-size :initial-element nil)))
237         (replace new-tns (finite-sb-live-tns sb))
238         (fill (finite-sb-live-tns sb) nil)
239         (setf (finite-sb-live-tns sb) new-tns)))
240
241     (setf (finite-sb-current-size sb) new-size))
242   (values))
243
244 ;;; This variable is true whenever we are in pack (and thus the per-SB
245 ;;; conflicts information is in use.)
246 (defvar *in-pack* nil)
247
248 ;;; In order to prevent the conflict data structures from growing
249 ;;; arbitrarily large, we clear them whenever a GC happens and we
250 ;;; aren't currently in pack. We revert to the initial number of
251 ;;; locations and 0 blocks.
252 (defun pack-before-gc-hook ()
253   (unless *in-pack*
254     (dolist (sb *backend-sb-list*)
255       (unless (eq (sb-kind sb) :non-packed)
256         (let ((size (sb-size sb)))
257           (fill (finite-sb-always-live sb) nil)
258           (setf (finite-sb-always-live sb)
259                 (make-array size
260                             :initial-element
261                             #-sb-xc #*
262                             ;; The cross-compiler isn't very good at
263                             ;; dumping specialized arrays, so we delay
264                             ;; construction of this SIMPLE-BIT-VECTOR
265                             ;; until runtime.
266                             #+sb-xc (make-array 0 :element-type 'bit)))
267
268           (fill (finite-sb-conflicts sb) nil)
269           (setf (finite-sb-conflicts sb)
270                 (make-array size :initial-element '#()))
271
272           (fill (finite-sb-live-tns sb) nil)
273           (setf (finite-sb-live-tns sb)
274                 (make-array size :initial-element nil))))))
275   (values))
276
277 (pushnew 'pack-before-gc-hook sb!ext:*before-gc-hooks*)
278 \f
279 ;;;; internal errors
280
281 ;;; Give someone a hard time because there isn't any load function
282 ;;; defined to move from SRC to DEST.
283 (defun no-load-fun-error (src dest)
284   (let* ((src-sc (tn-sc src))
285          (src-name (sc-name src-sc))
286          (dest-sc (tn-sc dest))
287          (dest-name (sc-name dest-sc)))
288     (cond ((eq (sb-kind (sc-sb src-sc)) :non-packed)
289            (unless (member src-sc (sc-constant-scs dest-sc))
290              (error "loading from an invalid constant SC?~@
291                      VM definition inconsistent, try recompiling."))
292            (error "no load function defined to load SC ~S ~
293                    from its constant SC ~S"
294                   dest-name src-name))
295           ((member src-sc (sc-alternate-scs dest-sc))
296            (error "no load function defined to load SC ~S from its ~
297                    alternate SC ~S"
298                   dest-name src-name))
299           ((member dest-sc (sc-alternate-scs src-sc))
300            (error "no load function defined to save SC ~S in its ~
301                    alternate SC ~S"
302                   src-name dest-name))
303           (t
304            ;; FIXME: "VM definition is inconsistent" shouldn't be a
305            ;; possibility in SBCL.
306            (error "loading to/from SCs that aren't alternates?~@
307                    VM definition is inconsistent, try recompiling.")))))
308
309 ;;; Called when we failed to pack TN. If RESTRICTED is true, then we
310 ;;; are restricted to pack TN in its SC.
311 (defun failed-to-pack-error (tn restricted)
312   (declare (type tn tn))
313   (let* ((sc (tn-sc tn))
314          (scs (cons sc (sc-alternate-scs sc))))
315     (cond
316      (restricted
317       (error "failed to pack restricted TN ~S in its SC ~S"
318              tn (sc-name sc)))
319      (t
320       (aver (not (find :unbounded scs
321                        :key (lambda (x) (sb-kind (sc-sb x))))))
322       (let ((ptype (tn-primitive-type tn)))
323         (cond
324          (ptype
325           (aver (member (sc-number sc) (primitive-type-scs ptype)))
326           (error "SC ~S doesn't have any :UNBOUNDED alternate SCs, but is~@
327                   a SC for primitive-type ~S."
328                  (sc-name sc) (primitive-type-name ptype)))
329          (t
330           (error "SC ~S doesn't have any :UNBOUNDED alternate SCs."
331                  (sc-name sc)))))))))
332
333 ;;; Return a list of format arguments describing how TN is used in
334 ;;; OP's VOP.
335 (defun describe-tn-use (loc tn op)
336   (let* ((vop (tn-ref-vop op))
337          (args (vop-args vop))
338          (results (vop-results vop))
339          (name (with-output-to-string (stream)
340                  (print-tn-guts tn stream)))
341          (2comp (component-info *component-being-compiled*))
342          temp)
343     (cond
344      ((setq temp (position-in #'tn-ref-across tn args :key #'tn-ref-tn))
345       `("~2D: ~A (~:R argument)" ,loc ,name ,(1+ temp)))
346      ((setq temp (position-in #'tn-ref-across tn results :key #'tn-ref-tn))
347       `("~2D: ~A (~:R result)" ,loc ,name ,(1+ temp)))
348      ((setq temp (position-in #'tn-ref-across tn args :key #'tn-ref-load-tn))
349       `("~2D: ~A (~:R argument load TN)" ,loc ,name ,(1+ temp)))
350      ((setq temp (position-in #'tn-ref-across tn results :key
351                               #'tn-ref-load-tn))
352       `("~2D: ~A (~:R result load TN)" ,loc ,name ,(1+ temp)))
353      ((setq temp (position-in #'tn-ref-across tn (vop-temps vop)
354                               :key #'tn-ref-tn))
355       `("~2D: ~A (temporary ~A)" ,loc ,name
356         ,(operand-parse-name (elt (vop-parse-temps
357                                    (vop-parse-or-lose
358                                     (vop-info-name  (vop-info vop))))
359                                   temp))))
360      ((eq (tn-kind tn) :component)
361       `("~2D: ~A (component live)" ,loc ,name))
362      ((position-in #'tn-next tn (ir2-component-wired-tns 2comp))
363       `("~2D: ~A (wired)" ,loc ,name))
364      ((position-in #'tn-next tn (ir2-component-restricted-tns 2comp))
365       `("~2D: ~A (restricted)" ,loc ,name))
366      (t
367       `("~2D: not referenced?" ,loc)))))
368
369 ;;; If load TN packing fails, try to give a helpful error message. We
370 ;;; find a TN in each location that conflicts, and print it.
371 (defun failed-to-pack-load-tn-error (scs op)
372   (declare (list scs) (type tn-ref op))
373   (collect ((used)
374             (unused))
375     (dolist (sc scs)
376       (let* ((sb (sc-sb sc))
377              (confs (finite-sb-live-tns sb)))
378         (aver (eq (sb-kind sb) :finite))
379         (dolist (el (sc-locations sc))
380           (declare (type index el))
381           (let ((conf (load-tn-conflicts-in-sc op sc el t)))
382             (if conf
383                 (used (describe-tn-use el conf op))
384                 (do ((i el (1+ i))
385                      (end (+ el (sc-element-size sc))))
386                     ((= i end)
387                      (unused el))
388                   (declare (type index i end))
389                   (let ((victim (svref confs i)))
390                     (when victim
391                       (used (describe-tn-use el victim op))
392                       (return t)))))))))
393
394     (multiple-value-bind (arg-p n more-p costs load-scs incon)
395         (get-operand-info op)
396       (declare (ignore costs load-scs))
397         (aver (not more-p))
398         (error "unable to pack a Load-TN in SC ~{~A~#[~^~;, or ~:;,~]~} ~
399                 for the ~:R ~:[result~;argument~] to~@
400                 the ~S VOP,~@
401                 ~:[since all SC elements are in use:~:{~%~@?~}~%~;~
402                 ~:*but these SC elements are not in use:~%  ~S~%Bug?~*~]~
403                 ~:[~;~@
404                 Current cost info inconsistent with that in effect at compile ~
405                 time. Recompile.~%Compilation order may be incorrect.~]"
406                (mapcar #'sc-name scs)
407                n arg-p
408                (vop-info-name (vop-info (tn-ref-vop op)))
409                (unused) (used)
410                incon))))
411
412 ;;; This is called when none of the SCs that we can load OP into are
413 ;;; allowed by OP's primitive-type.
414 (defun no-load-scs-allowed-by-primitive-type-error (ref)
415   (declare (type tn-ref ref))
416   (let* ((tn (tn-ref-tn ref))
417          (ptype (tn-primitive-type tn)))
418     (multiple-value-bind (arg-p pos more-p costs load-scs incon)
419         (get-operand-info ref)
420       (declare (ignore costs))
421       (aver (not more-p))
422       (error "~S is not valid as the ~:R ~:[result~;argument~] to VOP:~
423               ~%  ~S,~@
424               since the TN's primitive type ~S doesn't allow any of the SCs~@
425               allowed by the operand restriction:~%  ~S~
426               ~:[~;~@
427               Current cost info inconsistent with that in effect at compile ~
428               time. Recompile.~%Compilation order may be incorrect.~]"
429              tn pos arg-p
430              (template-name (vop-info (tn-ref-vop ref)))
431              (primitive-type-name ptype)
432              (mapcar #'sc-name (listify-restrictions load-scs))
433              incon))))
434 \f
435 ;;;; register saving
436
437 ;;; Do stuff to note that TN is spilled at VOP for the debugger's benefit.
438 (defun note-spilled-tn (tn vop)
439   (when (and (tn-leaf tn) (vop-save-set vop))
440     (let ((2comp (component-info *component-being-compiled*)))
441       (setf (gethash tn (ir2-component-spilled-tns 2comp)) t)
442       (pushnew tn (gethash vop (ir2-component-spilled-vops 2comp)))))
443   (values))
444
445 ;;; Make a save TN for TN, pack it, and return it. We copy various
446 ;;; conflict information from the TN so that pack does the right
447 ;;; thing.
448 (defun pack-save-tn (tn)
449   (declare (type tn tn))
450   (let ((res (make-tn 0 :save nil nil)))
451     (dolist (alt (sc-alternate-scs (tn-sc tn))
452                  (error "no unbounded alternate for SC ~S"
453                         (sc-name (tn-sc tn))))
454       (when (eq (sb-kind (sc-sb alt)) :unbounded)
455         (setf (tn-save-tn tn) res)
456         (setf (tn-save-tn res) tn)
457         (setf (tn-sc res) alt)
458         (pack-tn res t)
459         (return res)))))
460
461 ;;; Find the load function for moving from SRC to DEST and emit a
462 ;;; MOVE-OPERAND VOP with that function as its info arg.
463 (defun emit-operand-load (node block src dest before)
464   (declare (type node node) (type ir2-block block)
465            (type tn src dest) (type (or vop null) before))
466   (emit-load-template node block
467                       (template-or-lose 'move-operand)
468                       src dest
469                       (list (or (svref (sc-move-funs (tn-sc dest))
470                                        (sc-number (tn-sc src)))
471                                 (no-load-fun-error src dest)))
472                       before)
473   (values))
474
475 ;;; Find the preceding use of the VOP NAME in the emit order, starting
476 ;;; with VOP. We must find the VOP in the same IR1 block.
477 (defun reverse-find-vop (name vop)
478   (do* ((block (vop-block vop) (ir2-block-prev block))
479         (last vop (ir2-block-last-vop block)))
480        (nil)
481     (aver (eq (ir2-block-block block) (ir2-block-block (vop-block vop))))
482     (do ((current last (vop-prev current)))
483         ((null current))
484       (when (eq (vop-info-name (vop-info current)) name)
485         (return-from reverse-find-vop current)))))
486
487 ;;; For TNs that have other than one writer, we save the TN before
488 ;;; each call. If a local call (MOVE-ARGS is :LOCAL-CALL), then we
489 ;;; scan back for the ALLOCATE-FRAME VOP, and emit the save there.
490 ;;; This is necessary because in a self-recursive local call, the
491 ;;; registers holding the current arguments may get trashed by setting
492 ;;; up the call arguments. The ALLOCATE-FRAME VOP marks a place at
493 ;;; which the values are known to be good.
494 (defun save-complex-writer-tn (tn vop)
495   (let ((save (or (tn-save-tn tn)
496                   (pack-save-tn tn)))
497         (node (vop-node vop))
498         (block (vop-block vop))
499         (next (vop-next vop)))
500     (when (eq (tn-kind save) :specified-save)
501       (setf (tn-kind save) :save))
502     (aver (eq (tn-kind save) :save))
503     (emit-operand-load node block tn save
504                        (if (eq (vop-info-move-args (vop-info vop))
505                                :local-call)
506                            (reverse-find-vop 'allocate-frame vop)
507                            vop))
508     (emit-operand-load node block save tn next)))
509
510 ;;; Return a VOP after which is an OK place to save the value of TN.
511 ;;; For correctness, it is only required that this location be after
512 ;;; any possible write and before any possible restore location.
513 ;;;
514 ;;; In practice, we return the unique writer VOP, but give up if the
515 ;;; TN is ever read by a VOP with MOVE-ARGS :LOCAL-CALL. This prevents
516 ;;; us from being confused by non-tail local calls.
517 ;;;
518 ;;; When looking for writes, we have to ignore uses of MOVE-OPERAND,
519 ;;; since they will correspond to restores that we have already done.
520 (defun find-single-writer (tn)
521   (declare (type tn tn))
522   (do ((write (tn-writes tn) (tn-ref-next write))
523        (res nil))
524       ((null write)
525        (when (and res
526                   (do ((read (tn-reads tn) (tn-ref-next read)))
527                       ((not read) t)
528                     (when (eq (vop-info-move-args
529                                (vop-info
530                                 (tn-ref-vop read)))
531                               :local-call)
532                       (return nil))))
533          (tn-ref-vop res)))
534
535     (unless (eq (vop-info-name (vop-info (tn-ref-vop write)))
536                 'move-operand)
537       (when res (return nil))
538       (setq res write))))
539
540 ;;; Try to save TN at a single location. If we succeed, return T,
541 ;;; otherwise NIL.
542 (defun save-single-writer-tn (tn)
543   (declare (type tn tn))
544   (let* ((old-save (tn-save-tn tn))
545          (save (or old-save (pack-save-tn tn)))
546          (writer (find-single-writer tn)))
547     (when (and writer
548                (or (not old-save)
549                    (eq (tn-kind old-save) :specified-save)))
550       (emit-operand-load (vop-node writer) (vop-block writer)
551                          tn save (vop-next writer))
552       (setf (tn-kind save) :save-once)
553       t)))
554
555 ;;; Restore a TN with a :SAVE-ONCE save TN.
556 (defun restore-single-writer-tn (tn vop)
557   (declare (type tn) (type vop vop))
558   (let ((save (tn-save-tn tn)))
559     (aver (eq (tn-kind save) :save-once))
560     (emit-operand-load (vop-node vop) (vop-block vop) save tn (vop-next vop)))
561   (values))
562
563 ;;; Save a single TN that needs to be saved, choosing save-once if
564 ;;; appropriate. This is also called by SPILL-AND-PACK-LOAD-TN.
565 (defun basic-save-tn (tn vop)
566   (declare (type tn tn) (type vop vop))
567   (let ((save (tn-save-tn tn)))
568     (cond ((and save (eq (tn-kind save) :save-once))
569            (restore-single-writer-tn tn vop))
570           ((save-single-writer-tn tn)
571            (restore-single-writer-tn tn vop))
572           (t
573            (save-complex-writer-tn tn vop))))
574   (values))
575
576 ;;; Scan over the VOPs in BLOCK, emiting saving code for TNs noted in
577 ;;; the codegen info that are packed into saved SCs.
578 (defun emit-saves (block)
579   (declare (type ir2-block block))
580   (do ((vop (ir2-block-start-vop block) (vop-next vop)))
581       ((null vop))
582     (when (eq (vop-info-save-p (vop-info vop)) t)
583       (do-live-tns (tn (vop-save-set vop) block)
584         (when (and (sc-save-p (tn-sc tn))
585                    (not (eq (tn-kind tn) :component)))
586           (basic-save-tn tn vop)))))
587
588   (values))
589 \f
590 ;;;; optimized saving
591
592 ;;; Save TN if it isn't a single-writer TN that has already been
593 ;;; saved. If multi-write, we insert the save BEFORE the specified
594 ;;; VOP. CONTEXT is a VOP used to tell which node/block to use for the
595 ;;; new VOP.
596 (defun save-if-necessary (tn before context)
597   (declare (type tn tn) (type (or vop null) before) (type vop context))
598   (let ((save (tn-save-tn tn)))
599     (when (eq (tn-kind save) :specified-save)
600       (setf (tn-kind save) :save))
601     (aver (member (tn-kind save) '(:save :save-once)))
602     (unless (eq (tn-kind save) :save-once)
603       (or (save-single-writer-tn tn)
604           (emit-operand-load (vop-node context) (vop-block context)
605                              tn save before))))
606   (values))
607
608 ;;; Load the TN from its save location, allocating one if necessary.
609 ;;; The load is inserted BEFORE the specifier VOP. CONTEXT is a VOP
610 ;;; used to tell which node/block to use for the new VOP.
611 (defun restore-tn (tn before context)
612   (declare (type tn tn) (type (or vop null) before) (type vop context))
613   (let ((save (or (tn-save-tn tn) (pack-save-tn tn))))
614     (emit-operand-load (vop-node context) (vop-block context)
615                        save tn before))
616   (values))
617
618 (eval-when (:compile-toplevel :execute)
619
620 ;;; Do stuff to note a read of TN, for OPTIMIZED-EMIT-SAVES-BLOCK.
621 (defmacro save-note-read (tn)
622   `(let* ((tn ,tn)
623           (num (tn-number tn)))
624      (when (and (sc-save-p (tn-sc tn))
625                 (zerop (sbit restores num))
626                 (not (eq (tn-kind tn) :component)))
627        (setf (sbit restores num) 1)
628        (push tn restores-list))))
629
630 ) ; EVAL-WHEN
631
632 ;;; Start scanning backward at the end of BLOCK, looking which TNs are
633 ;;; live and looking for places where we have to save. We manipulate
634 ;;; two sets: SAVES and RESTORES.
635 ;;;
636 ;;; SAVES is a set of all the TNs that have to be saved because they
637 ;;; are restored after some call. We normally delay saving until the
638 ;;; beginning of the block, but we must save immediately if we see a
639 ;;; write of the saved TN. We also immediately save all TNs and exit
640 ;;; when we see a NOTE-ENVIRONMENT-START VOP, since saves can't be
641 ;;; done before the environment is properly initialized.
642 ;;;
643 ;;; RESTORES is a set of all the TNs read (and not written) between
644 ;;; here and the next call, i.e. the set of TNs that must be restored
645 ;;; when we reach the next (earlier) call VOP. Unlike SAVES, this set
646 ;;; is cleared when we do the restoring after a call. Any TNs that
647 ;;; were in RESTORES are moved into SAVES to ensure that they are
648 ;;; saved at some point.
649 ;;;
650 ;;; SAVES and RESTORES are represented using both a list and a
651 ;;; bit-vector so that we can quickly iterate and test for membership.
652 ;;; The incoming SAVES and RESTORES args are used for computing these
653 ;;; sets (the initial contents are ignored.)
654 ;;;
655 ;;; When we hit a VOP with :COMPUTE-ONLY SAVE-P (an internal error
656 ;;; location), we pretend that all live TNs were read, unless (= speed
657 ;;; 3), in which case we mark all the TNs that are live but not
658 ;;; restored as spilled.
659 (defun optimized-emit-saves-block (block saves restores)
660   (declare (type ir2-block block) (type simple-bit-vector saves restores))
661   (let ((1block (ir2-block-block block))
662         (saves-list ())
663         (restores-list ())
664         (skipping nil))
665     (declare (list saves-list restores-list))
666     (clear-bit-vector saves)
667     (clear-bit-vector restores)
668     (do-live-tns (tn (ir2-block-live-in block) block)
669       (when (and (sc-save-p (tn-sc tn))
670                  (not (eq (tn-kind tn) :component)))
671         (let ((num (tn-number tn)))
672           (setf (sbit restores num) 1)
673           (push tn restores-list))))
674
675     (do ((block block (ir2-block-prev block))
676          (prev nil block))
677         ((not (eq (ir2-block-block block) 1block))
678          (aver (not skipping))
679          (dolist (save saves-list)
680            (let ((start (ir2-block-start-vop prev)))
681              (save-if-necessary save start start)))
682          prev)
683       (do ((vop (ir2-block-last-vop block) (vop-prev vop)))
684           ((null vop))
685         (let ((info (vop-info vop)))
686           (case (vop-info-name info)
687             (allocate-frame
688              (aver skipping)
689              (setq skipping nil))
690             (note-environment-start
691              (aver (not skipping))
692              (dolist (save saves-list)
693                (save-if-necessary save (vop-next vop) vop))
694              (return-from optimized-emit-saves-block block)))
695
696           (unless skipping
697             (do ((write (vop-results vop) (tn-ref-across write)))
698                 ((null write))
699               (let* ((tn (tn-ref-tn write))
700                      (num (tn-number tn)))
701                 (unless (zerop (sbit restores num))
702                   (setf (sbit restores num) 0)
703                   (setq restores-list
704                         (delete tn restores-list :test #'eq)))
705                 (unless (zerop (sbit saves num))
706                   (setf (sbit saves num) 0)
707                   (save-if-necessary tn (vop-next vop) vop)
708                   (setq saves-list
709                         (delete tn saves-list :test #'eq))))))
710
711           (macrolet (;; Do stuff to note a read of TN, for
712                      ;; OPTIMIZED-EMIT-SAVES-BLOCK.
713                      (save-note-read (tn)
714                        `(let* ((tn ,tn)
715                                (num (tn-number tn)))
716                           (when (and (sc-save-p (tn-sc tn))
717                                      (zerop (sbit restores num))
718                                      (not (eq (tn-kind tn) :component)))
719                           (setf (sbit restores num) 1)
720                           (push tn restores-list)))))
721
722             (case (vop-info-save-p info)
723               ((t)
724                (dolist (tn restores-list)
725                  (restore-tn tn (vop-next vop) vop)
726                  (let ((num (tn-number tn)))
727                    (when (zerop (sbit saves num))
728                      (push tn saves-list)
729                      (setf (sbit saves num) 1))))
730                (setq restores-list nil)
731                (clear-bit-vector restores))
732               (:compute-only
733                (cond ((policy (vop-node vop) (= speed 3))
734                       (do-live-tns (tn (vop-save-set vop) block)
735                         (when (zerop (sbit restores (tn-number tn)))
736                           (note-spilled-tn tn vop))))
737                      (t
738                       (do-live-tns (tn (vop-save-set vop) block)
739                         (save-note-read tn))))))
740
741             (if (eq (vop-info-move-args info) :local-call)
742                 (setq skipping t)
743                 (do ((read (vop-args vop) (tn-ref-across read)))
744                     ((null read))
745                   (save-note-read (tn-ref-tn read))))))))))
746
747 ;;; This is like EMIT-SAVES, only different. We avoid redundant saving
748 ;;; within the block, and don't restore values that aren't used before
749 ;;; the next call. This function is just the top level loop over the
750 ;;; blocks in the component, which locates blocks that need saving
751 ;;; done.
752 (defun optimized-emit-saves (component)
753   (declare (type component component))
754   (let* ((gtn-count (1+ (ir2-component-global-tn-counter
755                          (component-info component))))
756          (saves (make-array gtn-count :element-type 'bit))
757          (restores (make-array gtn-count :element-type 'bit))
758          (block (ir2-block-prev (block-info (component-tail component))))
759          (head (block-info (component-head component))))
760     (loop
761       (when (eq block head) (return))
762       (when (do ((vop (ir2-block-start-vop block) (vop-next vop)))
763                 ((null vop) nil)
764               (when (eq (vop-info-save-p (vop-info vop)) t)
765                 (return t)))
766         (setq block (optimized-emit-saves-block block saves restores)))
767       (setq block (ir2-block-prev block)))))
768
769 ;;; Iterate over the normal TNs, finding the cost of packing on the
770 ;;; stack in units of the number of references. We count all
771 ;;; references as +1, and subtract out REGISTER-SAVE-PENALTY for each
772 ;;; place where we would have to save a register.
773 (defun assign-tn-costs (component)
774   (do-ir2-blocks (block component)
775     (do ((vop (ir2-block-start-vop block) (vop-next vop)))
776         ((null vop))
777       (when (eq (vop-info-save-p (vop-info vop)) t)
778         (do-live-tns (tn (vop-save-set vop) block)
779           (decf (tn-cost tn) *backend-register-save-penalty*)))))
780
781   (do ((tn (ir2-component-normal-tns (component-info component))
782            (tn-next tn)))
783       ((null tn))
784     (let ((cost (tn-cost tn)))
785       (declare (fixnum cost))
786       (do ((ref (tn-reads tn) (tn-ref-next ref)))
787           ((null ref))
788         (incf cost))
789       (do ((ref (tn-writes tn) (tn-ref-next ref)))
790           ((null ref))
791         (incf cost))
792       (setf (tn-cost tn) cost))))
793 \f
794 ;;;; load TN packing
795
796 ;;; These variables indicate the last location at which we computed
797 ;;; the Live-TNs. They hold the BLOCK and VOP values that were passed
798 ;;; to COMPUTE-LIVE-TNS.
799 (defvar *live-block*)
800 (defvar *live-vop*)
801
802 ;;; If we unpack some TNs, then we mark all affected blocks by
803 ;;; sticking them in this hash-table. This is initially null. We
804 ;;; create the hashtable if we do any unpacking.
805 (defvar *repack-blocks*)
806 (declaim (type (or hash-table null) *repack-blocks*))
807
808 ;;; Set the LIVE-TNS vectors in all :FINITE SBs to represent the TNs
809 ;;; live at the end of BLOCK.
810 (defun init-live-tns (block)
811   (dolist (sb *backend-sb-list*)
812     (when (eq (sb-kind sb) :finite)
813       (fill (finite-sb-live-tns sb) nil)))
814
815   (do-live-tns (tn (ir2-block-live-in block) block)
816     (let* ((sc (tn-sc tn))
817            (sb (sc-sb sc)))
818       (when (eq (sb-kind sb) :finite)
819         (do ((offset (tn-offset tn) (1+ offset))
820              (end (+ (tn-offset tn) (sc-element-size sc))))
821             ((= offset end))
822           (declare (type index offset end))
823           (setf (svref (finite-sb-live-tns sb) offset) tn)))))
824
825   (setq *live-block* block)
826   (setq *live-vop* (ir2-block-last-vop block))
827
828   (values))
829
830 ;;; Set the LIVE-TNs in :FINITE SBs to represent the TNs live
831 ;;; immediately after the evaluation of VOP in BLOCK, excluding
832 ;;; results of the VOP. If VOP is null, then compute the live TNs at
833 ;;; the beginning of the block. Sequential calls on the same block
834 ;;; must be in reverse VOP order.
835 (defun compute-live-tns (block vop)
836   (declare (type ir2-block block) (type vop vop))
837   (unless (eq block *live-block*)
838     (init-live-tns block))
839
840   (do ((current *live-vop* (vop-prev current)))
841       ((eq current vop)
842        (do ((res (vop-results vop) (tn-ref-across res)))
843            ((null res))
844          (let* ((tn (tn-ref-tn res))
845                 (sc (tn-sc tn))
846                 (sb (sc-sb sc)))
847            (when (eq (sb-kind sb) :finite)
848              (do ((offset (tn-offset tn) (1+ offset))
849                   (end (+ (tn-offset tn) (sc-element-size sc))))
850                  ((= offset end))
851                (declare (type index offset end))
852                (setf (svref (finite-sb-live-tns sb) offset) nil))))))
853     (do ((ref (vop-refs current) (tn-ref-next-ref ref)))
854         ((null ref))
855       (let ((ltn (tn-ref-load-tn ref)))
856         (when ltn
857           (let* ((sc (tn-sc ltn))
858                  (sb (sc-sb sc)))
859             (when (eq (sb-kind sb) :finite)
860               (let ((tns (finite-sb-live-tns sb)))
861                 (do ((offset (tn-offset ltn) (1+ offset))
862                      (end (+ (tn-offset ltn) (sc-element-size sc))))
863                     ((= offset end))
864                   (declare (type index offset end))
865                   (aver (null (svref tns offset)))))))))
866
867       (let* ((tn (tn-ref-tn ref))
868              (sc (tn-sc tn))
869              (sb (sc-sb sc)))
870         (when (eq (sb-kind sb) :finite)
871           (let ((tns (finite-sb-live-tns sb)))
872             (do ((offset (tn-offset tn) (1+ offset))
873                  (end (+ (tn-offset tn) (sc-element-size sc))))
874                 ((= offset end))
875               (declare (type index offset end))
876               (if (tn-ref-write-p ref)
877                   (setf (svref tns offset) nil)
878                   (let ((old (svref tns offset)))
879                     (aver (or (null old) (eq old tn)))
880                     (setf (svref tns offset) tn)))))))))
881
882   (setq *live-vop* vop)
883   (values))
884
885 ;;; This is kind of like OFFSET-CONFLICTS-IN-SB, except that it uses
886 ;;; the VOP refs to determine whether a Load-TN for OP could be packed
887 ;;; in the specified location, disregarding conflicts with TNs not
888 ;;; referenced by this VOP. There is a conflict if either:
889 ;;;  1. The reference is a result, and the same location is either:
890 ;;;     -- Used by some other result.
891 ;;;     -- Used in any way after the reference (exclusive).
892 ;;;  2. The reference is an argument, and the same location is either:
893 ;;;     -- Used by some other argument.
894 ;;;     -- Used in any way before the reference (exclusive).
895 ;;;
896 ;;; In 1 (and 2) above, the first bullet corresponds to result-result
897 ;;; (and argument-argument) conflicts. We need this case because there
898 ;;; aren't any TN-REFs to represent the implicit reading of results or
899 ;;; writing of arguments.
900 ;;;
901 ;;; The second bullet corresponds conflicts with temporaries or between
902 ;;; arguments and results.
903 ;;;
904 ;;; We consider both the TN-REF-TN and the TN-REF-LOAD-TN (if any) to
905 ;;; be referenced simultaneously and in the same way. This causes
906 ;;; load-TNs to appear live to the beginning (or end) of the VOP, as
907 ;;; appropriate.
908 ;;;
909 ;;; We return a conflicting TN if there is a conflict.
910 (defun load-tn-offset-conflicts-in-sb (op sb offset)
911   (declare (type tn-ref op) (type finite-sb sb) (type index offset))
912   (aver (eq (sb-kind sb) :finite))
913   (let ((vop (tn-ref-vop op)))
914     (labels ((tn-overlaps (tn)
915                (let ((sc (tn-sc tn))
916                      (tn-offset (tn-offset tn)))
917                  (when (and (eq (sc-sb sc) sb)
918                             (<= tn-offset offset)
919                             (< offset
920                                (the index
921                                     (+ tn-offset (sc-element-size sc)))))
922                    tn)))
923              (same (ref)
924                (let ((tn (tn-ref-tn ref))
925                      (ltn (tn-ref-load-tn ref)))
926                  (or (tn-overlaps tn)
927                      (and ltn (tn-overlaps ltn)))))
928              (is-op (ops)
929                (do ((ops ops (tn-ref-across ops)))
930                    ((null ops) nil)
931                  (let ((found (same ops)))
932                    (when (and found (not (eq ops op)))
933                      (return found)))))
934              (is-ref (refs end)
935                (do ((refs refs (tn-ref-next-ref refs)))
936                    ((eq refs end) nil)
937                  (let ((found (same refs)))
938                  (when found (return found))))))
939       (declare (inline is-op is-ref tn-overlaps))
940       (if (tn-ref-write-p op)
941           (or (is-op (vop-results vop))
942               (is-ref (vop-refs vop) op))
943           (or (is-op (vop-args vop))
944               (is-ref (tn-ref-next-ref op) nil))))))
945
946 ;;; Iterate over all the elements in the SB that would be allocated by
947 ;;; allocating a TN in SC at Offset, checking for conflict with
948 ;;; load-TNs or other TNs (live in the LIVE-TNS, which must be set
949 ;;; up.) We also return true if there aren't enough locations after
950 ;;; Offset to hold a TN in SC. If Ignore-Live is true, then we ignore
951 ;;; the live-TNs, considering only references within Op's VOP.
952 ;;;
953 ;;; We return a conflicting TN, or :OVERFLOW if the TN won't fit.
954 (defun load-tn-conflicts-in-sc (op sc offset ignore-live)
955   (let* ((sb (sc-sb sc))
956          (size (finite-sb-current-size sb)))
957     (do ((i offset (1+ i))
958          (end (+ offset (sc-element-size sc))))
959         ((= i end) nil)
960       (declare (type index i end))
961       (let ((res (or (when (>= i size) :overflow)
962                      (and (not ignore-live)
963                           (svref (finite-sb-live-tns sb) i))
964                      (load-tn-offset-conflicts-in-sb op sb i))))
965         (when res (return res))))))
966
967 ;;; If a load-TN for OP is targeted to a legal location in SC, then
968 ;;; return the offset, otherwise return NIL. We see whether the target
969 ;;; of the operand is packed, and try that location. There isn't any
970 ;;; need to chain down the target path, since everything is packed
971 ;;; now.
972 ;;;
973 ;;; We require the target to be in SC (and not merely to overlap with
974 ;;; SC). This prevents SC information from being lost in load TNs (we
975 ;;; won't pack a load TN in ANY-REG when it is targeted to a
976 ;;; DESCRIPTOR-REG.) This shouldn't hurt the code as long as all
977 ;;; relevant overlapping SCs are allowed in the operand SC
978 ;;; restriction.
979 (defun find-load-tn-target (op sc)
980   (declare (inline member))
981   (let ((target (tn-ref-target op)))
982     (when target
983       (let* ((tn (tn-ref-tn target))
984              (loc (tn-offset tn)))
985         (if (and (eq (tn-sc tn) sc)
986                  (member (the index loc) (sc-locations sc))
987                  (not (load-tn-conflicts-in-sc op sc loc nil)))
988             loc
989             nil)))))
990
991 ;;; Select a legal location for a load TN for Op in SC. We just
992 ;;; iterate over the SC's locations. If we can't find a legal
993 ;;; location, return NIL.
994 (defun select-load-tn-location (op sc)
995   (declare (type tn-ref op) (type sc sc))
996
997   ;; Check any target location first.
998   (let ((target (tn-ref-target op)))
999     (when target
1000       (let* ((tn (tn-ref-tn target))
1001              (loc (tn-offset tn)))
1002         (when (and (eq (sc-sb sc) (sc-sb (tn-sc tn)))
1003                    (member (the index loc) (sc-locations sc))
1004                    (not (load-tn-conflicts-in-sc op sc loc nil)))
1005               (return-from select-load-tn-location loc)))))
1006
1007   (dolist (loc (sc-locations sc) nil)
1008     (unless (load-tn-conflicts-in-sc op sc loc nil)
1009       (return loc))))
1010
1011 (defevent unpack-tn "Unpacked a TN to satisfy operand SC restriction.")
1012
1013 ;;; Make TN's location the same as for its save TN (allocating a save
1014 ;;; TN if necessary.) Delete any save/restore code that has been
1015 ;;; emitted thus far. Mark all blocks containing references as needing
1016 ;;; to be repacked.
1017 (defun unpack-tn (tn)
1018   (event unpack-tn)
1019   (let ((stn (or (tn-save-tn tn)
1020                  (pack-save-tn tn))))
1021     (setf (tn-sc tn) (tn-sc stn))
1022     (setf (tn-offset tn) (tn-offset stn))
1023     (flet ((zot (refs)
1024              (do ((ref refs (tn-ref-next ref)))
1025                  ((null ref))
1026                (let ((vop (tn-ref-vop ref)))
1027                  (if (eq (vop-info-name (vop-info vop)) 'move-operand)
1028                      (delete-vop vop)
1029                      (setf (gethash (vop-block vop) *repack-blocks*) t))))))
1030       (zot (tn-reads tn))
1031       (zot (tn-writes tn))))
1032
1033   (values))
1034
1035 (defevent unpack-fallback "Unpacked some operand TN.")
1036
1037 ;;; This is called by PACK-LOAD-TN where there isn't any location free
1038 ;;; that we can pack into. What we do is move some live TN in one of
1039 ;;; the specified SCs to memory, then mark this block all blocks that
1040 ;;; reference the TN as needing repacking. If we succeed, we throw to
1041 ;;; UNPACKED-TN. If we fail, we return NIL.
1042 ;;;
1043 ;;; We can unpack any live TN that appears in the NORMAL-TNs list
1044 ;;; (isn't wired or restricted.) We prefer to unpack TNs that are not
1045 ;;; used by the VOP. If we can't find any such TN, then we unpack some
1046 ;;; argument or result TN. The only way we can fail is if all
1047 ;;; locations in SC are used by load-TNs or temporaries in VOP.
1048 (defun unpack-for-load-tn (sc op)
1049   (declare (type sc sc) (type tn-ref op))
1050   (let ((sb (sc-sb sc))
1051         (normal-tns (ir2-component-normal-tns
1052                      (component-info *component-being-compiled*)))
1053         (node (vop-node (tn-ref-vop op)))
1054         (fallback nil))
1055     (flet ((unpack-em (victims)
1056              (unless *repack-blocks*
1057                (setq *repack-blocks* (make-hash-table :test 'eq)))
1058              (setf (gethash (vop-block (tn-ref-vop op)) *repack-blocks*) t)
1059              (dolist (victim victims)
1060                (event unpack-tn node)
1061                (unpack-tn victim))
1062              (throw 'unpacked-tn nil)))
1063       (dolist (loc (sc-locations sc))
1064         (declare (type index loc))
1065         (block SKIP
1066           (collect ((victims nil adjoin))
1067             (do ((i loc (1+ i))
1068                  (end (+ loc (sc-element-size sc))))
1069                 ((= i end))
1070               (declare (type index i end))
1071               (let ((victim (svref (finite-sb-live-tns sb) i)))
1072                 (when victim
1073                   (unless (find-in #'tn-next victim normal-tns)
1074                     (return-from SKIP))
1075                   (victims victim))))
1076
1077             (let ((conf (load-tn-conflicts-in-sc op sc loc t)))
1078               (cond ((not conf)
1079                      (unpack-em (victims)))
1080                     ((eq conf :overflow))
1081                     ((not fallback)
1082                      (cond ((find conf (victims))
1083                             (setq fallback (victims)))
1084                            ((find-in #'tn-next conf normal-tns)
1085                             (setq fallback (list conf))))))))))
1086
1087       (when fallback
1088         (event unpack-fallback node)
1089         (unpack-em fallback))))
1090
1091   nil)
1092
1093 ;;; Try to pack a load TN in the SCs indicated by Load-SCs. If we run
1094 ;;; out of SCs, then we unpack some TN and try again. We return the
1095 ;;; packed load TN.
1096 ;;;
1097 ;;; Note: we allow a Load-TN to be packed in the target location even
1098 ;;; if that location is in a SC not allowed by the primitive type.
1099 ;;; (The SC must still be allowed by the operand restriction.) This
1100 ;;; makes move VOPs more efficient, since we won't do a move from the
1101 ;;; stack into a non-descriptor any-reg though a descriptor argument
1102 ;;; load-TN. This does give targeting some real semantics, making it
1103 ;;; not a pure advisory to pack. It allows pack to do some packing it
1104 ;;; wouldn't have done before.
1105 (defun pack-load-tn (load-scs op)
1106   (declare (type sc-vector load-scs) (type tn-ref op))
1107   (let ((vop (tn-ref-vop op)))
1108     (compute-live-tns (vop-block vop) vop))
1109
1110   (let* ((tn (tn-ref-tn op))
1111          (ptype (tn-primitive-type tn))
1112          (scs (svref load-scs (sc-number (tn-sc tn)))))
1113     (let ((current-scs scs)
1114           (allowed ()))
1115       (loop
1116         (cond
1117          ((null current-scs)
1118           (unless allowed
1119             (no-load-scs-allowed-by-primitive-type-error op))
1120           (dolist (sc allowed)
1121             (unpack-for-load-tn sc op))
1122           (failed-to-pack-load-tn-error allowed op))
1123         (t
1124          (let* ((sc (svref *backend-sc-numbers* (pop current-scs)))
1125                 (target (find-load-tn-target op sc)))
1126            (when (or target (sc-allowed-by-primitive-type sc ptype))
1127              (let ((loc (or target
1128                             (select-load-tn-location op sc))))
1129                (when loc
1130                  (let ((res (make-tn 0 :load nil sc)))
1131                    (setf (tn-offset res) loc)
1132                    (return res))))
1133              (push sc allowed)))))))))
1134
1135 ;;; Scan a list of load-SCs vectors and a list of TN-REFS threaded by
1136 ;;; TN-REF-ACROSS. When we find a reference whose TN doesn't satisfy
1137 ;;; the restriction, we pack a Load-TN and load the operand into it.
1138 ;;; If a load-tn has already been allocated, we can assume that the
1139 ;;; restriction is satisfied.
1140 #!-sb-fluid (declaim (inline check-operand-restrictions))
1141 (defun check-operand-restrictions (scs ops)
1142   (declare (list scs) (type (or tn-ref null) ops))
1143
1144   ;; Check the targeted operands first.
1145   (do ((scs scs (cdr scs))
1146        (op ops (tn-ref-across op)))
1147       ((null scs))
1148       (let ((target (tn-ref-target op)))
1149         (when target
1150            (let* ((load-tn (tn-ref-load-tn op))
1151                   (load-scs (svref (car scs)
1152                                    (sc-number
1153                                     (tn-sc (or load-tn (tn-ref-tn op)))))))
1154              (if load-tn
1155                  (aver (eq load-scs t))
1156                (unless (eq load-scs t)
1157                        (setf (tn-ref-load-tn op)
1158                              (pack-load-tn (car scs) op))))))))
1159
1160   (do ((scs scs (cdr scs))
1161        (op ops (tn-ref-across op)))
1162       ((null scs))
1163       (let ((target (tn-ref-target op)))
1164         (unless target
1165            (let* ((load-tn (tn-ref-load-tn op))
1166                   (load-scs (svref (car scs)
1167                                    (sc-number
1168                                     (tn-sc (or load-tn (tn-ref-tn op)))))))
1169              (if load-tn
1170                  (aver (eq load-scs t))
1171                (unless (eq load-scs t)
1172                        (setf (tn-ref-load-tn op)
1173                              (pack-load-tn (car scs) op))))))))
1174
1175   (values))
1176
1177 ;;; Scan the VOPs in BLOCK, looking for operands whose SC restrictions
1178 ;;; aren't satisfied. We do the results first, since they are
1179 ;;; evaluated later, and our conflict analysis is a backward scan.
1180 (defun pack-load-tns (block)
1181   (catch 'unpacked-tn
1182     (let ((*live-block* nil)
1183           (*live-vop* nil))
1184       (do ((vop (ir2-block-last-vop block) (vop-prev vop)))
1185           ((null vop))
1186         (let ((info (vop-info vop)))
1187           (check-operand-restrictions (vop-info-result-load-scs info)
1188                                       (vop-results vop))
1189           (check-operand-restrictions (vop-info-arg-load-scs info)
1190                                       (vop-args vop))))))
1191   (values))
1192 \f
1193 ;;;; targeting
1194
1195 ;;; Link the TN-REFS READ and WRITE together using the TN-REF-TARGET
1196 ;;; when this seems like a good idea. Currently we always do, as this
1197 ;;; increases the success of load-TN targeting.
1198 (defun target-if-desirable (read write)
1199   (declare (type tn-ref read write))
1200   ;; As per the comments at the definition of TN-REF-TARGET, read and
1201   ;; write refs are always paired, with TARGET in the read pointing to
1202   ;; the write and vice versa.
1203   (aver (eq (tn-ref-write-p read)
1204             (not (tn-ref-write-p write))))
1205   (setf (tn-ref-target read) write)
1206   (setf (tn-ref-target write) read))
1207
1208 ;;; If TN can be packed into SC so as to honor a preference to TARGET,
1209 ;;; then return the offset to pack at, otherwise return NIL. TARGET
1210 ;;; must be already packed.
1211 (defun check-ok-target (target tn sc)
1212   (declare (type tn target tn) (type sc sc) (inline member))
1213   (let* ((loc (tn-offset target))
1214          (target-sc (tn-sc target))
1215          (target-sb (sc-sb target-sc)))
1216     (declare (type index loc))
1217     ;; We can honor a preference if:
1218     ;; -- TARGET's location is in SC's locations.
1219     ;; -- The element sizes of the two SCs are the same.
1220     ;; -- TN doesn't conflict with target's location.
1221     (if (and (eq target-sb (sc-sb sc))
1222              (or (eq (sb-kind target-sb) :unbounded)
1223                  (member loc (sc-locations sc)))
1224              (= (sc-element-size target-sc) (sc-element-size sc))
1225              (not (conflicts-in-sc tn sc loc))
1226              (zerop (mod loc (sc-alignment sc))))
1227         loc
1228         nil)))
1229
1230 ;;; Scan along the target path from TN, looking at readers or writers.
1231 ;;; When we find a packed TN, return CHECK-OK-TARGET of that TN. If
1232 ;;; there is no target, or if the TN has multiple readers (writers),
1233 ;;; then we return NIL. We also always return NIL after 10 iterations
1234 ;;; to get around potential circularity problems.
1235 ;;;
1236 ;;; FIXME: (30 minutes of reverse engineering?) It'd be nice to
1237 ;;; rewrite the header comment here to explain the interface and its
1238 ;;; motivation, and move remarks about implementation details (like
1239 ;;; 10!) inside.
1240 (defun find-ok-target-offset (tn sc)
1241   (declare (type tn tn) (type sc sc))
1242   (flet ((frob-slot (slot-fun)
1243            (declare (type function slot-fun))
1244            (let ((count 10)
1245                  (current tn))
1246              (declare (type index count))
1247              (loop
1248               (let ((refs (funcall slot-fun current)))
1249                 (unless (and (plusp count)
1250                              refs
1251                              (not (tn-ref-next refs)))
1252                   (return nil))
1253                 (let ((target (tn-ref-target refs)))
1254                   (unless target (return nil))
1255                   (setq current (tn-ref-tn target))
1256                   (when (tn-offset current)
1257                     (return (check-ok-target current tn sc)))
1258                   (decf count)))))))
1259     (declare (inline frob-slot)) ; until DYNAMIC-EXTENT works
1260     (or (frob-slot #'tn-reads)
1261         (frob-slot #'tn-writes))))
1262 \f
1263 ;;;; location selection
1264
1265 ;;; Select some location for TN in SC, returning the offset if we
1266 ;;; succeed, and NIL if we fail. We start scanning at the Last-Offset
1267 ;;; in an attempt to distribute the TNs across all storage.
1268 ;;;
1269 ;;; We call OFFSET-CONFLICTS-IN-SB directly, rather than using
1270 ;;; CONFLICTS-IN-SC. This allows us to more efficient in packing
1271 ;;; multi-location TNs: we don't have to multiply the number of tests
1272 ;;; by the TN size. This falls out naturally, since we have to be
1273 ;;; aware of TN size anyway so that we don't call CONFLICTS-IN-SC on a
1274 ;;; bogus offset.
1275 ;;;
1276 ;;; We give up on finding a location after our current pointer has
1277 ;;; wrapped twice. This will result in testing some locations twice in
1278 ;;; the case that we fail, but is simpler than trying to figure out
1279 ;;; the soonest failure point.
1280 ;;;
1281 ;;; We also give up without bothering to wrap if the current size
1282 ;;; isn't large enough to hold a single element of element-size
1283 ;;; without bothering to wrap. If it doesn't fit this iteration, it
1284 ;;; won't fit next.
1285 ;;;
1286 ;;; ### Note that we actually try to pack as many consecutive TNs as
1287 ;;; possible in the same location, since we start scanning at the same
1288 ;;; offset that the last TN was successfully packed in. This is a
1289 ;;; weakening of the scattering hueristic that was put in to prevent
1290 ;;; restricted VOP temps from hogging all of the registers. This way,
1291 ;;; all of these temps probably end up in one register.
1292 (defun select-location (tn sc &optional use-reserved-locs)
1293   (declare (type tn tn) (type sc sc) (inline member))
1294   (let* ((sb (sc-sb sc))
1295          (element-size (sc-element-size sc))
1296          (alignment (sc-alignment sc))
1297          (align-mask (1- alignment))
1298          (size (finite-sb-current-size sb))
1299          (start-offset (finite-sb-last-offset sb)))
1300     (let ((current-start
1301            (logandc2 (the index (+ start-offset align-mask)) align-mask))
1302           (wrap-p nil))
1303       (declare (type index current-start))
1304       (loop
1305         (when (> (+ current-start element-size) size)
1306           (cond ((or wrap-p (> element-size size))
1307                  (return nil))
1308                 (t
1309                  (setq current-start 0)
1310                  (setq wrap-p t))))
1311
1312         (if (or (eq (sb-kind sb) :unbounded)
1313                 (and (member current-start (sc-locations sc))
1314                      (or use-reserved-locs
1315                          (not (member current-start
1316                                       (sc-reserve-locations sc))))))
1317             (dotimes (i element-size
1318                         (return-from select-location current-start))
1319               (declare (type index i))
1320               (let ((offset (+ current-start i)))
1321                 (when (offset-conflicts-in-sb tn sb offset)
1322                   (setq current-start
1323                         (logandc2 (the index (+ (the index (1+ offset))
1324                                                 align-mask))
1325                                   align-mask))
1326                   (return))))
1327             (incf current-start alignment))))))
1328
1329 ;;; If a save TN, return the saved TN, otherwise return TN. This is
1330 ;;; useful for getting the conflicts of a TN that might be a save TN.
1331 (defun original-tn (tn)
1332   (declare (type tn tn))
1333   (if (member (tn-kind tn) '(:save :save-once :specified-save))
1334       (tn-save-tn tn)
1335       tn))
1336 \f
1337 ;;;; pack interface
1338
1339 ;;; Attempt to pack TN in all possible SCs, first in the SC chosen by
1340 ;;; representation selection, then in the alternate SCs in the order
1341 ;;; they were specified in the SC definition. If the TN-COST is
1342 ;;; negative, then we don't attempt to pack in SCs that must be saved.
1343 ;;; If Restricted, then we can only pack in TN-SC, not in any
1344 ;;; Alternate-SCs.
1345 ;;;
1346 ;;; If we are attempting to pack in the SC of the save TN for a TN
1347 ;;; with a :SPECIFIED-SAVE TN, then we pack in that location, instead
1348 ;;; of allocating a new stack location.
1349 (defun pack-tn (tn restricted)
1350   (declare (type tn tn))
1351   (let* ((original (original-tn tn))
1352          (fsc (tn-sc tn))
1353          (alternates (unless restricted (sc-alternate-scs fsc)))
1354          (save (tn-save-tn tn))
1355          (specified-save-sc
1356           (when (and save
1357                      (eq (tn-kind save) :specified-save))
1358             (tn-sc save))))
1359
1360     (do ((sc fsc (pop alternates)))
1361         ((null sc)
1362          (failed-to-pack-error tn restricted))
1363       (when (eq sc specified-save-sc)
1364         (unless (tn-offset save)
1365           (pack-tn save nil))
1366         (setf (tn-offset tn) (tn-offset save))
1367         (setf (tn-sc tn) (tn-sc save))
1368         (return))
1369       (when (or restricted
1370                 (not (and (minusp (tn-cost tn)) (sc-save-p sc))))
1371         (let ((loc (or (find-ok-target-offset original sc)
1372                        (select-location original sc)
1373                        (and restricted
1374                             (select-location original sc t))
1375                        (when (eq (sb-kind (sc-sb sc)) :unbounded)
1376                          (grow-sc sc)
1377                          (or (select-location original sc)
1378                              (error "failed to pack after growing SC?"))))))
1379           (when loc
1380             (add-location-conflicts original sc loc)
1381             (setf (tn-sc tn) sc)
1382             (setf (tn-offset tn) loc)
1383             (return))))))
1384
1385   (values))
1386
1387 ;;; Pack a wired TN, checking that the offset is in bounds for the SB,
1388 ;;; and that the TN doesn't conflict with some other TN already packed
1389 ;;; in that location. If the TN is wired to a location beyond the end
1390 ;;; of a :UNBOUNDED SB, then grow the SB enough to hold the TN.
1391 ;;;
1392 ;;; ### Checking for conflicts is disabled for :SPECIFIED-SAVE TNs.
1393 ;;; This is kind of a hack to make specifying wired stack save
1394 ;;; locations for local call arguments (such as OLD-FP) work, since
1395 ;;; the caller and callee OLD-FP save locations may conflict when the
1396 ;;; save locations don't really (due to being in different frames.)
1397 (defun pack-wired-tn (tn)
1398   (declare (type tn tn))
1399   (let* ((sc (tn-sc tn))
1400          (sb (sc-sb sc))
1401          (offset (tn-offset tn))
1402          (end (+ offset (sc-element-size sc)))
1403          (original (original-tn tn)))
1404     (when (> end (finite-sb-current-size sb))
1405       (unless (eq (sb-kind sb) :unbounded)
1406         (error "~S is wired to a location that is out of bounds." tn))
1407       (grow-sc sc end))
1408
1409     ;; For non-x86 ports the presence of a save-tn associated with a
1410     ;; tn is used to identify the old-fp and return-pc tns. It depends
1411     ;; on the old-fp and return-pc being passed in registers.
1412     #!-x86
1413     (when (and (not (eq (tn-kind tn) :specified-save))
1414                (conflicts-in-sc original sc offset))
1415       (error "~S is wired to a location that it conflicts with." tn))
1416
1417     ;; Use the above check, but only print a verbose warning. This can
1418     ;; be helpful for debugging the x86 port.
1419     #+nil
1420     (when (and (not (eq (tn-kind tn) :specified-save))
1421                (conflicts-in-sc original sc offset))
1422           (format t "~&* Pack-wired-tn possible conflict:~%  ~
1423                      tn: ~S; tn-kind: ~S~%  ~
1424                      sc: ~S~%  ~
1425                      sb: ~S; sb-name: ~S; sb-kind: ~S~%  ~
1426                      offset: ~S; end: ~S~%  ~
1427                      original ~S~%  ~
1428                      tn-save-tn: ~S; tn-kind of tn-save-tn: ~S~%"
1429                   tn (tn-kind tn) sc
1430                   sb (sb-name sb) (sb-kind sb)
1431                   offset end
1432                   original
1433                   (tn-save-tn tn) (tn-kind (tn-save-tn tn))))
1434
1435     ;; On the x86 ports the old-fp and return-pc are often passed on
1436     ;; the stack so the above hack for the other ports does not always
1437     ;; work. Here the old-fp and return-pc tns are identified by being
1438     ;; on the stack in their standard save locations.
1439     #!+x86
1440     (when (and (not (eq (tn-kind tn) :specified-save))
1441                (not (and (string= (sb-name sb) "STACK")
1442                          (or (= offset 0)
1443                              (= offset 1))))
1444                (conflicts-in-sc original sc offset))
1445       (error "~S is wired to a location that it conflicts with." tn))
1446
1447     (add-location-conflicts original sc offset)))
1448
1449 (defevent repack-block "Repacked a block due to TN unpacking.")
1450
1451 (defun pack (component)
1452   (aver (not *in-pack*))
1453   (let ((*in-pack* t)
1454         (optimize (policy *lexenv*
1455                           (or (>= speed compilation-speed)
1456                               (>= space compilation-speed))))
1457         (2comp (component-info component)))
1458     (init-sb-vectors component)
1459
1460     ;; Call the target functions.
1461     (do-ir2-blocks (block component)
1462       (do ((vop (ir2-block-start-vop block) (vop-next vop)))
1463           ((null vop))
1464         (let ((target-fun (vop-info-target-fun (vop-info vop))))
1465           (when target-fun
1466             (funcall target-fun vop)))))
1467
1468
1469     ;; Pack wired TNs first.
1470     (do ((tn (ir2-component-wired-tns 2comp) (tn-next tn)))
1471         ((null tn))
1472       (pack-wired-tn tn))
1473
1474     ;; Pack restricted component TNs.
1475     (do ((tn (ir2-component-restricted-tns 2comp) (tn-next tn)))
1476         ((null tn))
1477       (when (eq (tn-kind tn) :component)
1478         (pack-tn tn t)))
1479
1480     ;; Pack other restricted TNs.
1481     (do ((tn (ir2-component-restricted-tns 2comp) (tn-next tn)))
1482         ((null tn))
1483       (unless (tn-offset tn)
1484         (pack-tn tn t)))
1485
1486     ;; Assign costs to normal TNs so we know which ones should always
1487     ;; be packed on the stack.
1488     (when (and optimize *pack-assign-costs*)
1489       (assign-tn-costs component))
1490
1491     ;; Pack normal TNs in the order that they appear in the code. This
1492     ;; should have some tendency to pack important TNs first, since
1493     ;; control analysis favors the drop-through. This should also help
1494     ;; targeting, since we will pack the target TN soon after we
1495     ;; determine the location of the targeting TN.
1496     (do-ir2-blocks (block component)
1497       (let ((ltns (ir2-block-local-tns block)))
1498         (do ((i (1- (ir2-block-local-tn-count block)) (1- i)))
1499             ((minusp i))
1500           (declare (fixnum i))
1501           (let ((tn (svref ltns i)))
1502             (unless (or (null tn) (eq tn :more) (tn-offset tn))
1503               (pack-tn tn nil))))))
1504
1505     ;; Pack any leftover normal TNs. This is to deal with :MORE TNs,
1506     ;; which could possibly not appear in any local TN map.
1507     (do ((tn (ir2-component-normal-tns 2comp) (tn-next tn)))
1508         ((null tn))
1509       (unless (tn-offset tn)
1510         (pack-tn tn nil)))
1511
1512     ;; Do load TN packing and emit saves.
1513     (let ((*repack-blocks* nil))
1514       (cond ((and optimize *pack-optimize-saves*)
1515              (optimized-emit-saves component)
1516              (do-ir2-blocks (block component)
1517                (pack-load-tns block)))
1518             (t
1519              (do-ir2-blocks (block component)
1520                (emit-saves block)
1521                (pack-load-tns block))))
1522       (when *repack-blocks*
1523         (loop
1524           (when (zerop (hash-table-count *repack-blocks*)) (return))
1525           (maphash (lambda (block v)
1526                      (declare (ignore v))
1527                      (remhash block *repack-blocks*)
1528                      (event repack-block)
1529                      (pack-load-tns block))
1530                    *repack-blocks*)))))
1531
1532   (values))