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