0.8.3.70:
[sbcl.git] / src / compiler / ir1opt.lisp
1 ;;;; This file implements the IR1 optimization phase of the compiler.
2 ;;;; IR1 optimization is a grab-bag of optimizations that don't make
3 ;;;; major changes to the block-level control flow and don't use flow
4 ;;;; analysis. These optimizations can mostly be classified as
5 ;;;; "meta-evaluation", but there is a sizable top-down component as
6 ;;;; well.
7
8 ;;;; This software is part of the SBCL system. See the README file for
9 ;;;; more information.
10 ;;;;
11 ;;;; This software is derived from the CMU CL system, which was
12 ;;;; written at Carnegie Mellon University and released into the
13 ;;;; public domain. The software is in the public domain and is
14 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
15 ;;;; files for more information.
16
17 (in-package "SB!C")
18 \f
19 ;;;; interface for obtaining results of constant folding
20
21 ;;; Return true for an LVAR whose sole use is a reference to a
22 ;;; constant leaf.
23 (defun constant-lvar-p (thing)
24   (and (lvar-p thing)
25        (let ((use (principal-lvar-use thing)))
26          (and (ref-p use) (constant-p (ref-leaf use))))))
27
28 ;;; Return the constant value for an LVAR whose only use is a constant
29 ;;; node.
30 (declaim (ftype (function (lvar) t) lvar-value))
31 (defun lvar-value (lvar)
32   (let ((use (principal-lvar-use lvar)))
33     (constant-value (ref-leaf use))))
34 \f
35 ;;;; interface for obtaining results of type inference
36
37 ;;; Our best guess for the type of this lvar's value. Note that this
38 ;;; may be VALUES or FUNCTION type, which cannot be passed as an
39 ;;; argument to the normal type operations. See LVAR-TYPE.
40 ;;;
41 ;;; The result value is cached in the LVAR-%DERIVED-TYPE slot. If the
42 ;;; slot is true, just return that value, otherwise recompute and
43 ;;; stash the value there.
44 #!-sb-fluid (declaim (inline lvar-derived-type))
45 (defun lvar-derived-type (lvar)
46   (declare (type lvar lvar))
47   (or (lvar-%derived-type lvar)
48       (setf (lvar-%derived-type lvar)
49             (%lvar-derived-type lvar))))
50 (defun %lvar-derived-type (lvar)
51   (declare (type lvar lvar))
52   (let ((uses (lvar-uses lvar)))
53     (cond ((null uses) *empty-type*)
54           ((listp uses)
55            (do ((res (node-derived-type (first uses))
56                      (values-type-union (node-derived-type (first current))
57                                         res))
58                 (current (rest uses) (rest current)))
59                ((null current) res)))
60           (t
61            (node-derived-type (lvar-uses lvar))))))
62
63 ;;; Return the derived type for LVAR's first value. This is guaranteed
64 ;;; not to be a VALUES or FUNCTION type.
65 (declaim (ftype (sfunction (lvar) ctype) lvar-type))
66 (defun lvar-type (lvar)
67   (single-value-type (lvar-derived-type lvar)))
68
69 ;;; If LVAR is an argument of a function, return a type which the
70 ;;; function checks LVAR for.
71 #!-sb-fluid (declaim (inline lvar-externally-checkable-type))
72 (defun lvar-externally-checkable-type (lvar)
73   (or (lvar-%externally-checkable-type lvar)
74       (%lvar-%externally-checkable-type lvar)))
75 (defun %lvar-%externally-checkable-type (lvar)
76   (declare (type lvar lvar))
77   (let ((dest (lvar-dest lvar)))
78     (if (not (and dest (combination-p dest)))
79         ;; TODO: MV-COMBINATION
80         (setf (lvar-%externally-checkable-type lvar) *wild-type*)
81         (let* ((fun (combination-fun dest))
82                (args (combination-args dest))
83                (fun-type (lvar-type fun)))
84           (setf (lvar-%externally-checkable-type fun) *wild-type*)
85           (if (or (not (call-full-like-p dest))
86                   (not (fun-type-p fun-type))
87                   ;; FUN-TYPE might be (AND FUNCTION (SATISFIES ...)).
88                   (fun-type-wild-args fun-type))
89               (dolist (arg args)
90                 (when arg
91                   (setf (lvar-%externally-checkable-type arg)
92                         *wild-type*)))
93               (map-combination-args-and-types
94                (lambda (arg type)
95                  (setf (lvar-%externally-checkable-type arg)
96                        (acond ((lvar-%externally-checkable-type arg)
97                                (values-type-intersection
98                                 it (coerce-to-values type)))
99                               (t (coerce-to-values type)))))
100                dest)))))
101   (lvar-%externally-checkable-type lvar))
102 #!-sb-fluid(declaim (inline flush-lvar-externally-checkable-type))
103 (defun flush-lvar-externally-checkable-type (lvar)
104   (declare (type lvar lvar))
105   (setf (lvar-%externally-checkable-type lvar) nil))
106 \f
107 ;;;; interface routines used by optimizers
108
109 ;;; This function is called by optimizers to indicate that something
110 ;;; interesting has happened to the value of LVAR. Optimizers must
111 ;;; make sure that they don't call for reoptimization when nothing has
112 ;;; happened, since optimization will fail to terminate.
113 ;;;
114 ;;; We clear any cached type for the lvar and set the reoptimize flags
115 ;;; on everything in sight.
116 (defun reoptimize-lvar (lvar)
117   (declare (type (or lvar null) lvar))
118   (when lvar
119     (setf (lvar-%derived-type lvar) nil)
120     (let ((dest (lvar-dest lvar)))
121       (when dest
122         (setf (lvar-reoptimize lvar) t)
123         (setf (node-reoptimize dest) t)
124         (binding* (;; Since this may be called during IR1 conversion,
125                    ;; PREV may be missing.
126                    (prev (node-prev dest) :exit-if-null)
127                    (block (ctran-block prev))
128                    (component (block-component block)))
129           (when (typep dest 'cif)
130             (setf (block-test-modified block) t))
131           (setf (block-reoptimize block) t)
132           (setf (component-reoptimize component) t))))
133     (do-uses (node lvar)
134       (setf (block-type-check (node-block node)) t)))
135   (values))
136
137 (defun reoptimize-lvar-uses (lvar)
138   (declare (type lvar lvar))
139   (do-uses (use lvar)
140     (setf (node-reoptimize use) t)
141     (setf (block-reoptimize (node-block use)) t)
142     (setf (component-reoptimize (node-component use)) t)))
143
144 ;;; Annotate NODE to indicate that its result has been proven to be
145 ;;; TYPEP to RTYPE. After IR1 conversion has happened, this is the
146 ;;; only correct way to supply information discovered about a node's
147 ;;; type. If you screw with the NODE-DERIVED-TYPE directly, then
148 ;;; information may be lost and reoptimization may not happen.
149 ;;;
150 ;;; What we do is intersect RTYPE with NODE's DERIVED-TYPE. If the
151 ;;; intersection is different from the old type, then we do a
152 ;;; REOPTIMIZE-LVAR on the NODE-LVAR.
153 (defun derive-node-type (node rtype)
154   (declare (type valued-node node) (type ctype rtype))
155   (let ((node-type (node-derived-type node)))
156     (unless (eq node-type rtype)
157       (let ((int (values-type-intersection node-type rtype))
158             (lvar (node-lvar node)))
159         (when (type/= node-type int)
160           (when (and *check-consistency*
161                      (eq int *empty-type*)
162                      (not (eq rtype *empty-type*)))
163             (let ((*compiler-error-context* node))
164               (compiler-warn
165                "New inferred type ~S conflicts with old type:~
166                 ~%  ~S~%*** possible internal error? Please report this."
167                (type-specifier rtype) (type-specifier node-type))))
168           (setf (node-derived-type node) int)
169           ;; If the new type consists of only one object, replace the
170           ;; node with a constant reference.
171           (when (and (ref-p node)
172                      (lambda-var-p (ref-leaf node)))
173             (let ((type (single-value-type int)))
174               (when (and (member-type-p type)
175                          (null (rest (member-type-members type))))
176                 (change-ref-leaf node (find-constant
177                                        (first (member-type-members type)))))))
178           (reoptimize-lvar lvar)))))
179   (values))
180
181 ;;; This is similar to DERIVE-NODE-TYPE, but asserts that it is an
182 ;;; error for LVAR's value not to be TYPEP to TYPE. We implement it
183 ;;; splitting off DEST a new CAST node; old LVAR will deliver values
184 ;;; to CAST. If we improve the assertion, we set TYPE-CHECK and
185 ;;; TYPE-ASSERTED to guarantee that the new assertion will be checked.
186 (defun assert-lvar-type (lvar type policy)
187   (declare (type lvar lvar) (type ctype type))
188   (unless (values-subtypep (lvar-derived-type lvar) type)
189     (let* ((dest (lvar-dest lvar))
190            (ctran (node-prev dest)))
191       (with-ir1-environment-from-node dest
192         (let* ((cast (make-cast lvar type policy))
193                (internal-lvar (make-lvar))
194                (internal-ctran (make-ctran)))
195           (setf (ctran-next ctran) cast
196                 (node-prev cast) ctran)
197           (use-continuation cast internal-ctran internal-lvar)
198           (link-node-to-previous-ctran dest internal-ctran)
199           (substitute-lvar internal-lvar lvar)
200           (setf (lvar-dest lvar) cast)
201           (reoptimize-lvar lvar)
202           (when (return-p dest)
203             (node-ends-block cast))
204           (setf (block-attributep (block-flags (node-block cast))
205                                   type-check type-asserted)
206                 t))))))
207
208 \f
209 ;;;; IR1-OPTIMIZE
210
211 ;;; Do one forward pass over COMPONENT, deleting unreachable blocks
212 ;;; and doing IR1 optimizations. We can ignore all blocks that don't
213 ;;; have the REOPTIMIZE flag set. If COMPONENT-REOPTIMIZE is true when
214 ;;; we are done, then another iteration would be beneficial.
215 (defun ir1-optimize (component)
216   (declare (type component component))
217   (setf (component-reoptimize component) nil)
218   (do-blocks (block component)
219     (cond
220       ;; We delete blocks when there is either no predecessor or the
221       ;; block is in a lambda that has been deleted. These blocks
222       ;; would eventually be deleted by DFO recomputation, but doing
223       ;; it here immediately makes the effect available to IR1
224       ;; optimization.
225       ((or (block-delete-p block)
226            (null (block-pred block)))
227        (delete-block block))
228       ((eq (functional-kind (block-home-lambda block)) :deleted)
229        ;; Preserve the BLOCK-SUCC invariant that almost every block has
230        ;; one successor (and a block with DELETE-P set is an acceptable
231        ;; exception).
232        (mark-for-deletion block)
233        (delete-block block))
234       (t
235        (loop
236           (let ((succ (block-succ block)))
237             (unless (singleton-p succ)
238               (return)))
239
240           (let ((last (block-last block)))
241             (typecase last
242               (cif
243                (flush-dest (if-test last))
244                (when (unlink-node last)
245                  (return)))
246               (exit
247                (when (maybe-delete-exit last)
248                  (return)))))
249
250           (unless (join-successor-if-possible block)
251             (return)))
252
253        (when (and (block-reoptimize block) (block-component block))
254          (aver (not (block-delete-p block)))
255          (ir1-optimize-block block))
256
257        (cond ((and (block-delete-p block) (block-component block))
258               (delete-block block))
259              ((and (block-flush-p block) (block-component block))
260               (flush-dead-code block))))))
261
262   (values))
263
264 ;;; Loop over the nodes in BLOCK, acting on (and clearing) REOPTIMIZE
265 ;;; flags.
266 ;;;
267 ;;; Note that although they are cleared here, REOPTIMIZE flags might
268 ;;; still be set upon return from this function, meaning that further
269 ;;; optimization is wanted (as a consequence of optimizations we did).
270 (defun ir1-optimize-block (block)
271   (declare (type cblock block))
272   ;; We clear the node and block REOPTIMIZE flags before doing the
273   ;; optimization, not after. This ensures that the node or block will
274   ;; be reoptimized if necessary.
275   (setf (block-reoptimize block) nil)
276   (do-nodes (node nil block :restart-p t)
277     (when (node-reoptimize node)
278       ;; As above, we clear the node REOPTIMIZE flag before optimizing.
279       (setf (node-reoptimize node) nil)
280       (typecase node
281         (ref)
282         (combination
283          ;; With a COMBINATION, we call PROPAGATE-FUN-CHANGE whenever
284          ;; the function changes, and call IR1-OPTIMIZE-COMBINATION if
285          ;; any argument changes.
286          (ir1-optimize-combination node))
287         (cif
288          (ir1-optimize-if node))
289         (creturn
290          ;; KLUDGE: We leave the NODE-OPTIMIZE flag set going into
291          ;; IR1-OPTIMIZE-RETURN, since IR1-OPTIMIZE-RETURN wants to
292          ;; clear the flag itself. -- WHN 2002-02-02, quoting original
293          ;; CMU CL comments
294          (setf (node-reoptimize node) t)
295          (ir1-optimize-return node))
296         (mv-combination
297          (ir1-optimize-mv-combination node))
298         (exit
299          ;; With an EXIT, we derive the node's type from the VALUE's
300          ;; type.
301          (let ((value (exit-value node)))
302            (when value
303              (derive-node-type node (lvar-derived-type value)))))
304         (cset
305          (ir1-optimize-set node))
306         (cast
307          (ir1-optimize-cast node)))))
308
309   (values))
310
311 ;;; Try to join with a successor block. If we succeed, we return true,
312 ;;; otherwise false.
313 (defun join-successor-if-possible (block)
314   (declare (type cblock block))
315   (let ((next (first (block-succ block))))
316     (when (block-start next)  ; NEXT is not an END-OF-COMPONENT marker
317       (cond ( ;; We cannot combine with a successor block if:
318              (or
319               ;; The successor has more than one predecessor.
320               (rest (block-pred next))
321               ;; The successor is the current block (infinite loop).
322               (eq next block)
323               ;; The next block has a different cleanup, and thus
324               ;; we may want to insert cleanup code between the
325               ;; two blocks at some point.
326               (not (eq (block-end-cleanup block)
327                        (block-start-cleanup next)))
328               ;; The next block has a different home lambda, and
329               ;; thus the control transfer is a non-local exit.
330               (not (eq (block-home-lambda block)
331                        (block-home-lambda next))))
332              nil)
333             (t
334              (join-blocks block next)
335              t)))))
336
337 ;;; Join together two blocks. The code in BLOCK2 is moved into BLOCK1
338 ;;; and BLOCK2 is deleted from the DFO. We combine the optimize flags
339 ;;; for the two blocks so that any indicated optimization gets done.
340 (defun join-blocks (block1 block2)
341   (declare (type cblock block1 block2))
342   (let* ((last1 (block-last block1))
343          (last2 (block-last block2))
344          (succ (block-succ block2))
345          (start2 (block-start block2)))
346     (do ((ctran start2 (node-next (ctran-next ctran))))
347         ((not ctran))
348       (setf (ctran-block ctran) block1))
349
350     (unlink-blocks block1 block2)
351     (dolist (block succ)
352       (unlink-blocks block2 block)
353       (link-blocks block1 block))
354
355     (setf (ctran-kind start2) :inside-block)
356     (setf (node-next last1) start2)
357     (setf (ctran-use start2) last1)
358     (setf (block-last block1) last2))
359
360   (setf (block-flags block1)
361         (attributes-union (block-flags block1)
362                           (block-flags block2)
363                           (block-attributes type-asserted test-modified)))
364
365   (let ((next (block-next block2))
366         (prev (block-prev block2)))
367     (setf (block-next prev) next)
368     (setf (block-prev next) prev))
369
370   (values))
371
372 ;;; Delete any nodes in BLOCK whose value is unused and which have no
373 ;;; side effects. We can delete sets of lexical variables when the set
374 ;;; variable has no references.
375 (defun flush-dead-code (block)
376   (declare (type cblock block))
377   (setf (block-flush-p block) nil)
378   (do-nodes-backwards (node lvar block)
379     (unless lvar
380       (typecase node
381         (ref
382          (delete-ref node)
383          (unlink-node node))
384         (combination
385          (let ((info (combination-kind node)))
386            (when (fun-info-p info)
387              (let ((attr (fun-info-attributes info)))
388                (when (and (not (ir1-attributep attr call))
389                           ;; ### For now, don't delete potentially
390                           ;; flushable calls when they have the CALL
391                           ;; attribute. Someday we should look at the
392                           ;; functional args to determine if they have
393                           ;; any side effects.
394                           (if (policy node (= safety 3))
395                               (ir1-attributep attr flushable)
396                               (ir1-attributep attr unsafely-flushable)))
397                  (flush-combination node))))))
398         (mv-combination
399          (when (eq (basic-combination-kind node) :local)
400            (let ((fun (combination-lambda node)))
401              (when (dolist (var (lambda-vars fun) t)
402                      (when (or (leaf-refs var)
403                                (lambda-var-sets var))
404                        (return nil)))
405                (flush-dest (first (basic-combination-args node)))
406                (delete-let fun)))))
407         (exit
408          (let ((value (exit-value node)))
409            (when value
410              (flush-dest value)
411              (setf (exit-value node) nil))))
412         (cset
413          (let ((var (set-var node)))
414            (when (and (lambda-var-p var)
415                       (null (leaf-refs var)))
416              (flush-dest (set-value node))
417              (setf (basic-var-sets var)
418                    (delq node (basic-var-sets var)))
419              (unlink-node node))))
420         (cast
421          (unless (cast-type-check node)
422            (flush-dest (cast-value node))
423            (unlink-node node))))))
424
425   (values))
426 \f
427 ;;;; local call return type propagation
428
429 ;;; This function is called on RETURN nodes that have their REOPTIMIZE
430 ;;; flag set. It iterates over the uses of the RESULT, looking for
431 ;;; interesting stuff to update the TAIL-SET. If a use isn't a local
432 ;;; call, then we union its type together with the types of other such
433 ;;; uses. We assign to the RETURN-RESULT-TYPE the intersection of this
434 ;;; type with the RESULT's asserted type. We can make this
435 ;;; intersection now (potentially before type checking) because this
436 ;;; assertion on the result will eventually be checked (if
437 ;;; appropriate.)
438 ;;;
439 ;;; We call MAYBE-CONVERT-TAIL-LOCAL-CALL on each local non-MV
440 ;;; combination, which may change the succesor of the call to be the
441 ;;; called function, and if so, checks if the call can become an
442 ;;; assignment. If we convert to an assignment, we abort, since the
443 ;;; RETURN has been deleted.
444 (defun find-result-type (node)
445   (declare (type creturn node))
446   (let ((result (return-result node)))
447     (collect ((use-union *empty-type* values-type-union))
448       (do-uses (use result)
449         (cond ((and (basic-combination-p use)
450                     (eq (basic-combination-kind use) :local))
451                (aver (eq (lambda-tail-set (node-home-lambda use))
452                          (lambda-tail-set (combination-lambda use))))
453                (when (combination-p use)
454                  (when (nth-value 1 (maybe-convert-tail-local-call use))
455                    (return-from find-result-type (values)))))
456               (t
457                (use-union (node-derived-type use)))))
458       (let ((int
459              ;; (values-type-intersection
460              ;; (continuation-asserted-type result) ; FIXME -- APD, 2002-01-26
461              (use-union)
462               ;; )
463             ))
464         (setf (return-result-type node) int))))
465   (values))
466
467 ;;; Do stuff to realize that something has changed about the value
468 ;;; delivered to a return node. Since we consider the return values of
469 ;;; all functions in the tail set to be equivalent, this amounts to
470 ;;; bringing the entire tail set up to date. We iterate over the
471 ;;; returns for all the functions in the tail set, reanalyzing them
472 ;;; all (not treating NODE specially.)
473 ;;;
474 ;;; When we are done, we check whether the new type is different from
475 ;;; the old TAIL-SET-TYPE. If so, we set the type and also reoptimize
476 ;;; all the lvars for references to functions in the tail set. This
477 ;;; will cause IR1-OPTIMIZE-COMBINATION to derive the new type as the
478 ;;; results of the calls.
479 (defun ir1-optimize-return (node)
480   (declare (type creturn node))
481   (let* ((tails (lambda-tail-set (return-lambda node)))
482          (funs (tail-set-funs tails)))
483     (collect ((res *empty-type* values-type-union))
484       (dolist (fun funs)
485         (let ((return (lambda-return fun)))
486           (when return
487             (when (node-reoptimize return)
488               (setf (node-reoptimize return) nil)
489               (find-result-type return))
490             (res (return-result-type return)))))
491
492       (when (type/= (res) (tail-set-type tails))
493         (setf (tail-set-type tails) (res))
494         (dolist (fun (tail-set-funs tails))
495           (dolist (ref (leaf-refs fun))
496             (reoptimize-lvar (node-lvar ref)))))))
497
498   (values))
499 \f
500 ;;;; IF optimization
501
502 ;;; If the test has multiple uses, replicate the node when possible.
503 ;;; Also check whether the predicate is known to be true or false,
504 ;;; deleting the IF node in favor of the appropriate branch when this
505 ;;; is the case.
506 (defun ir1-optimize-if (node)
507   (declare (type cif node))
508   (let ((test (if-test node))
509         (block (node-block node)))
510
511     (when (and (eq (block-start-node block) node)
512                (listp (lvar-uses test)))
513       (do-uses (use test)
514         (when (immediately-used-p test use)
515           (convert-if-if use node)
516           (when (not (listp (lvar-uses test))) (return)))))
517
518     (let* ((type (lvar-type test))
519            (victim
520             (cond ((constant-lvar-p test)
521                    (if (lvar-value test)
522                        (if-alternative node)
523                        (if-consequent node)))
524                   ((not (types-equal-or-intersect type (specifier-type 'null)))
525                    (if-alternative node))
526                   ((type= type (specifier-type 'null))
527                    (if-consequent node)))))
528       (when victim
529         (flush-dest test)
530         (when (rest (block-succ block))
531           (unlink-blocks block victim))
532         (setf (component-reanalyze (node-component node)) t)
533         (unlink-node node))))
534   (values))
535
536 ;;; Create a new copy of an IF node that tests the value of the node
537 ;;; USE. The test must have >1 use, and must be immediately used by
538 ;;; USE. NODE must be the only node in its block (implying that
539 ;;; block-start = if-test).
540 ;;;
541 ;;; This optimization has an effect semantically similar to the
542 ;;; source-to-source transformation:
543 ;;;    (IF (IF A B C) D E) ==>
544 ;;;    (IF A (IF B D E) (IF C D E))
545 ;;;
546 ;;; We clobber the NODE-SOURCE-PATH of both the original and the new
547 ;;; node so that dead code deletion notes will definitely not consider
548 ;;; either node to be part of the original source. One node might
549 ;;; become unreachable, resulting in a spurious note.
550 (defun convert-if-if (use node)
551   (declare (type node use) (type cif node))
552   (with-ir1-environment-from-node node
553     (let* ((block (node-block node))
554            (test (if-test node))
555            (cblock (if-consequent node))
556            (ablock (if-alternative node))
557            (use-block (node-block use))
558            (new-ctran (make-ctran))
559            (new-lvar (make-lvar))
560            (new-node (make-if :test new-lvar
561                               :consequent cblock
562                               :alternative ablock))
563            (new-block (ctran-starts-block new-ctran)))
564       (link-node-to-previous-ctran new-node new-ctran)
565       (setf (lvar-dest new-lvar) new-node)
566       (setf (block-last new-block) new-node)
567
568       (unlink-blocks use-block block)
569       (%delete-lvar-use use)
570       (add-lvar-use use new-lvar)
571       (link-blocks use-block new-block)
572
573       (link-blocks new-block cblock)
574       (link-blocks new-block ablock)
575
576       (push "<IF Duplication>" (node-source-path node))
577       (push "<IF Duplication>" (node-source-path new-node))
578
579       (reoptimize-lvar test)
580       (reoptimize-lvar new-lvar)
581       (setf (component-reanalyze *current-component*) t)))
582   (values))
583 \f
584 ;;;; exit IR1 optimization
585
586 ;;; This function attempts to delete an exit node, returning true if
587 ;;; it deletes the block as a consequence:
588 ;;; -- If the exit is degenerate (has no ENTRY), then we don't do
589 ;;;    anything, since there is nothing to be done.
590 ;;; -- If the exit node and its ENTRY have the same home lambda then
591 ;;;    we know the exit is local, and can delete the exit. We change
592 ;;;    uses of the Exit-Value to be uses of the original lvar,
593 ;;;    then unlink the node. If the exit is to a TR context, then we
594 ;;;    must do MERGE-TAIL-SETS on any local calls which delivered
595 ;;;    their value to this exit.
596 ;;; -- If there is no value (as in a GO), then we skip the value
597 ;;;    semantics.
598 ;;;
599 ;;; This function is also called by environment analysis, since it
600 ;;; wants all exits to be optimized even if normal optimization was
601 ;;; omitted.
602 (defun maybe-delete-exit (node)
603   (declare (type exit node))
604   (let ((value (exit-value node))
605         (entry (exit-entry node)))
606     (when (and entry
607                (eq (node-home-lambda node) (node-home-lambda entry)))
608       (setf (entry-exits entry) (delq node (entry-exits entry)))
609       (if value
610           (delete-filter node (node-lvar node) value)
611           (unlink-node node)))))
612
613 \f
614 ;;;; combination IR1 optimization
615
616 ;;; Report as we try each transform?
617 #!+sb-show
618 (defvar *show-transforms-p* nil)
619
620 ;;; Do IR1 optimizations on a COMBINATION node.
621 (declaim (ftype (function (combination) (values)) ir1-optimize-combination))
622 (defun ir1-optimize-combination (node)
623   (when (lvar-reoptimize (basic-combination-fun node))
624     (propagate-fun-change node))
625   (let ((args (basic-combination-args node))
626         (kind (basic-combination-kind node)))
627     (case kind
628       (:local
629        (let ((fun (combination-lambda node)))
630          (if (eq (functional-kind fun) :let)
631              (propagate-let-args node fun)
632              (propagate-local-call-args node fun))))
633       ((:full :error)
634        (dolist (arg args)
635          (when arg
636            (setf (lvar-reoptimize arg) nil))))
637       (t
638        (dolist (arg args)
639          (when arg
640            (setf (lvar-reoptimize arg) nil)))
641
642        (let ((attr (fun-info-attributes kind)))
643          (when (and (ir1-attributep attr foldable)
644                     ;; KLUDGE: The next test could be made more sensitive,
645                     ;; only suppressing constant-folding of functions with
646                     ;; CALL attributes when they're actually passed
647                     ;; function arguments. -- WHN 19990918
648                     (not (ir1-attributep attr call))
649                     (every #'constant-lvar-p args)
650                     (node-lvar node)
651                     ;; Even if the function is foldable in principle,
652                     ;; it might be one of our low-level
653                     ;; implementation-specific functions. Such
654                     ;; functions don't necessarily exist at runtime on
655                     ;; a plain vanilla ANSI Common Lisp
656                     ;; cross-compilation host, in which case the
657                     ;; cross-compiler can't fold it because the
658                     ;; cross-compiler doesn't know how to evaluate it.
659                     #+sb-xc-host
660                     (or (fboundp (combination-fun-source-name node))
661                         (progn (format t ";;; !!! Unbound fun: (~S~{ ~S~})~%"
662                                        (combination-fun-source-name node)
663                                        (mapcar #'lvar-value args))
664                                nil)))
665            (constant-fold-call node)
666            (return-from ir1-optimize-combination)))
667
668        (let ((fun (fun-info-derive-type kind)))
669          (when fun
670            (let ((res (funcall fun node)))
671              (when res
672                (derive-node-type node (coerce-to-values res))
673                (maybe-terminate-block node nil)))))
674
675        (let ((fun (fun-info-optimizer kind)))
676          (unless (and fun (funcall fun node))
677            (dolist (x (fun-info-transforms kind))
678              #!+sb-show
679              (when *show-transforms-p*
680                (let* ((lvar (basic-combination-fun node))
681                       (fname (lvar-fun-name lvar t)))
682                  (/show "trying transform" x (transform-function x) "for" fname)))
683              (unless (ir1-transform node x)
684                #!+sb-show
685                (when *show-transforms-p*
686                  (/show "quitting because IR1-TRANSFORM result was NIL"))
687                (return))))))))
688
689   (values))
690
691 ;;; If NODE doesn't return (i.e. return type is NIL), then terminate
692 ;;; the block there, and link it to the component tail.
693 ;;;
694 ;;; Except when called during IR1 convertion, we delete the
695 ;;; continuation if it has no other uses. (If it does have other uses,
696 ;;; we reoptimize.)
697 ;;;
698 ;;; Termination on the basis of a continuation type is
699 ;;; inhibited when:
700 ;;; -- The continuation is deleted (hence the assertion is spurious), or
701 ;;; -- We are in IR1 conversion (where THE assertions are subject to
702 ;;;    weakening.) FIXME: Now THE assertions are not weakened, but new
703 ;;;    uses can(?) be added later. -- APD, 2003-07-17
704 ;;;
705 ;;; Why do we need to consider LVAR type? -- APD, 2003-07-30
706 (defun maybe-terminate-block (node ir1-converting-not-optimizing-p)
707   (declare (type (or basic-combination cast) node))
708   (let* ((block (node-block node))
709          (lvar (node-lvar node))
710          (ctran (node-next node))
711          (tail (component-tail (block-component block)))
712          (succ (first (block-succ block))))
713     (unless (or (and (eq node (block-last block)) (eq succ tail))
714                 (block-delete-p block))
715       (when (eq (node-derived-type node) *empty-type*)
716         (cond (ir1-converting-not-optimizing-p
717                (cond
718                  ((block-last block)
719                   (aver (eq (block-last block) node)))
720                  (t
721                   (setf (block-last block) node)
722                   (setf (ctran-use ctran) nil)
723                   (setf (ctran-kind ctran) :unused)
724                   (setf (ctran-block ctran) nil)
725                   (setf (node-next node) nil)
726                   (link-blocks block (ctran-starts-block ctran)))))
727               (t
728                (node-ends-block node)))
729
730         (unlink-blocks block (first (block-succ block)))
731         (setf (component-reanalyze (block-component block)) t)
732         (aver (not (block-succ block)))
733         (link-blocks block tail)
734         (if ir1-converting-not-optimizing-p
735             (%delete-lvar-use node)
736             (delete-lvar-use node))
737         t))))
738
739 ;;; This is called both by IR1 conversion and IR1 optimization when
740 ;;; they have verified the type signature for the call, and are
741 ;;; wondering if something should be done to special-case the call. If
742 ;;; CALL is a call to a global function, then see whether it defined
743 ;;; or known:
744 ;;; -- If a DEFINED-FUN should be inline expanded, then convert
745 ;;;    the expansion and change the call to call it. Expansion is
746 ;;;    enabled if :INLINE or if SPACE=0. If the FUNCTIONAL slot is
747 ;;;    true, we never expand, since this function has already been
748 ;;;    converted. Local call analysis will duplicate the definition
749 ;;;    if necessary. We claim that the parent form is LABELS for
750 ;;;    context declarations, since we don't want it to be considered
751 ;;;    a real global function.
752 ;;; -- If it is a known function, mark it as such by setting the KIND.
753 ;;;
754 ;;; We return the leaf referenced (NIL if not a leaf) and the
755 ;;; FUN-INFO assigned.
756 (defun recognize-known-call (call ir1-converting-not-optimizing-p)
757   (declare (type combination call))
758   (let* ((ref (lvar-uses (basic-combination-fun call)))
759          (leaf (when (ref-p ref) (ref-leaf ref)))
760          (inlinep (if (defined-fun-p leaf)
761                       (defined-fun-inlinep leaf)
762                       :no-chance)))
763     (cond
764      ((eq inlinep :notinline) (values nil nil))
765      ((not (and (global-var-p leaf)
766                 (eq (global-var-kind leaf) :global-function)))
767       (values leaf nil))
768      ((and (ecase inlinep
769              (:inline t)
770              (:no-chance nil)
771              ((nil :maybe-inline) (policy call (zerop space))))
772            (defined-fun-p leaf)
773            (defined-fun-inline-expansion leaf)
774            (let ((fun (defined-fun-functional leaf)))
775              (or (not fun)
776                  (and (eq inlinep :inline) (functional-kind fun))))
777            (inline-expansion-ok call))
778       (flet (;; FIXME: Is this what the old CMU CL internal documentation
779              ;; called semi-inlining? A more descriptive name would
780              ;; be nice. -- WHN 2002-01-07
781              (frob ()
782                (let ((res (ir1-convert-lambda-for-defun
783                            (defined-fun-inline-expansion leaf)
784                            leaf t
785                            #'ir1-convert-inline-lambda)))
786                  (setf (defined-fun-functional leaf) res)
787                  (change-ref-leaf ref res))))
788         (if ir1-converting-not-optimizing-p
789             (frob)
790             (with-ir1-environment-from-node call
791               (frob)
792               (locall-analyze-component *current-component*))))
793
794       (values (ref-leaf (lvar-uses (basic-combination-fun call)))
795               nil))
796      (t
797       (let ((info (info :function :info (leaf-source-name leaf))))
798         (if info
799             (values leaf (setf (basic-combination-kind call) info))
800             (values leaf nil)))))))
801
802 ;;; Check whether CALL satisfies TYPE. If so, apply the type to the
803 ;;; call, and do MAYBE-TERMINATE-BLOCK and return the values of
804 ;;; RECOGNIZE-KNOWN-CALL. If an error, set the combination kind and
805 ;;; return NIL, NIL. If the type is just FUNCTION, then skip the
806 ;;; syntax check, arg/result type processing, but still call
807 ;;; RECOGNIZE-KNOWN-CALL, since the call might be to a known lambda,
808 ;;; and that checking is done by local call analysis.
809 (defun validate-call-type (call type ir1-converting-not-optimizing-p)
810   (declare (type combination call) (type ctype type))
811   (cond ((not (fun-type-p type))
812          (aver (multiple-value-bind (val win)
813                    (csubtypep type (specifier-type 'function))
814                  (or val (not win))))
815          (recognize-known-call call ir1-converting-not-optimizing-p))
816         ((valid-fun-use call type
817                         :argument-test #'always-subtypep
818                         :result-test #'always-subtypep
819                         ;; KLUDGE: Common Lisp is such a dynamic
820                         ;; language that all we can do here in
821                         ;; general is issue a STYLE-WARNING. It
822                         ;; would be nice to issue a full WARNING
823                         ;; in the special case of of type
824                         ;; mismatches within a compilation unit
825                         ;; (as in section 3.2.2.3 of the spec)
826                         ;; but at least as of sbcl-0.6.11, we
827                         ;; don't keep track of whether the
828                         ;; mismatched data came from the same
829                         ;; compilation unit, so we can't do that.
830                         ;; -- WHN 2001-02-11
831                         ;;
832                         ;; FIXME: Actually, I think we could
833                         ;; issue a full WARNING if the call
834                         ;; violates a DECLAIM FTYPE.
835                         :lossage-fun #'compiler-style-warn
836                         :unwinnage-fun #'compiler-notify)
837          (assert-call-type call type)
838          (maybe-terminate-block call ir1-converting-not-optimizing-p)
839          (recognize-known-call call ir1-converting-not-optimizing-p))
840         (t
841          (setf (combination-kind call) :error)
842          (values nil nil))))
843
844 ;;; This is called by IR1-OPTIMIZE when the function for a call has
845 ;;; changed. If the call is local, we try to LET-convert it, and
846 ;;; derive the result type. If it is a :FULL call, we validate it
847 ;;; against the type, which recognizes known calls, does inline
848 ;;; expansion, etc. If a call to a predicate in a non-conditional
849 ;;; position or to a function with a source transform, then we
850 ;;; reconvert the form to give IR1 another chance.
851 (defun propagate-fun-change (call)
852   (declare (type combination call))
853   (let ((*compiler-error-context* call)
854         (fun-lvar (basic-combination-fun call)))
855     (setf (lvar-reoptimize fun-lvar) nil)
856     (case (combination-kind call)
857       (:local
858        (let ((fun (combination-lambda call)))
859          (maybe-let-convert fun)
860          (unless (member (functional-kind fun) '(:let :assignment :deleted))
861            (derive-node-type call (tail-set-type (lambda-tail-set fun))))))
862       (:full
863        (multiple-value-bind (leaf info)
864            (validate-call-type call (lvar-type fun-lvar) nil)
865          (cond ((functional-p leaf)
866                 (convert-call-if-possible
867                  (lvar-uses (basic-combination-fun call))
868                  call))
869                ((not leaf))
870                ((and (leaf-has-source-name-p leaf)
871                      (or (info :function :source-transform (leaf-source-name leaf))
872                          (and info
873                               (ir1-attributep (fun-info-attributes info)
874                                               predicate)
875                               (let ((lvar (node-lvar call)))
876                                 (and lvar (not (if-p (lvar-dest lvar))))))))
877                 (let ((name (leaf-source-name leaf))
878                       (dummies (make-gensym-list
879                                 (length (combination-args call)))))
880                   (transform-call call
881                                   `(lambda ,dummies
882                                      (,@(if (symbolp name)
883                                             `(,name)
884                                             `(funcall #',name))
885                                         ,@dummies))
886                                   (leaf-source-name leaf)))))))))
887   (values))
888 \f
889 ;;;; known function optimization
890
891 ;;; Add a failed optimization note to FAILED-OPTIMZATIONS for NODE,
892 ;;; FUN and ARGS. If there is already a note for NODE and TRANSFORM,
893 ;;; replace it, otherwise add a new one.
894 (defun record-optimization-failure (node transform args)
895   (declare (type combination node) (type transform transform)
896            (type (or fun-type list) args))
897   (let* ((table (component-failed-optimizations *component-being-compiled*))
898          (found (assoc transform (gethash node table))))
899     (if found
900         (setf (cdr found) args)
901         (push (cons transform args) (gethash node table))))
902   (values))
903
904 ;;; Attempt to transform NODE using TRANSFORM-FUNCTION, subject to the
905 ;;; call type constraint TRANSFORM-TYPE. If we are inhibited from
906 ;;; doing the transform for some reason and FLAME is true, then we
907 ;;; make a note of the message in FAILED-OPTIMIZATIONS for IR1
908 ;;; finalize to pick up. We return true if the transform failed, and
909 ;;; thus further transformation should be attempted. We return false
910 ;;; if either the transform succeeded or was aborted.
911 (defun ir1-transform (node transform)
912   (declare (type combination node) (type transform transform))
913   (let* ((type (transform-type transform))
914          (fun (transform-function transform))
915          (constrained (fun-type-p type))
916          (table (component-failed-optimizations *component-being-compiled*))
917          (flame (if (transform-important transform)
918                     (policy node (>= speed inhibit-warnings))
919                     (policy node (> speed inhibit-warnings))))
920          (*compiler-error-context* node))
921     (cond ((or (not constrained)
922                (valid-fun-use node type))
923            (multiple-value-bind (severity args)
924                (catch 'give-up-ir1-transform
925                  (transform-call node
926                                  (funcall fun node)
927                                  (combination-fun-source-name node))
928                  (values :none nil))
929              (ecase severity
930                (:none
931                 (remhash node table)
932                 nil)
933                (:aborted
934                 (setf (combination-kind node) :error)
935                 (when args
936                   (apply #'compiler-warn args))
937                 (remhash node table)
938                 nil)
939                (:failure
940                 (if args
941                     (when flame
942                       (record-optimization-failure node transform args))
943                     (setf (gethash node table)
944                           (remove transform (gethash node table) :key #'car)))
945                 t)
946                (:delayed
947                  (remhash node table)
948                  nil))))
949           ((and flame
950                 (valid-fun-use node
951                                type
952                                :argument-test #'types-equal-or-intersect
953                                :result-test #'values-types-equal-or-intersect))
954            (record-optimization-failure node transform type)
955            t)
956           (t
957            t))))
958
959 ;;; When we don't like an IR1 transform, we throw the severity/reason
960 ;;; and args.
961 ;;;
962 ;;; GIVE-UP-IR1-TRANSFORM is used to throw out of an IR1 transform,
963 ;;; aborting this attempt to transform the call, but admitting the
964 ;;; possibility that this or some other transform will later succeed.
965 ;;; If arguments are supplied, they are format arguments for an
966 ;;; efficiency note.
967 ;;;
968 ;;; ABORT-IR1-TRANSFORM is used to throw out of an IR1 transform and
969 ;;; force a normal call to the function at run time. No further
970 ;;; optimizations will be attempted.
971 ;;;
972 ;;; DELAY-IR1-TRANSFORM is used to throw out of an IR1 transform, and
973 ;;; delay the transform on the node until later. REASONS specifies
974 ;;; when the transform will be later retried. The :OPTIMIZE reason
975 ;;; causes the transform to be delayed until after the current IR1
976 ;;; optimization pass. The :CONSTRAINT reason causes the transform to
977 ;;; be delayed until after constraint propagation.
978 ;;;
979 ;;; FIXME: Now (0.6.11.44) that there are 4 variants of this (GIVE-UP,
980 ;;; ABORT, DELAY/:OPTIMIZE, DELAY/:CONSTRAINT) and we're starting to
981 ;;; do CASE operations on the various REASON values, it might be a
982 ;;; good idea to go OO, representing the reasons by objects, using
983 ;;; CLOS methods on the objects instead of CASE, and (possibly) using
984 ;;; SIGNAL instead of THROW.
985 (declaim (ftype (function (&rest t) nil) give-up-ir1-transform))
986 (defun give-up-ir1-transform (&rest args)
987   (throw 'give-up-ir1-transform (values :failure args)))
988 (defun abort-ir1-transform (&rest args)
989   (throw 'give-up-ir1-transform (values :aborted args)))
990 (defun delay-ir1-transform (node &rest reasons)
991   (let ((assoc (assoc node *delayed-ir1-transforms*)))
992     (cond ((not assoc)
993             (setf *delayed-ir1-transforms*
994                     (acons node reasons *delayed-ir1-transforms*))
995             (throw 'give-up-ir1-transform :delayed))
996           ((cdr assoc)
997             (dolist (reason reasons)
998               (pushnew reason (cdr assoc)))
999             (throw 'give-up-ir1-transform :delayed)))))
1000
1001 ;;; Clear any delayed transform with no reasons - these should have
1002 ;;; been tried in the last pass. Then remove the reason from the
1003 ;;; delayed transform reasons, and if any become empty then set
1004 ;;; reoptimize flags for the node. Return true if any transforms are
1005 ;;; to be retried.
1006 (defun retry-delayed-ir1-transforms (reason)
1007   (setf *delayed-ir1-transforms*
1008         (remove-if-not #'cdr *delayed-ir1-transforms*))
1009   (let ((reoptimize nil))
1010     (dolist (assoc *delayed-ir1-transforms*)
1011       (let ((reasons (remove reason (cdr assoc))))
1012         (setf (cdr assoc) reasons)
1013         (unless reasons
1014           (let ((node (car assoc)))
1015             (unless (node-deleted node)
1016               (setf reoptimize t)
1017               (setf (node-reoptimize node) t)
1018               (let ((block (node-block node)))
1019                 (setf (block-reoptimize block) t)
1020                 (setf (component-reoptimize (block-component block)) t)))))))
1021     reoptimize))
1022
1023 ;;; Take the lambda-expression RES, IR1 convert it in the proper
1024 ;;; environment, and then install it as the function for the call
1025 ;;; NODE. We do local call analysis so that the new function is
1026 ;;; integrated into the control flow.
1027 ;;;
1028 ;;; We require the original function source name in order to generate
1029 ;;; a meaningful debug name for the lambda we set up. (It'd be
1030 ;;; possible to do this starting from debug names as well as source
1031 ;;; names, but as of sbcl-0.7.1.5, there was no need for this
1032 ;;; generality, since source names are always known to our callers.)
1033 (defun transform-call (call res source-name)
1034   (declare (type combination call) (list res))
1035   (aver (and (legal-fun-name-p source-name)
1036              (not (eql source-name '.anonymous.))))
1037   (node-ends-block call)
1038   (with-ir1-environment-from-node call
1039     (with-component-last-block (*current-component*
1040                                 (block-next (node-block call)))
1041       (let ((new-fun (ir1-convert-inline-lambda
1042                       res
1043                       :debug-name (debug-namify "LAMBDA-inlined ~A"
1044                                                 (as-debug-name
1045                                                  source-name
1046                                                  "<unknown function>"))))
1047             (ref (lvar-use (combination-fun call))))
1048         (change-ref-leaf ref new-fun)
1049         (setf (combination-kind call) :full)
1050         (locall-analyze-component *current-component*))))
1051   (values))
1052
1053 ;;; Replace a call to a foldable function of constant arguments with
1054 ;;; the result of evaluating the form. If there is an error during the
1055 ;;; evaluation, we give a warning and leave the call alone, making the
1056 ;;; call a :ERROR call.
1057 ;;;
1058 ;;; If there is more than one value, then we transform the call into a
1059 ;;; VALUES form.
1060 (defun constant-fold-call (call)
1061   (let ((args (mapcar #'lvar-value (combination-args call)))
1062         (fun-name (combination-fun-source-name call)))
1063     (multiple-value-bind (values win)
1064         (careful-call fun-name
1065                       args
1066                       call
1067                       ;; Note: CMU CL had COMPILER-WARN here, and that
1068                       ;; seems more natural, but it's probably not.
1069                       ;;
1070                       ;; It's especially not while bug 173 exists:
1071                       ;; Expressions like
1072                       ;;   (COND (END
1073                       ;;          (UNLESS (OR UNSAFE? (<= END SIZE)))
1074                       ;;            ...))
1075                       ;; can cause constant-folding TYPE-ERRORs (in
1076                       ;; #'<=) when END can be proved to be NIL, even
1077                       ;; though the code is perfectly legal and safe
1078                       ;; because a NIL value of END means that the
1079                       ;; #'<= will never be executed.
1080                       ;;
1081                       ;; Moreover, even without bug 173,
1082                       ;; quite-possibly-valid code like
1083                       ;;   (COND ((NONINLINED-PREDICATE END)
1084                       ;;          (UNLESS (<= END SIZE))
1085                       ;;            ...))
1086                       ;; (where NONINLINED-PREDICATE is something the
1087                       ;; compiler can't do at compile time, but which
1088                       ;; turns out to make the #'<= expression
1089                       ;; unreachable when END=NIL) could cause errors
1090                       ;; when the compiler tries to constant-fold (<=
1091                       ;; END SIZE).
1092                       ;;
1093                       ;; So, with or without bug 173, it'd be
1094                       ;; unnecessarily evil to do a full
1095                       ;; COMPILER-WARNING (and thus return FAILURE-P=T
1096                       ;; from COMPILE-FILE) for legal code, so we we
1097                       ;; use a wimpier COMPILE-STYLE-WARNING instead.
1098                       #'compiler-style-warn
1099                       "constant folding")
1100       (cond ((not win)
1101              (setf (combination-kind call) :error))
1102             ((and (proper-list-of-length-p values 1))
1103              (with-ir1-environment-from-node call
1104                (let* ((lvar (node-lvar call))
1105                       (prev (node-prev call))
1106                       (intermediate-ctran (make-ctran)))
1107                  (%delete-lvar-use call)
1108                  (setf (ctran-next prev) nil)
1109                  (setf (node-prev call) nil)
1110                  (reference-constant prev intermediate-ctran lvar
1111                                      (first values))
1112                  (link-node-to-previous-ctran call intermediate-ctran)
1113                  (reoptimize-lvar lvar)
1114                  (flush-combination call))))
1115             (t (let ((dummies (make-gensym-list (length args))))
1116                  (transform-call
1117                   call
1118                   `(lambda ,dummies
1119                      (declare (ignore ,@dummies))
1120                      (values ,@(mapcar (lambda (x) `',x) values)))
1121                   fun-name))))))
1122   (values))
1123 \f
1124 ;;;; local call optimization
1125
1126 ;;; Propagate TYPE to LEAF and its REFS, marking things changed. If
1127 ;;; the leaf type is a function type, then just leave it alone, since
1128 ;;; TYPE is never going to be more specific than that (and
1129 ;;; TYPE-INTERSECTION would choke.)
1130 (defun propagate-to-refs (leaf type)
1131   (declare (type leaf leaf) (type ctype type))
1132   (let ((var-type (leaf-type leaf)))
1133     (unless (fun-type-p var-type)
1134       (let ((int (type-approx-intersection2 var-type type)))
1135         (when (type/= int var-type)
1136           (setf (leaf-type leaf) int)
1137           (dolist (ref (leaf-refs leaf))
1138             (derive-node-type ref (make-single-value-type int))
1139             ;; KLUDGE: LET var substitution
1140             (let* ((lvar (node-lvar ref)))
1141               (when (and lvar (combination-p (lvar-dest lvar)))
1142                 (reoptimize-lvar lvar))))))
1143       (values))))
1144
1145 ;;; Iteration variable: exactly one SETQ of the form:
1146 ;;;
1147 ;;; (let ((var initial))
1148 ;;;   ...
1149 ;;;   (setq var (+ var step))
1150 ;;;   ...)
1151 (defun maybe-infer-iteration-var-type (var initial-type)
1152   (binding* ((sets (lambda-var-sets var) :exit-if-null)
1153              (set (first sets))
1154              (() (null (rest sets)) :exit-if-null)
1155              (set-use (principal-lvar-use (set-value set)))
1156              (() (and (combination-p set-use)
1157                       (fun-info-p (combination-kind set-use))
1158                       (eq (combination-fun-source-name set-use) '+))
1159                :exit-if-null)
1160              (+-args (basic-combination-args set-use))
1161              (() (and (proper-list-of-length-p +-args 2 2)
1162                       (let ((first (principal-lvar-use
1163                                     (first +-args))))
1164                         (and (ref-p first)
1165                              (eq (ref-leaf first) var))))
1166                :exit-if-null)
1167              (step-type (lvar-type (second +-args)))
1168              (set-type (lvar-type (set-value set))))
1169     (when (and (numeric-type-p initial-type)
1170                (numeric-type-p step-type)
1171                (numeric-type-equal initial-type step-type))
1172       (multiple-value-bind (low high)
1173           (cond ((csubtypep step-type (specifier-type '(real 0 *)))
1174                  (values (numeric-type-low initial-type)
1175                          (when (and (numeric-type-p set-type)
1176                                     (numeric-type-equal set-type initial-type))
1177                            (numeric-type-high set-type))))
1178                 ((csubtypep step-type (specifier-type '(real * 0)))
1179                  (values (when (and (numeric-type-p set-type)
1180                                     (numeric-type-equal set-type initial-type))
1181                            (numeric-type-low set-type))
1182                          (numeric-type-high initial-type)))
1183                 (t
1184                  (values nil nil)))
1185         (modified-numeric-type initial-type
1186                                :low low
1187                                :high high
1188                                :enumerable nil)))))
1189 (deftransform + ((x y) * * :result result)
1190   "check for iteration variable reoptimization"
1191   (let ((dest (principal-lvar-end result))
1192         (use (principal-lvar-use x)))
1193     (when (and (ref-p use)
1194                (set-p dest)
1195                (eq (ref-leaf use)
1196                    (set-var dest)))
1197       (reoptimize-lvar (set-value dest))))
1198   (give-up-ir1-transform))
1199
1200 ;;; Figure out the type of a LET variable that has sets. We compute
1201 ;;; the union of the INITIAL-TYPE and the types of all the set
1202 ;;; values and to a PROPAGATE-TO-REFS with this type.
1203 (defun propagate-from-sets (var initial-type)
1204   (collect ((res initial-type type-union))
1205     (dolist (set (basic-var-sets var))
1206       (let ((type (lvar-type (set-value set))))
1207         (res type)
1208         (when (node-reoptimize set)
1209           (derive-node-type set (make-single-value-type type))
1210           (setf (node-reoptimize set) nil))))
1211     (let ((res (res)))
1212       (awhen (maybe-infer-iteration-var-type var initial-type)
1213         (setq res it))
1214       (propagate-to-refs var res)))
1215   (values))
1216
1217 ;;; If a LET variable, find the initial value's type and do
1218 ;;; PROPAGATE-FROM-SETS. We also derive the VALUE's type as the node's
1219 ;;; type.
1220 (defun ir1-optimize-set (node)
1221   (declare (type cset node))
1222   (let ((var (set-var node)))
1223     (when (and (lambda-var-p var) (leaf-refs var))
1224       (let ((home (lambda-var-home var)))
1225         (when (eq (functional-kind home) :let)
1226           (let* ((initial-value (let-var-initial-value var))
1227                  (initial-type (lvar-type initial-value)))
1228             (setf (lvar-reoptimize initial-value) nil)
1229             (propagate-from-sets var initial-type))))))
1230
1231   (derive-node-type node (make-single-value-type
1232                           (lvar-type (set-value node))))
1233   (values))
1234
1235 ;;; Return true if the value of REF will always be the same (and is
1236 ;;; thus legal to substitute.)
1237 (defun constant-reference-p (ref)
1238   (declare (type ref ref))
1239   (let ((leaf (ref-leaf ref)))
1240     (typecase leaf
1241       ((or constant functional) t)
1242       (lambda-var
1243        (null (lambda-var-sets leaf)))
1244       (defined-fun
1245        (not (eq (defined-fun-inlinep leaf) :notinline)))
1246       (global-var
1247        (case (global-var-kind leaf)
1248          (:global-function
1249           (let ((name (leaf-source-name leaf)))
1250             (or #-sb-xc-host
1251                 (eq (symbol-package (fun-name-block-name name))
1252                     *cl-package*)
1253                 (info :function :info name)))))))))
1254
1255 ;;; If we have a non-set LET var with a single use, then (if possible)
1256 ;;; replace the variable reference's LVAR with the arg lvar.
1257 ;;;
1258 ;;; We change the REF to be a reference to NIL with unused value, and
1259 ;;; let it be flushed as dead code. A side effect of this substitution
1260 ;;; is to delete the variable.
1261 (defun substitute-single-use-lvar (arg var)
1262   (declare (type lvar arg) (type lambda-var var))
1263   (binding* ((ref (first (leaf-refs var)))
1264              (lvar (node-lvar ref) :exit-if-null)
1265              (dest (lvar-dest lvar)))
1266     (when (and
1267            ;; Think about (LET ((A ...)) (IF ... A ...)): two
1268            ;; LVAR-USEs should not be met on one path.
1269            (eq (lvar-uses lvar) ref)
1270            (typecase dest
1271              ;; we should not change lifetime of unknown values lvars
1272              (cast
1273               (and (type-single-value-p (lvar-derived-type arg))
1274                    (multiple-value-bind (pdest pprev)
1275                        (principal-lvar-end lvar)
1276                      (declare (ignore pdest))
1277                      (lvar-single-value-p pprev))))
1278              (mv-combination
1279               (or (eq (basic-combination-fun dest) lvar)
1280                   (and (eq (basic-combination-kind dest) :local)
1281                        (type-single-value-p (lvar-derived-type arg)))))
1282              ((or creturn exit)
1283               ;; While CRETURN and EXIT nodes may be known-values,
1284               ;; they have their own complications, such as
1285               ;; substitution into CRETURN may create new tail calls.
1286               nil)
1287              (t
1288               (aver (lvar-single-value-p lvar))
1289               t))
1290            (eq (node-home-lambda ref)
1291                (lambda-home (lambda-var-home var))))
1292       (setf (node-derived-type ref) *wild-type*)
1293       (substitute-lvar-uses lvar arg)
1294       (delete-lvar-use ref)
1295       (change-ref-leaf ref (find-constant nil))
1296       (delete-ref ref)
1297       (unlink-node ref)
1298       (reoptimize-lvar lvar)
1299       t)))
1300
1301 ;;; Delete a LET, removing the call and bind nodes, and warning about
1302 ;;; any unreferenced variables. Note that FLUSH-DEAD-CODE will come
1303 ;;; along right away and delete the REF and then the lambda, since we
1304 ;;; flush the FUN lvar.
1305 (defun delete-let (clambda)
1306   (declare (type clambda clambda))
1307   (aver (functional-letlike-p clambda))
1308   (note-unreferenced-vars clambda)
1309   (let ((call (let-combination clambda)))
1310     (flush-dest (basic-combination-fun call))
1311     (unlink-node call)
1312     (unlink-node (lambda-bind clambda))
1313     (setf (lambda-bind clambda) nil))
1314   (values))
1315
1316 ;;; This function is called when one of the arguments to a LET
1317 ;;; changes. We look at each changed argument. If the corresponding
1318 ;;; variable is set, then we call PROPAGATE-FROM-SETS. Otherwise, we
1319 ;;; consider substituting for the variable, and also propagate
1320 ;;; derived-type information for the arg to all the VAR's refs.
1321 ;;;
1322 ;;; Substitution is inhibited when the arg leaf's derived type isn't a
1323 ;;; subtype of the argument's leaf type. This prevents type checking
1324 ;;; from being defeated, and also ensures that the best representation
1325 ;;; for the variable can be used.
1326 ;;;
1327 ;;; Substitution of individual references is inhibited if the
1328 ;;; reference is in a different component from the home. This can only
1329 ;;; happen with closures over top level lambda vars. In such cases,
1330 ;;; the references may have already been compiled, and thus can't be
1331 ;;; retroactively modified.
1332 ;;;
1333 ;;; If all of the variables are deleted (have no references) when we
1334 ;;; are done, then we delete the LET.
1335 ;;;
1336 ;;; Note that we are responsible for clearing the LVAR-REOPTIMIZE
1337 ;;; flags.
1338 (defun propagate-let-args (call fun)
1339   (declare (type combination call) (type clambda fun))
1340   (loop for arg in (combination-args call)
1341         and var in (lambda-vars fun) do
1342     (when (and arg (lvar-reoptimize arg))
1343       (setf (lvar-reoptimize arg) nil)
1344       (cond
1345         ((lambda-var-sets var)
1346          (propagate-from-sets var (lvar-type arg)))
1347         ((let ((use (lvar-uses arg)))
1348            (when (ref-p use)
1349              (let ((leaf (ref-leaf use)))
1350                (when (and (constant-reference-p use)
1351                           (csubtypep (leaf-type leaf)
1352                                      ;; (NODE-DERIVED-TYPE USE) would
1353                                      ;; be better -- APD, 2003-05-15
1354                                      (leaf-type var)))
1355                  (propagate-to-refs var (lvar-type arg))
1356                  (let ((use-component (node-component use)))
1357                    (prog1 (substitute-leaf-if
1358                            (lambda (ref)
1359                              (cond ((eq (node-component ref) use-component)
1360                                     t)
1361                                    (t
1362                                     (aver (lambda-toplevelish-p (lambda-home fun)))
1363                                     nil)))
1364                            leaf var)))
1365                  t)))))
1366         ((and (null (rest (leaf-refs var)))
1367               (substitute-single-use-lvar arg var)))
1368         (t
1369          (propagate-to-refs var (lvar-type arg))))))
1370
1371   (when (every #'not (combination-args call))
1372     (delete-let fun))
1373
1374   (values))
1375
1376 ;;; This function is called when one of the args to a non-LET local
1377 ;;; call changes. For each changed argument corresponding to an unset
1378 ;;; variable, we compute the union of the types across all calls and
1379 ;;; propagate this type information to the var's refs.
1380 ;;;
1381 ;;; If the function has an XEP, then we don't do anything, since we
1382 ;;; won't discover anything.
1383 ;;;
1384 ;;; We can clear the LVAR-REOPTIMIZE flags for arguments in all calls
1385 ;;; corresponding to changed arguments in CALL, since the only use in
1386 ;;; IR1 optimization of the REOPTIMIZE flag for local call args is
1387 ;;; right here.
1388 (defun propagate-local-call-args (call fun)
1389   (declare (type combination call) (type clambda fun))
1390
1391   (unless (or (functional-entry-fun fun)
1392               (lambda-optional-dispatch fun))
1393     (let* ((vars (lambda-vars fun))
1394            (union (mapcar (lambda (arg var)
1395                             (when (and arg
1396                                        (lvar-reoptimize arg)
1397                                        (null (basic-var-sets var)))
1398                               (lvar-type arg)))
1399                           (basic-combination-args call)
1400                           vars))
1401            (this-ref (lvar-use (basic-combination-fun call))))
1402
1403       (dolist (arg (basic-combination-args call))
1404         (when arg
1405           (setf (lvar-reoptimize arg) nil)))
1406
1407       (dolist (ref (leaf-refs fun))
1408         (let ((dest (node-dest ref)))
1409           (unless (or (eq ref this-ref) (not dest))
1410             (setq union
1411                   (mapcar (lambda (this-arg old)
1412                             (when old
1413                               (setf (lvar-reoptimize this-arg) nil)
1414                               (type-union (lvar-type this-arg) old)))
1415                           (basic-combination-args dest)
1416                           union)))))
1417
1418       (loop for var in vars
1419             and type in union
1420             when type do (propagate-to-refs var type))))
1421
1422   (values))
1423 \f
1424 ;;;; multiple values optimization
1425
1426 ;;; Do stuff to notice a change to a MV combination node. There are
1427 ;;; two main branches here:
1428 ;;;  -- If the call is local, then it is already a MV let, or should
1429 ;;;     become one. Note that although all :LOCAL MV calls must eventually
1430 ;;;     be converted to :MV-LETs, there can be a window when the call
1431 ;;;     is local, but has not been LET converted yet. This is because
1432 ;;;     the entry-point lambdas may have stray references (in other
1433 ;;;     entry points) that have not been deleted yet.
1434 ;;;  -- The call is full. This case is somewhat similar to the non-MV
1435 ;;;     combination optimization: we propagate return type information and
1436 ;;;     notice non-returning calls. We also have an optimization
1437 ;;;     which tries to convert MV-CALLs into MV-binds.
1438 (defun ir1-optimize-mv-combination (node)
1439   (ecase (basic-combination-kind node)
1440     (:local
1441      (let ((fun-lvar (basic-combination-fun node)))
1442        (when (lvar-reoptimize fun-lvar)
1443          (setf (lvar-reoptimize fun-lvar) nil)
1444          (maybe-let-convert (combination-lambda node))))
1445      (setf (lvar-reoptimize (first (basic-combination-args node))) nil)
1446      (when (eq (functional-kind (combination-lambda node)) :mv-let)
1447        (unless (convert-mv-bind-to-let node)
1448          (ir1-optimize-mv-bind node))))
1449     (:full
1450      (let* ((fun (basic-combination-fun node))
1451             (fun-changed (lvar-reoptimize fun))
1452             (args (basic-combination-args node)))
1453        (when fun-changed
1454          (setf (lvar-reoptimize fun) nil)
1455          (let ((type (lvar-type fun)))
1456            (when (fun-type-p type)
1457              (derive-node-type node (fun-type-returns type))))
1458          (maybe-terminate-block node nil)
1459          (let ((use (lvar-uses fun)))
1460            (when (and (ref-p use) (functional-p (ref-leaf use)))
1461              (convert-call-if-possible use node)
1462              (when (eq (basic-combination-kind node) :local)
1463                (maybe-let-convert (ref-leaf use))))))
1464        (unless (or (eq (basic-combination-kind node) :local)
1465                    (eq (lvar-fun-name fun) '%throw))
1466          (ir1-optimize-mv-call node))
1467        (dolist (arg args)
1468          (setf (lvar-reoptimize arg) nil))))
1469     (:error))
1470   (values))
1471
1472 ;;; Propagate derived type info from the values lvar to the vars.
1473 (defun ir1-optimize-mv-bind (node)
1474   (declare (type mv-combination node))
1475   (let* ((arg (first (basic-combination-args node)))
1476          (vars (lambda-vars (combination-lambda node)))
1477          (n-vars (length vars))
1478          (types (values-type-in (lvar-derived-type arg)
1479                                 n-vars)))
1480     (loop for var in vars
1481           and type in types
1482           do (if (basic-var-sets var)
1483                  (propagate-from-sets var type)
1484                  (propagate-to-refs var type)))
1485     (setf (lvar-reoptimize arg) nil))
1486   (values))
1487
1488 ;;; If possible, convert a general MV call to an MV-BIND. We can do
1489 ;;; this if:
1490 ;;; -- The call has only one argument, and
1491 ;;; -- The function has a known fixed number of arguments, or
1492 ;;; -- The argument yields a known fixed number of values.
1493 ;;;
1494 ;;; What we do is change the function in the MV-CALL to be a lambda
1495 ;;; that "looks like an MV bind", which allows
1496 ;;; IR1-OPTIMIZE-MV-COMBINATION to notice that this call can be
1497 ;;; converted (the next time around.) This new lambda just calls the
1498 ;;; actual function with the MV-BIND variables as arguments. Note that
1499 ;;; this new MV bind is not let-converted immediately, as there are
1500 ;;; going to be stray references from the entry-point functions until
1501 ;;; they get deleted.
1502 ;;;
1503 ;;; In order to avoid loss of argument count checking, we only do the
1504 ;;; transformation according to a known number of expected argument if
1505 ;;; safety is unimportant. We can always convert if we know the number
1506 ;;; of actual values, since the normal call that we build will still
1507 ;;; do any appropriate argument count checking.
1508 ;;;
1509 ;;; We only attempt the transformation if the called function is a
1510 ;;; constant reference. This allows us to just splice the leaf into
1511 ;;; the new function, instead of trying to somehow bind the function
1512 ;;; expression. The leaf must be constant because we are evaluating it
1513 ;;; again in a different place. This also has the effect of squelching
1514 ;;; multiple warnings when there is an argument count error.
1515 (defun ir1-optimize-mv-call (node)
1516   (let ((fun (basic-combination-fun node))
1517         (*compiler-error-context* node)
1518         (ref (lvar-uses (basic-combination-fun node)))
1519         (args (basic-combination-args node)))
1520
1521     (unless (and (ref-p ref) (constant-reference-p ref)
1522                  (singleton-p args))
1523       (return-from ir1-optimize-mv-call))
1524
1525     (multiple-value-bind (min max)
1526         (fun-type-nargs (lvar-type fun))
1527       (let ((total-nvals
1528              (multiple-value-bind (types nvals)
1529                  (values-types (lvar-derived-type (first args)))
1530                (declare (ignore types))
1531                (if (eq nvals :unknown) nil nvals))))
1532
1533         (when total-nvals
1534           (when (and min (< total-nvals min))
1535             (compiler-warn
1536              "MULTIPLE-VALUE-CALL with ~R values when the function expects ~
1537              at least ~R."
1538              total-nvals min)
1539             (setf (basic-combination-kind node) :error)
1540             (return-from ir1-optimize-mv-call))
1541           (when (and max (> total-nvals max))
1542             (compiler-warn
1543              "MULTIPLE-VALUE-CALL with ~R values when the function expects ~
1544              at most ~R."
1545              total-nvals max)
1546             (setf (basic-combination-kind node) :error)
1547             (return-from ir1-optimize-mv-call)))
1548
1549         (let ((count (cond (total-nvals)
1550                            ((and (policy node (zerop verify-arg-count))
1551                                  (eql min max))
1552                             min)
1553                            (t nil))))
1554           (when count
1555             (with-ir1-environment-from-node node
1556               (let* ((dums (make-gensym-list count))
1557                      (ignore (gensym))
1558                      (fun (ir1-convert-lambda
1559                            `(lambda (&optional ,@dums &rest ,ignore)
1560                               (declare (ignore ,ignore))
1561                               (funcall ,(ref-leaf ref) ,@dums)))))
1562                 (change-ref-leaf ref fun)
1563                 (aver (eq (basic-combination-kind node) :full))
1564                 (locall-analyze-component *current-component*)
1565                 (aver (eq (basic-combination-kind node) :local)))))))))
1566   (values))
1567
1568 ;;; If we see:
1569 ;;;    (multiple-value-bind
1570 ;;;     (x y)
1571 ;;;     (values xx yy)
1572 ;;;      ...)
1573 ;;; Convert to:
1574 ;;;    (let ((x xx)
1575 ;;;       (y yy))
1576 ;;;      ...)
1577 ;;;
1578 ;;; What we actually do is convert the VALUES combination into a
1579 ;;; normal LET combination calling the original :MV-LET lambda. If
1580 ;;; there are extra args to VALUES, discard the corresponding
1581 ;;; lvars. If there are insufficient args, insert references to NIL.
1582 (defun convert-mv-bind-to-let (call)
1583   (declare (type mv-combination call))
1584   (let* ((arg (first (basic-combination-args call)))
1585          (use (lvar-uses arg)))
1586     (when (and (combination-p use)
1587                (eq (lvar-fun-name (combination-fun use))
1588                    'values))
1589       (let* ((fun (combination-lambda call))
1590              (vars (lambda-vars fun))
1591              (vals (combination-args use))
1592              (nvars (length vars))
1593              (nvals (length vals)))
1594         (cond ((> nvals nvars)
1595                (mapc #'flush-dest (subseq vals nvars))
1596                (setq vals (subseq vals 0 nvars)))
1597               ((< nvals nvars)
1598                (with-ir1-environment-from-node use
1599                  (let ((node-prev (node-prev use)))
1600                    (setf (node-prev use) nil)
1601                    (setf (ctran-next node-prev) nil)
1602                    (collect ((res vals))
1603                      (loop for count below (- nvars nvals)
1604                            for prev = node-prev then ctran
1605                            for ctran = (make-ctran)
1606                            and lvar = (make-lvar use)
1607                            do (reference-constant prev ctran lvar nil)
1608                               (res lvar)
1609                            finally (link-node-to-previous-ctran
1610                                     use ctran))
1611                      (setq vals (res)))))))
1612         (setf (combination-args use) vals)
1613         (flush-dest (combination-fun use))
1614         (let ((fun-lvar (basic-combination-fun call)))
1615           (setf (lvar-dest fun-lvar) use)
1616           (setf (combination-fun use) fun-lvar)
1617           (flush-lvar-externally-checkable-type fun-lvar))
1618         (setf (combination-kind use) :local)
1619         (setf (functional-kind fun) :let)
1620         (flush-dest (first (basic-combination-args call)))
1621         (unlink-node call)
1622         (when vals
1623           (reoptimize-lvar (first vals)))
1624         (propagate-to-args use fun)
1625         (reoptimize-call use))
1626       t)))
1627
1628 ;;; If we see:
1629 ;;;    (values-list (list x y z))
1630 ;;;
1631 ;;; Convert to:
1632 ;;;    (values x y z)
1633 ;;;
1634 ;;; In implementation, this is somewhat similar to
1635 ;;; CONVERT-MV-BIND-TO-LET. We grab the args of LIST and make them
1636 ;;; args of the VALUES-LIST call, flushing the old argument lvar
1637 ;;; (allowing the LIST to be flushed.)
1638 ;;;
1639 ;;; FIXME: Thus we lose possible type assertions on (LIST ...).
1640 (defoptimizer (values-list optimizer) ((list) node)
1641   (let ((use (lvar-uses list)))
1642     (when (and (combination-p use)
1643                (eq (lvar-fun-name (combination-fun use))
1644                    'list))
1645
1646       ;; FIXME: VALUES might not satisfy an assertion on NODE-LVAR.
1647       (change-ref-leaf (lvar-uses (combination-fun node))
1648                        (find-free-fun 'values "in a strange place"))
1649       (setf (combination-kind node) :full)
1650       (let ((args (combination-args use)))
1651         (dolist (arg args)
1652           (setf (lvar-dest arg) node)
1653           (flush-lvar-externally-checkable-type arg))
1654         (setf (combination-args use) nil)
1655         (flush-dest list)
1656         (setf (combination-args node) args))
1657       t)))
1658
1659 ;;; If VALUES appears in a non-MV context, then effectively convert it
1660 ;;; to a PROG1. This allows the computation of the additional values
1661 ;;; to become dead code.
1662 (deftransform values ((&rest vals) * * :node node)
1663   (unless (lvar-single-value-p (node-lvar node))
1664     (give-up-ir1-transform))
1665   (setf (node-derived-type node) *wild-type*)
1666   (principal-lvar-single-valuify (node-lvar node))
1667   (if vals
1668       (let ((dummies (make-gensym-list (length (cdr vals)))))
1669         `(lambda (val ,@dummies)
1670            (declare (ignore ,@dummies))
1671            val))
1672       nil))
1673
1674 ;;; TODO:
1675 ;;; - CAST chains;
1676 (defun ir1-optimize-cast (cast &optional do-not-optimize)
1677   (declare (type cast cast))
1678   (let* ((value (cast-value cast))
1679          (value-type (lvar-derived-type value))
1680          (atype (cast-asserted-type cast))
1681          (int (values-type-intersection value-type atype)))
1682     (derive-node-type cast int)
1683     (when (eq int *empty-type*)
1684       (unless (eq value-type *empty-type*)
1685
1686         ;; FIXME: Do it in one step.
1687         (filter-lvar
1688          value
1689          `(multiple-value-call #'list 'dummy))
1690         (filter-lvar
1691          (cast-value cast)
1692          ;; FIXME: Derived type.
1693          `(%compile-time-type-error 'dummy
1694                                     ',(type-specifier atype)
1695                                     ',(type-specifier value-type)))
1696         ;; KLUDGE: FILTER-LVAR does not work for non-returning
1697         ;; functions, so we declare the return type of
1698         ;; %COMPILE-TIME-TYPE-ERROR to be * and derive the real type
1699         ;; here.
1700         (setq value (cast-value cast))
1701         (derive-node-type (lvar-uses value) *empty-type*)
1702         (maybe-terminate-block (lvar-uses value) nil)
1703         ;; FIXME: Is it necessary?
1704         (aver (null (block-pred (node-block cast))))
1705         (setf (block-delete-p (node-block cast)) t)
1706         (return-from ir1-optimize-cast)))
1707     (when (eq (node-derived-type cast) *empty-type*)
1708       (maybe-terminate-block cast nil))
1709
1710     (when (not do-not-optimize)
1711       (let ((lvar (node-lvar cast)))
1712         (when (values-subtypep value-type (cast-asserted-type cast))
1713           (delete-filter cast lvar value)
1714           (when lvar
1715             (reoptimize-lvar lvar)
1716             (when (lvar-single-value-p lvar)
1717               (note-single-valuified-lvar lvar)))
1718           (return-from ir1-optimize-cast t))
1719
1720         (when (and (listp (lvar-uses value))
1721                    lvar)
1722           ;; Pathwise removing of CAST
1723           (let ((ctran (node-next cast))
1724                 (dest (lvar-dest lvar))
1725                 next-block)
1726             (collect ((merges))
1727               (do-uses (use value)
1728                 (when (and (values-subtypep (node-derived-type use) atype)
1729                            (immediately-used-p value use))
1730                   (unless next-block
1731                     (when ctran (ensure-block-start ctran))
1732                     (setq next-block (first (block-succ (node-block cast)))))
1733                   (%delete-lvar-use use)
1734                   (add-lvar-use use lvar)
1735                   (unlink-blocks (node-block use) (node-block cast))
1736                   (link-blocks (node-block use) next-block)
1737                   (when (and (return-p dest)
1738                              (basic-combination-p use)
1739                              (eq (basic-combination-kind use) :local))
1740                     (merges use))))
1741               (dolist (use (merges))
1742                 (merge-tail-sets use)))))))
1743
1744     (when (and (cast-%type-check cast)
1745                (values-subtypep value-type
1746                                 (cast-type-to-check cast)))
1747       (setf (cast-%type-check cast) nil)))
1748
1749   (unless do-not-optimize
1750     (setf (node-reoptimize cast) nil)))