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