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