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