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