0.8.0.74:
[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                     (fboundp (combination-fun-source-name node)))
757            (constant-fold-call node)
758            (return-from ir1-optimize-combination)))
759
760        (let ((fun (fun-info-derive-type kind)))
761          (when fun
762            (let ((res (funcall fun node)))
763              (when res
764                (derive-node-type node (coerce-to-values res))
765                (maybe-terminate-block node nil)))))
766
767        (let ((fun (fun-info-optimizer kind)))
768          (unless (and fun (funcall fun node))
769            (dolist (x (fun-info-transforms kind))
770              #!+sb-show
771              (when *show-transforms-p*
772                (let* ((cont (basic-combination-fun node))
773                       (fname (continuation-fun-name cont t)))
774                  (/show "trying transform" x (transform-function x) "for" fname)))
775              (unless (ir1-transform node x)
776                #!+sb-show
777                (when *show-transforms-p*
778                  (/show "quitting because IR1-TRANSFORM result was NIL"))
779                (return))))))))
780
781   (values))
782
783 ;;; If NODE doesn't return (i.e. return type is NIL), then terminate
784 ;;; the block there, and link it to the component tail. We also change
785 ;;; the NODE's CONT to be a dummy continuation to prevent the use from
786 ;;; confusing things.
787 ;;;
788 ;;; Except when called during IR1 [FIXME: What does this mean? Except
789 ;;; during IR1 conversion? What about IR1 optimization?], we delete
790 ;;; the continuation if it has no other uses. (If it does have other
791 ;;; uses, we reoptimize.)
792 ;;;
793 ;;; Termination on the basis of a continuation type is
794 ;;; inhibited when:
795 ;;; -- The continuation is deleted (hence the assertion is spurious), or
796 ;;; -- We are in IR1 conversion (where THE assertions are subject to
797 ;;;    weakening.)
798 (defun maybe-terminate-block (node ir1-converting-not-optimizing-p)
799   (declare (type (or basic-combination cast) node))
800   (let* ((block (node-block node))
801          (cont (node-cont node))
802          (tail (component-tail (block-component block)))
803          (succ (first (block-succ block))))
804     (unless (or (and (eq node (block-last block)) (eq succ tail))
805                 (block-delete-p block))
806       (when (or (and (not (or ir1-converting-not-optimizing-p
807                               (eq (continuation-kind cont) :deleted)))
808                      (eq (continuation-derived-type cont) *empty-type*))
809                 (eq (node-derived-type node) *empty-type*))
810         (cond (ir1-converting-not-optimizing-p
811                (delete-continuation-use node)
812                (cond
813                 ((block-last block)
814                  (aver (and (eq (block-last block) node)
815                             (eq (continuation-kind cont) :block-start))))
816                 (t
817                  (setf (block-last block) node)
818                  (link-blocks block (continuation-starts-block cont)))))
819               (t
820                (node-ends-block node)
821                (delete-continuation-use node)
822                (if (eq (continuation-kind cont) :unused)
823                    (delete-continuation cont)
824                    (reoptimize-continuation cont))))
825
826         (unlink-blocks block (first (block-succ block)))
827         (setf (component-reanalyze (block-component block)) t)
828         (aver (not (block-succ block)))
829         (link-blocks block tail)
830         (add-continuation-use node (make-continuation))
831         t))))
832
833 ;;; This is called both by IR1 conversion and IR1 optimization when
834 ;;; they have verified the type signature for the call, and are
835 ;;; wondering if something should be done to special-case the call. If
836 ;;; CALL is a call to a global function, then see whether it defined
837 ;;; or known:
838 ;;; -- If a DEFINED-FUN should be inline expanded, then convert
839 ;;;    the expansion and change the call to call it. Expansion is
840 ;;;    enabled if :INLINE or if SPACE=0. If the FUNCTIONAL slot is
841 ;;;    true, we never expand, since this function has already been
842 ;;;    converted. Local call analysis will duplicate the definition
843 ;;;    if necessary. We claim that the parent form is LABELS for
844 ;;;    context declarations, since we don't want it to be considered
845 ;;;    a real global function.
846 ;;; -- If it is a known function, mark it as such by setting the KIND.
847 ;;;
848 ;;; We return the leaf referenced (NIL if not a leaf) and the
849 ;;; FUN-INFO assigned.
850 ;;;
851 ;;; FIXME: The IR1-CONVERTING-NOT-OPTIMIZING-P argument is what the
852 ;;; old CMU CL code called IR1-P, without explanation. My (WHN
853 ;;; 2002-01-09) tentative understanding of it is that we can call this
854 ;;; operation either in initial IR1 conversion or in later IR1
855 ;;; optimization, and it tells which is which. But it would be good
856 ;;; for someone who really understands it to check whether this is
857 ;;; really right.
858 (defun recognize-known-call (call ir1-converting-not-optimizing-p)
859   (declare (type combination call))
860   (let* ((ref (continuation-use (basic-combination-fun call)))
861          (leaf (when (ref-p ref) (ref-leaf ref)))
862          (inlinep (if (defined-fun-p leaf)
863                       (defined-fun-inlinep leaf)
864                       :no-chance)))
865     (cond
866      ((eq inlinep :notinline) (values nil nil))
867      ((not (and (global-var-p leaf)
868                 (eq (global-var-kind leaf) :global-function)))
869       (values leaf nil))
870      ((and (ecase inlinep
871              (:inline t)
872              (:no-chance nil)
873              ((nil :maybe-inline) (policy call (zerop space))))
874            (defined-fun-p leaf)
875            (defined-fun-inline-expansion leaf)
876            (let ((fun (defined-fun-functional leaf)))
877              (or (not fun)
878                  (and (eq inlinep :inline) (functional-kind fun))))
879            (inline-expansion-ok call))
880       (flet (;; FIXME: Is this what the old CMU CL internal documentation
881              ;; called semi-inlining? A more descriptive name would
882              ;; be nice. -- WHN 2002-01-07
883              (frob ()
884                (let ((res (ir1-convert-lambda-for-defun
885                            (defined-fun-inline-expansion leaf)
886                            leaf t
887                            #'ir1-convert-inline-lambda)))
888                  (setf (defined-fun-functional leaf) res)
889                  (change-ref-leaf ref res))))
890         (if ir1-converting-not-optimizing-p
891             (frob)
892             (with-ir1-environment-from-node call
893               (frob)
894               (locall-analyze-component *current-component*))))
895
896       (values (ref-leaf (continuation-use (basic-combination-fun call)))
897               nil))
898      (t
899       (let ((info (info :function :info (leaf-source-name leaf))))
900         (if info
901             (values leaf (setf (basic-combination-kind call) info))
902             (values leaf nil)))))))
903
904 ;;; Check whether CALL satisfies TYPE. If so, apply the type to the
905 ;;; call, and do MAYBE-TERMINATE-BLOCK and return the values of
906 ;;; RECOGNIZE-KNOWN-CALL. If an error, set the combination kind and
907 ;;; return NIL, NIL. If the type is just FUNCTION, then skip the
908 ;;; syntax check, arg/result type processing, but still call
909 ;;; RECOGNIZE-KNOWN-CALL, since the call might be to a known lambda,
910 ;;; and that checking is done by local call analysis.
911 (defun validate-call-type (call type ir1-converting-not-optimizing-p)
912   (declare (type combination call) (type ctype type))
913   (cond ((not (fun-type-p type))
914          (aver (multiple-value-bind (val win)
915                    (csubtypep type (specifier-type 'function))
916                  (or val (not win))))
917          (recognize-known-call call ir1-converting-not-optimizing-p))
918         ((valid-fun-use call type
919                         :argument-test #'always-subtypep
920                         :result-test #'always-subtypep
921                         ;; KLUDGE: Common Lisp is such a dynamic
922                         ;; language that all we can do here in
923                         ;; general is issue a STYLE-WARNING. It
924                         ;; would be nice to issue a full WARNING
925                         ;; in the special case of of type
926                         ;; mismatches within a compilation unit
927                         ;; (as in section 3.2.2.3 of the spec)
928                         ;; but at least as of sbcl-0.6.11, we
929                         ;; don't keep track of whether the
930                         ;; mismatched data came from the same
931                         ;; compilation unit, so we can't do that.
932                         ;; -- WHN 2001-02-11
933                         ;;
934                         ;; FIXME: Actually, I think we could
935                         ;; issue a full WARNING if the call
936                         ;; violates a DECLAIM FTYPE.
937                         :lossage-fun #'compiler-style-warn
938                         :unwinnage-fun #'compiler-notify)
939          (assert-call-type call type)
940          (maybe-terminate-block call ir1-converting-not-optimizing-p)
941          (recognize-known-call call ir1-converting-not-optimizing-p))
942         (t
943          (setf (combination-kind call) :error)
944          (values nil nil))))
945
946 ;;; This is called by IR1-OPTIMIZE when the function for a call has
947 ;;; changed. If the call is local, we try to LET-convert it, and
948 ;;; derive the result type. If it is a :FULL call, we validate it
949 ;;; against the type, which recognizes known calls, does inline
950 ;;; expansion, etc. If a call to a predicate in a non-conditional
951 ;;; position or to a function with a source transform, then we
952 ;;; reconvert the form to give IR1 another chance.
953 (defun propagate-fun-change (call)
954   (declare (type combination call))
955   (let ((*compiler-error-context* call)
956         (fun-cont (basic-combination-fun call)))
957     (setf (continuation-reoptimize fun-cont) nil)
958     (case (combination-kind call)
959       (:local
960        (let ((fun (combination-lambda call)))
961          (maybe-let-convert fun)
962          (unless (member (functional-kind fun) '(:let :assignment :deleted))
963            (derive-node-type call (tail-set-type (lambda-tail-set fun))))))
964       (:full
965        (multiple-value-bind (leaf info)
966            (validate-call-type call (continuation-type fun-cont) nil)
967          (cond ((functional-p leaf)
968                 (convert-call-if-possible
969                  (continuation-use (basic-combination-fun call))
970                  call))
971                ((not leaf))
972                ((and (leaf-has-source-name-p leaf)
973                      (or (info :function :source-transform (leaf-source-name leaf))
974                          (and info
975                               (ir1-attributep (fun-info-attributes info)
976                                               predicate)
977                               (let ((dest (continuation-dest (node-cont call))))
978                                 (and dest (not (if-p dest)))))))
979                 (let ((name (leaf-source-name leaf))
980                       (dummies (make-gensym-list
981                                 (length (combination-args call)))))
982                   (transform-call call
983                                   `(lambda ,dummies
984                                      (,@(if (symbolp name)
985                                             `(,name)
986                                             `(funcall #',name))
987                                         ,@dummies))
988                                   (leaf-source-name leaf)))))))))
989   (values))
990 \f
991 ;;;; known function optimization
992
993 ;;; Add a failed optimization note to FAILED-OPTIMZATIONS for NODE,
994 ;;; FUN and ARGS. If there is already a note for NODE and TRANSFORM,
995 ;;; replace it, otherwise add a new one.
996 (defun record-optimization-failure (node transform args)
997   (declare (type combination node) (type transform transform)
998            (type (or fun-type list) args))
999   (let* ((table (component-failed-optimizations *component-being-compiled*))
1000          (found (assoc transform (gethash node table))))
1001     (if found
1002         (setf (cdr found) args)
1003         (push (cons transform args) (gethash node table))))
1004   (values))
1005
1006 ;;; Attempt to transform NODE using TRANSFORM-FUNCTION, subject to the
1007 ;;; call type constraint TRANSFORM-TYPE. If we are inhibited from
1008 ;;; doing the transform for some reason and FLAME is true, then we
1009 ;;; make a note of the message in FAILED-OPTIMIZATIONS for IR1
1010 ;;; finalize to pick up. We return true if the transform failed, and
1011 ;;; thus further transformation should be attempted. We return false
1012 ;;; if either the transform succeeded or was aborted.
1013 (defun ir1-transform (node transform)
1014   (declare (type combination node) (type transform transform))
1015   (let* ((type (transform-type transform))
1016          (fun (transform-function transform))
1017          (constrained (fun-type-p type))
1018          (table (component-failed-optimizations *component-being-compiled*))
1019          (flame (if (transform-important transform)
1020                     (policy node (>= speed inhibit-warnings))
1021                     (policy node (> speed inhibit-warnings))))
1022          (*compiler-error-context* node))
1023     (cond ((or (not constrained)
1024                (valid-fun-use node type))
1025            (multiple-value-bind (severity args)
1026                (catch 'give-up-ir1-transform
1027                  (transform-call node
1028                                  (funcall fun node)
1029                                  (combination-fun-source-name node))
1030                  (values :none nil))
1031              (ecase severity
1032                (:none
1033                 (remhash node table)
1034                 nil)
1035                (:aborted
1036                 (setf (combination-kind node) :error)
1037                 (when args
1038                   (apply #'compiler-warn args))
1039                 (remhash node table)
1040                 nil)
1041                (:failure
1042                 (if args
1043                     (when flame
1044                       (record-optimization-failure node transform args))
1045                     (setf (gethash node table)
1046                           (remove transform (gethash node table) :key #'car)))
1047                 t)
1048                (:delayed
1049                  (remhash node table)
1050                  nil))))
1051           ((and flame
1052                 (valid-fun-use node
1053                                type
1054                                :argument-test #'types-equal-or-intersect
1055                                :result-test #'values-types-equal-or-intersect))
1056            (record-optimization-failure node transform type)
1057            t)
1058           (t
1059            t))))
1060
1061 ;;; When we don't like an IR1 transform, we throw the severity/reason
1062 ;;; and args. 
1063 ;;;
1064 ;;; GIVE-UP-IR1-TRANSFORM is used to throw out of an IR1 transform,
1065 ;;; aborting this attempt to transform the call, but admitting the
1066 ;;; possibility that this or some other transform will later succeed.
1067 ;;; If arguments are supplied, they are format arguments for an
1068 ;;; efficiency note.
1069 ;;;
1070 ;;; ABORT-IR1-TRANSFORM is used to throw out of an IR1 transform and
1071 ;;; force a normal call to the function at run time. No further
1072 ;;; optimizations will be attempted.
1073 ;;;
1074 ;;; DELAY-IR1-TRANSFORM is used to throw out of an IR1 transform, and
1075 ;;; delay the transform on the node until later. REASONS specifies
1076 ;;; when the transform will be later retried. The :OPTIMIZE reason
1077 ;;; causes the transform to be delayed until after the current IR1
1078 ;;; optimization pass. The :CONSTRAINT reason causes the transform to
1079 ;;; be delayed until after constraint propagation.
1080 ;;;
1081 ;;; FIXME: Now (0.6.11.44) that there are 4 variants of this (GIVE-UP,
1082 ;;; ABORT, DELAY/:OPTIMIZE, DELAY/:CONSTRAINT) and we're starting to
1083 ;;; do CASE operations on the various REASON values, it might be a
1084 ;;; good idea to go OO, representing the reasons by objects, using
1085 ;;; CLOS methods on the objects instead of CASE, and (possibly) using
1086 ;;; SIGNAL instead of THROW.
1087 (declaim (ftype (function (&rest t) nil) give-up-ir1-transform))
1088 (defun give-up-ir1-transform (&rest args)
1089   (throw 'give-up-ir1-transform (values :failure args)))
1090 (defun abort-ir1-transform (&rest args)
1091   (throw 'give-up-ir1-transform (values :aborted args)))
1092 (defun delay-ir1-transform (node &rest reasons)
1093   (let ((assoc (assoc node *delayed-ir1-transforms*)))
1094     (cond ((not assoc)
1095             (setf *delayed-ir1-transforms*
1096                     (acons node reasons *delayed-ir1-transforms*))
1097             (throw 'give-up-ir1-transform :delayed))
1098           ((cdr assoc)
1099             (dolist (reason reasons)
1100               (pushnew reason (cdr assoc)))
1101             (throw 'give-up-ir1-transform :delayed)))))
1102
1103 ;;; Clear any delayed transform with no reasons - these should have
1104 ;;; been tried in the last pass. Then remove the reason from the
1105 ;;; delayed transform reasons, and if any become empty then set
1106 ;;; reoptimize flags for the node. Return true if any transforms are
1107 ;;; to be retried.
1108 (defun retry-delayed-ir1-transforms (reason)
1109   (setf *delayed-ir1-transforms*
1110         (remove-if-not #'cdr *delayed-ir1-transforms*))
1111   (let ((reoptimize nil))
1112     (dolist (assoc *delayed-ir1-transforms*)
1113       (let ((reasons (remove reason (cdr assoc))))
1114         (setf (cdr assoc) reasons)
1115         (unless reasons
1116           (let ((node (car assoc)))
1117             (unless (node-deleted node)
1118               (setf reoptimize t)
1119               (setf (node-reoptimize node) t)
1120               (let ((block (node-block node)))
1121                 (setf (block-reoptimize block) t)
1122                 (setf (component-reoptimize (block-component block)) t)))))))
1123     reoptimize))
1124
1125 ;;; Take the lambda-expression RES, IR1 convert it in the proper
1126 ;;; environment, and then install it as the function for the call
1127 ;;; NODE. We do local call analysis so that the new function is
1128 ;;; integrated into the control flow.
1129 ;;;
1130 ;;; We require the original function source name in order to generate
1131 ;;; a meaningful debug name for the lambda we set up. (It'd be
1132 ;;; possible to do this starting from debug names as well as source
1133 ;;; names, but as of sbcl-0.7.1.5, there was no need for this
1134 ;;; generality, since source names are always known to our callers.)
1135 (defun transform-call (call res source-name)
1136   (declare (type combination call) (list res))
1137   (aver (and (legal-fun-name-p source-name)
1138              (not (eql source-name '.anonymous.))))
1139   (node-ends-block call)
1140   (with-ir1-environment-from-node call
1141     (with-component-last-block (*current-component*
1142                                 (block-next (node-block call)))
1143       (let ((new-fun (ir1-convert-inline-lambda
1144                       res
1145                       :debug-name (debug-namify "LAMBDA-inlined ~A"
1146                                                 (as-debug-name
1147                                                  source-name
1148                                                  "<unknown function>"))))
1149             (ref (continuation-use (combination-fun call))))
1150         (change-ref-leaf ref new-fun)
1151         (setf (combination-kind call) :full)
1152         (locall-analyze-component *current-component*))))
1153   (values))
1154
1155 ;;; Replace a call to a foldable function of constant arguments with
1156 ;;; the result of evaluating the form. If there is an error during the
1157 ;;; evaluation, we give a warning and leave the call alone, making the
1158 ;;; call a :ERROR call.
1159 ;;;
1160 ;;; If there is more than one value, then we transform the call into a
1161 ;;; VALUES form.
1162 ;;;
1163 ;;; An old commentary also said:
1164 ;;;
1165 ;;;   We insert the resulting constant node after the call, stealing
1166 ;;;   the call's continuation. We give the call a continuation with no
1167 ;;;   DEST, which should cause it and its arguments to go away.
1168 ;;;
1169 ;;; This seems to be more efficient, than the current code. Maybe we
1170 ;;; should really implement it? -- APD, 2002-12-23
1171 (defun constant-fold-call (call)
1172   (let ((args (mapcar #'continuation-value (combination-args call)))
1173         (fun-name (combination-fun-source-name call)))
1174     (multiple-value-bind (values win)
1175         (careful-call fun-name
1176                       args
1177                       call
1178                       ;; Note: CMU CL had COMPILER-WARN here, and that
1179                       ;; seems more natural, but it's probably not.
1180                       ;;
1181                       ;; It's especially not while bug 173 exists:
1182                       ;; Expressions like
1183                       ;;   (COND (END
1184                       ;;          (UNLESS (OR UNSAFE? (<= END SIZE)))
1185                       ;;            ...))
1186                       ;; can cause constant-folding TYPE-ERRORs (in
1187                       ;; #'<=) when END can be proved to be NIL, even
1188                       ;; though the code is perfectly legal and safe
1189                       ;; because a NIL value of END means that the
1190                       ;; #'<= will never be executed.
1191                       ;;
1192                       ;; Moreover, even without bug 173,
1193                       ;; quite-possibly-valid code like
1194                       ;;   (COND ((NONINLINED-PREDICATE END)
1195                       ;;          (UNLESS (<= END SIZE))
1196                       ;;            ...))
1197                       ;; (where NONINLINED-PREDICATE is something the
1198                       ;; compiler can't do at compile time, but which
1199                       ;; turns out to make the #'<= expression
1200                       ;; unreachable when END=NIL) could cause errors
1201                       ;; when the compiler tries to constant-fold (<=
1202                       ;; END SIZE).
1203                       ;;
1204                       ;; So, with or without bug 173, it'd be
1205                       ;; unnecessarily evil to do a full
1206                       ;; COMPILER-WARNING (and thus return FAILURE-P=T
1207                       ;; from COMPILE-FILE) for legal code, so we we
1208                       ;; use a wimpier COMPILE-STYLE-WARNING instead.
1209                       #'compiler-style-warn
1210                       "constant folding")
1211       (cond ((not win)
1212              (setf (combination-kind call) :error))
1213             ((and (proper-list-of-length-p values 1)
1214                   (eq (continuation-kind (node-cont call)) :inside-block))
1215              (with-ir1-environment-from-node call
1216                (let* ((cont (node-cont call))
1217                       (next (continuation-next cont))
1218                       (prev (make-continuation)))
1219                  (delete-continuation-use call)
1220                  (add-continuation-use call prev)
1221                  (reference-constant prev cont (first values))
1222                  (setf (continuation-next cont) next)
1223                  ;; FIXME: type checking?
1224                  (reoptimize-continuation cont)
1225                  (reoptimize-continuation prev)
1226                  (flush-combination call))))
1227             (t (let ((dummies (make-gensym-list (length args))))
1228                  (transform-call
1229                   call
1230                   `(lambda ,dummies
1231                      (declare (ignore ,@dummies))
1232                      (values ,@(mapcar (lambda (x) `',x) values)))
1233                   fun-name))))))
1234   (values))
1235 \f
1236 ;;;; local call optimization
1237
1238 ;;; Propagate TYPE to LEAF and its REFS, marking things changed. If
1239 ;;; the leaf type is a function type, then just leave it alone, since
1240 ;;; TYPE is never going to be more specific than that (and
1241 ;;; TYPE-INTERSECTION would choke.)
1242 (defun propagate-to-refs (leaf type)
1243   (declare (type leaf leaf) (type ctype type))
1244   (let ((var-type (leaf-type leaf)))
1245     (unless (fun-type-p var-type)
1246       (let ((int (type-approx-intersection2 var-type type)))
1247         (when (type/= int var-type)
1248           (setf (leaf-type leaf) int)
1249           (dolist (ref (leaf-refs leaf))
1250             (derive-node-type ref (make-single-value-type int))
1251             (let* ((cont (node-cont ref))
1252                    (dest (continuation-dest cont)))
1253               ;; KLUDGE: LET var substitution
1254               (when (combination-p dest)
1255                 (reoptimize-continuation cont))))))
1256       (values))))
1257
1258 ;;; Figure out the type of a LET variable that has sets. We compute
1259 ;;; the union of the initial value TYPE and the types of all the set
1260 ;;; values and to a PROPAGATE-TO-REFS with this type.
1261 (defun propagate-from-sets (var type)
1262   (collect ((res type type-union))
1263     (dolist (set (basic-var-sets var))
1264       (let ((type (continuation-type (set-value set))))
1265         (res type)
1266         (when (node-reoptimize set)
1267           (derive-node-type set (make-single-value-type type))
1268           (setf (node-reoptimize set) nil))))
1269     (propagate-to-refs var (res)))
1270   (values))
1271
1272 ;;; If a LET variable, find the initial value's type and do
1273 ;;; PROPAGATE-FROM-SETS. We also derive the VALUE's type as the node's
1274 ;;; type.
1275 (defun ir1-optimize-set (node)
1276   (declare (type cset node))
1277   (let ((var (set-var node)))
1278     (when (and (lambda-var-p var) (leaf-refs var))
1279       (let ((home (lambda-var-home var)))
1280         (when (eq (functional-kind home) :let)
1281           (let ((iv (let-var-initial-value var)))
1282             (setf (continuation-reoptimize iv) nil)
1283             (propagate-from-sets var (continuation-type iv)))))))
1284
1285   (derive-node-type node (make-single-value-type
1286                           (continuation-type (set-value node))))
1287   (values))
1288
1289 ;;; Return true if the value of REF will always be the same (and is
1290 ;;; thus legal to substitute.)
1291 (defun constant-reference-p (ref)
1292   (declare (type ref ref))
1293   (let ((leaf (ref-leaf ref)))
1294     (typecase leaf
1295       ((or constant functional) t)
1296       (lambda-var
1297        (null (lambda-var-sets leaf)))
1298       (defined-fun
1299        (not (eq (defined-fun-inlinep leaf) :notinline)))
1300       (global-var
1301        (case (global-var-kind leaf)
1302          (:global-function
1303           (let ((name (leaf-source-name leaf)))
1304             (or #-sb-xc-host
1305                 (eq (symbol-package (fun-name-block-name name))
1306                     *cl-package*)
1307                 (info :function :info name)))))))))
1308
1309 ;;; If we have a non-set LET var with a single use, then (if possible)
1310 ;;; replace the variable reference's CONT with the arg continuation.
1311 ;;; This is inhibited when:
1312 ;;; -- CONT has other uses, or
1313 ;;; -- the reference is in a different environment from the variable, or
1314 ;;; -- CONT carries unknown number of values, or
1315 ;;; -- DEST is return or exit, or
1316 ;;; -- DEST is sensitive to the number of values and ARG return non-one value.
1317 ;;;
1318 ;;; We change the REF to be a reference to NIL with unused value, and
1319 ;;; let it be flushed as dead code. A side effect of this substitution
1320 ;;; is to delete the variable.
1321 (defun substitute-single-use-continuation (arg var)
1322   (declare (type continuation arg) (type lambda-var var))
1323   (let* ((ref (first (leaf-refs var)))
1324          (cont (node-cont ref))
1325          (dest (continuation-dest cont)))
1326     (when (and (eq (continuation-use cont) ref)
1327                dest
1328                (typecase dest
1329                  (cast
1330                   (and (type-single-value-p (continuation-derived-type arg))
1331                        (multiple-value-bind (pdest pprev)
1332                            (principal-continuation-end cont)
1333                          (declare (ignore pdest))
1334                          (continuation-single-value-p pprev))))
1335                  (mv-combination
1336                   (or (eq (basic-combination-fun dest) cont)
1337                       (and (eq (basic-combination-kind dest) :local)
1338                            (type-single-value-p (continuation-derived-type arg)))))
1339                  ((or creturn exit)
1340                   nil)
1341                  (t
1342                   ;; (AVER (CONTINUATION-SINGLE-VALUE-P CONT))
1343                   t))
1344                (eq (node-home-lambda ref)
1345                    (lambda-home (lambda-var-home var))))
1346       (aver (member (continuation-kind arg)
1347                     '(:block-start :deleted-block-start :inside-block)))
1348       (setf (node-derived-type ref) *wild-type*)
1349       (change-ref-leaf ref (find-constant nil))
1350       (substitute-continuation arg cont)
1351       (reoptimize-continuation arg)
1352       t)))
1353
1354 ;;; Delete a LET, removing the call and bind nodes, and warning about
1355 ;;; any unreferenced variables. Note that FLUSH-DEAD-CODE will come
1356 ;;; along right away and delete the REF and then the lambda, since we
1357 ;;; flush the FUN continuation.
1358 (defun delete-let (clambda)
1359   (declare (type clambda clambda))
1360   (aver (functional-letlike-p clambda))
1361   (note-unreferenced-vars clambda)
1362   (let ((call (let-combination clambda)))
1363     (flush-dest (basic-combination-fun call))
1364     (unlink-node call)
1365     (unlink-node (lambda-bind clambda))
1366     (setf (lambda-bind clambda) nil))
1367   (values))
1368
1369 ;;; This function is called when one of the arguments to a LET
1370 ;;; changes. We look at each changed argument. If the corresponding
1371 ;;; variable is set, then we call PROPAGATE-FROM-SETS. Otherwise, we
1372 ;;; consider substituting for the variable, and also propagate
1373 ;;; derived-type information for the arg to all the VAR's refs.
1374 ;;;
1375 ;;; Substitution is inhibited when the arg leaf's derived type isn't a
1376 ;;; subtype of the argument's leaf type. This prevents type checking
1377 ;;; from being defeated, and also ensures that the best representation
1378 ;;; for the variable can be used.
1379 ;;;
1380 ;;; Substitution of individual references is inhibited if the
1381 ;;; reference is in a different component from the home. This can only
1382 ;;; happen with closures over top level lambda vars. In such cases,
1383 ;;; the references may have already been compiled, and thus can't be
1384 ;;; retroactively modified.
1385 ;;;
1386 ;;; If all of the variables are deleted (have no references) when we
1387 ;;; are done, then we delete the LET.
1388 ;;;
1389 ;;; Note that we are responsible for clearing the
1390 ;;; CONTINUATION-REOPTIMIZE flags.
1391 (defun propagate-let-args (call fun)
1392   (declare (type combination call) (type clambda fun))
1393   (loop for arg in (combination-args call)
1394         and var in (lambda-vars fun) do
1395     (when (and arg (continuation-reoptimize arg))
1396       (setf (continuation-reoptimize arg) nil)
1397       (cond
1398        ((lambda-var-sets var)
1399         (propagate-from-sets var (continuation-type arg)))
1400        ((let ((use (continuation-use arg)))
1401           (when (ref-p use)
1402             (let ((leaf (ref-leaf use)))
1403               (when (and (constant-reference-p use)
1404                          (csubtypep (leaf-type leaf)
1405                                     ;; (NODE-DERIVED-TYPE USE) would
1406                                     ;; be better -- APD, 2003-05-15
1407                                     (leaf-type var)))
1408                 (propagate-to-refs var (continuation-type arg))
1409                 (let ((use-component (node-component use)))
1410                   (substitute-leaf-if
1411                    (lambda (ref)
1412                      (cond ((eq (node-component ref) use-component)
1413                             t)
1414                            (t
1415                             (aver (lambda-toplevelish-p (lambda-home fun)))
1416                             nil)))
1417                    leaf var))
1418                 t)))))
1419        ((and (null (rest (leaf-refs var)))
1420              (substitute-single-use-continuation arg var)))
1421        (t
1422         (propagate-to-refs var (continuation-type arg))))))
1423
1424   (when (every #'not (combination-args call))
1425     (delete-let fun))
1426
1427   (values))
1428
1429 ;;; This function is called when one of the args to a non-LET local
1430 ;;; call changes. For each changed argument corresponding to an unset
1431 ;;; variable, we compute the union of the types across all calls and
1432 ;;; propagate this type information to the var's refs.
1433 ;;;
1434 ;;; If the function has an XEP, then we don't do anything, since we
1435 ;;; won't discover anything.
1436 ;;;
1437 ;;; We can clear the CONTINUATION-REOPTIMIZE flags for arguments in
1438 ;;; all calls corresponding to changed arguments in CALL, since the
1439 ;;; only use in IR1 optimization of the REOPTIMIZE flag for local call
1440 ;;; args is right here.
1441 (defun propagate-local-call-args (call fun)
1442   (declare (type combination call) (type clambda fun))
1443
1444   (unless (or (functional-entry-fun fun)
1445               (lambda-optional-dispatch fun))
1446     (let* ((vars (lambda-vars fun))
1447            (union (mapcar (lambda (arg var)
1448                             (when (and arg
1449                                        (continuation-reoptimize arg)
1450                                        (null (basic-var-sets var)))
1451                               (continuation-type arg)))
1452                           (basic-combination-args call)
1453                           vars))
1454            (this-ref (continuation-use (basic-combination-fun call))))
1455
1456       (dolist (arg (basic-combination-args call))
1457         (when arg
1458           (setf (continuation-reoptimize arg) nil)))
1459
1460       (dolist (ref (leaf-refs fun))
1461         (let ((dest (continuation-dest (node-cont ref))))
1462           (unless (or (eq ref this-ref) (not dest))
1463             (setq union
1464                   (mapcar (lambda (this-arg old)
1465                             (when old
1466                               (setf (continuation-reoptimize this-arg) nil)
1467                               (type-union (continuation-type this-arg) old)))
1468                           (basic-combination-args dest)
1469                           union)))))
1470
1471       (mapc (lambda (var type)
1472               (when type
1473                 (propagate-to-refs var type)))
1474             vars union)))
1475
1476   (values))
1477 \f
1478 ;;;; multiple values optimization
1479
1480 ;;; Do stuff to notice a change to a MV combination node. There are
1481 ;;; two main branches here:
1482 ;;;  -- If the call is local, then it is already a MV let, or should
1483 ;;;     become one. Note that although all :LOCAL MV calls must eventually
1484 ;;;     be converted to :MV-LETs, there can be a window when the call
1485 ;;;     is local, but has not been LET converted yet. This is because
1486 ;;;     the entry-point lambdas may have stray references (in other
1487 ;;;     entry points) that have not been deleted yet.
1488 ;;;  -- The call is full. This case is somewhat similar to the non-MV
1489 ;;;     combination optimization: we propagate return type information and
1490 ;;;     notice non-returning calls. We also have an optimization
1491 ;;;     which tries to convert MV-CALLs into MV-binds.
1492 (defun ir1-optimize-mv-combination (node)
1493   (ecase (basic-combination-kind node)
1494     (:local
1495      (let ((fun-cont (basic-combination-fun node)))
1496        (when (continuation-reoptimize fun-cont)
1497          (setf (continuation-reoptimize fun-cont) nil)
1498          (maybe-let-convert (combination-lambda node))))
1499      (setf (continuation-reoptimize (first (basic-combination-args node))) nil)
1500      (when (eq (functional-kind (combination-lambda node)) :mv-let)
1501        (unless (convert-mv-bind-to-let node)
1502          (ir1-optimize-mv-bind node))))
1503     (:full
1504      (let* ((fun (basic-combination-fun node))
1505             (fun-changed (continuation-reoptimize fun))
1506             (args (basic-combination-args node)))
1507        (when fun-changed
1508          (setf (continuation-reoptimize fun) nil)
1509          (let ((type (continuation-type fun)))
1510            (when (fun-type-p type)
1511              (derive-node-type node (fun-type-returns type))))
1512          (maybe-terminate-block node nil)
1513          (let ((use (continuation-use fun)))
1514            (when (and (ref-p use) (functional-p (ref-leaf use)))
1515              (convert-call-if-possible use node)
1516              (when (eq (basic-combination-kind node) :local)
1517                (maybe-let-convert (ref-leaf use))))))
1518        (unless (or (eq (basic-combination-kind node) :local)
1519                    (eq (continuation-fun-name fun) '%throw))
1520          (ir1-optimize-mv-call node))
1521        (dolist (arg args)
1522          (setf (continuation-reoptimize arg) nil))))
1523     (:error))
1524   (values))
1525
1526 ;;; Propagate derived type info from the values continuation to the
1527 ;;; vars.
1528 (defun ir1-optimize-mv-bind (node)
1529   (declare (type mv-combination node))
1530   (let ((arg (first (basic-combination-args node)))
1531         (vars (lambda-vars (combination-lambda node))))
1532     (multiple-value-bind (types nvals)
1533         (values-types (continuation-derived-type arg))
1534       (unless (eq nvals :unknown)
1535         (mapc (lambda (var type)
1536                 (if (basic-var-sets var)
1537                     (propagate-from-sets var type)
1538                     (propagate-to-refs var type)))
1539               vars
1540               (adjust-list types
1541                            (length vars)
1542                            (specifier-type 'null)))))
1543     (setf (continuation-reoptimize arg) nil))
1544   (values))
1545
1546 ;;; If possible, convert a general MV call to an MV-BIND. We can do
1547 ;;; this if:
1548 ;;; -- The call has only one argument, and
1549 ;;; -- The function has a known fixed number of arguments, or
1550 ;;; -- The argument yields a known fixed number of values.
1551 ;;;
1552 ;;; What we do is change the function in the MV-CALL to be a lambda
1553 ;;; that "looks like an MV bind", which allows
1554 ;;; IR1-OPTIMIZE-MV-COMBINATION to notice that this call can be
1555 ;;; converted (the next time around.) This new lambda just calls the
1556 ;;; actual function with the MV-BIND variables as arguments. Note that
1557 ;;; this new MV bind is not let-converted immediately, as there are
1558 ;;; going to be stray references from the entry-point functions until
1559 ;;; they get deleted.
1560 ;;;
1561 ;;; In order to avoid loss of argument count checking, we only do the
1562 ;;; transformation according to a known number of expected argument if
1563 ;;; safety is unimportant. We can always convert if we know the number
1564 ;;; of actual values, since the normal call that we build will still
1565 ;;; do any appropriate argument count checking.
1566 ;;;
1567 ;;; We only attempt the transformation if the called function is a
1568 ;;; constant reference. This allows us to just splice the leaf into
1569 ;;; the new function, instead of trying to somehow bind the function
1570 ;;; expression. The leaf must be constant because we are evaluating it
1571 ;;; again in a different place. This also has the effect of squelching
1572 ;;; multiple warnings when there is an argument count error.
1573 (defun ir1-optimize-mv-call (node)
1574   (let ((fun (basic-combination-fun node))
1575         (*compiler-error-context* node)
1576         (ref (continuation-use (basic-combination-fun node)))
1577         (args (basic-combination-args node)))
1578
1579     (unless (and (ref-p ref) (constant-reference-p ref)
1580                  (singleton-p args))
1581       (return-from ir1-optimize-mv-call))
1582
1583     (multiple-value-bind (min max)
1584         (fun-type-nargs (continuation-type fun))
1585       (let ((total-nvals
1586              (multiple-value-bind (types nvals)
1587                  (values-types (continuation-derived-type (first args)))
1588                (declare (ignore types))
1589                (if (eq nvals :unknown) nil nvals))))
1590
1591         (when total-nvals
1592           (when (and min (< total-nvals min))
1593             (compiler-warn
1594              "MULTIPLE-VALUE-CALL with ~R values when the function expects ~
1595              at least ~R."
1596              total-nvals min)
1597             (setf (basic-combination-kind node) :error)
1598             (return-from ir1-optimize-mv-call))
1599           (when (and max (> total-nvals max))
1600             (compiler-warn
1601              "MULTIPLE-VALUE-CALL with ~R values when the function expects ~
1602              at most ~R."
1603              total-nvals max)
1604             (setf (basic-combination-kind node) :error)
1605             (return-from ir1-optimize-mv-call)))
1606
1607         (let ((count (cond (total-nvals)
1608                            ((and (policy node (zerop verify-arg-count))
1609                                  (eql min max))
1610                             min)
1611                            (t nil))))
1612           (when count
1613             (with-ir1-environment-from-node node
1614               (let* ((dums (make-gensym-list count))
1615                      (ignore (gensym))
1616                      (fun (ir1-convert-lambda
1617                            `(lambda (&optional ,@dums &rest ,ignore)
1618                               (declare (ignore ,ignore))
1619                               (funcall ,(ref-leaf ref) ,@dums)))))
1620                 (change-ref-leaf ref fun)
1621                 (aver (eq (basic-combination-kind node) :full))
1622                 (locall-analyze-component *current-component*)
1623                 (aver (eq (basic-combination-kind node) :local)))))))))
1624   (values))
1625
1626 ;;; If we see:
1627 ;;;    (multiple-value-bind
1628 ;;;     (x y)
1629 ;;;     (values xx yy)
1630 ;;;      ...)
1631 ;;; Convert to:
1632 ;;;    (let ((x xx)
1633 ;;;       (y yy))
1634 ;;;      ...)
1635 ;;;
1636 ;;; What we actually do is convert the VALUES combination into a
1637 ;;; normal LET combination calling the original :MV-LET lambda. If
1638 ;;; there are extra args to VALUES, discard the corresponding
1639 ;;; continuations. If there are insufficient args, insert references
1640 ;;; to NIL.
1641 (defun convert-mv-bind-to-let (call)
1642   (declare (type mv-combination call))
1643   (let* ((arg (first (basic-combination-args call)))
1644          (use (continuation-use arg)))
1645     (when (and (combination-p use)
1646                (eq (continuation-fun-name (combination-fun use))
1647                    'values))
1648       (let* ((fun (combination-lambda call))
1649              (vars (lambda-vars fun))
1650              (vals (combination-args use))
1651              (nvars (length vars))
1652              (nvals (length vals)))
1653         (cond ((> nvals nvars)
1654                (mapc #'flush-dest (subseq vals nvars))
1655                (setq vals (subseq vals 0 nvars)))
1656               ((< nvals nvars)
1657                (with-ir1-environment-from-node use
1658                  (let ((node-prev (node-prev use)))
1659                    (setf (node-prev use) nil)
1660                    (setf (continuation-next node-prev) nil)
1661                    (collect ((res vals))
1662                      (loop for cont = (make-continuation use)
1663                            and prev = node-prev then cont
1664                            repeat (- nvars nvals)
1665                            do (reference-constant prev cont nil)
1666                               (res cont))
1667                      (setq vals (res)))
1668                    (link-node-to-previous-continuation use
1669                                                        (car (last vals)))))))
1670         (setf (combination-args use) vals)
1671         (flush-dest (combination-fun use))
1672         (let ((fun-cont (basic-combination-fun call)))
1673           (setf (continuation-dest fun-cont) use)
1674           (setf (combination-fun use) fun-cont)
1675           (flush-continuation-externally-checkable-type fun-cont))
1676         (setf (combination-kind use) :local)
1677         (setf (functional-kind fun) :let)
1678         (flush-dest (first (basic-combination-args call)))
1679         (unlink-node call)
1680         (when vals
1681           (reoptimize-continuation (first vals)))
1682         (propagate-to-args use fun)
1683         (reoptimize-call use))
1684       t)))
1685
1686 ;;; If we see:
1687 ;;;    (values-list (list x y z))
1688 ;;;
1689 ;;; Convert to:
1690 ;;;    (values x y z)
1691 ;;;
1692 ;;; In implementation, this is somewhat similar to
1693 ;;; CONVERT-MV-BIND-TO-LET. We grab the args of LIST and make them
1694 ;;; args of the VALUES-LIST call, flushing the old argument
1695 ;;; continuation (allowing the LIST to be flushed.)
1696 ;;;
1697 ;;; FIXME: Thus we lose possible type assertions on (LIST ...).
1698 (defoptimizer (values-list optimizer) ((list) node)
1699   (let ((use (continuation-use list)))
1700     (when (and (combination-p use)
1701                (eq (continuation-fun-name (combination-fun use))
1702                    'list))
1703
1704       ;; FIXME: VALUES might not satisfy an assertion on NODE-CONT.
1705       (change-ref-leaf (continuation-use (combination-fun node))
1706                        (find-free-fun 'values "in a strange place"))
1707       (setf (combination-kind node) :full)
1708       (let ((args (combination-args use)))
1709         (dolist (arg args)
1710           (setf (continuation-dest arg) node)
1711           (flush-continuation-externally-checkable-type arg))
1712         (setf (combination-args use) nil)
1713         (flush-dest list)
1714         (setf (combination-args node) args))
1715       t)))
1716
1717 ;;; If VALUES appears in a non-MV context, then effectively convert it
1718 ;;; to a PROG1. This allows the computation of the additional values
1719 ;;; to become dead code.
1720 (deftransform values ((&rest vals) * * :node node)
1721   (unless (continuation-single-value-p (node-cont node))
1722     (give-up-ir1-transform))
1723   (setf (node-derived-type node) *wild-type*)
1724   (principal-continuation-single-valuify (node-cont node))
1725   (if vals
1726       (let ((dummies (make-gensym-list (length (cdr vals)))))
1727         `(lambda (val ,@dummies)
1728            (declare (ignore ,@dummies))
1729            val))
1730       nil))
1731
1732 ;;; TODO:
1733 ;;; - CAST chains;
1734 (defun ir1-optimize-cast (cast &optional do-not-optimize)
1735   (declare (type cast cast))
1736   (let* ((value (cast-value cast))
1737          (value-type (continuation-derived-type value))
1738          (cont (node-cont cast))
1739          (dest (continuation-dest cont))
1740          (atype (cast-asserted-type cast))
1741          (int (values-type-intersection value-type atype)))
1742     (derive-node-type cast int)
1743     (when (eq int *empty-type*)
1744       (unless (eq value-type *empty-type*)
1745
1746         ;; FIXME: Do it in one step.
1747         (filter-continuation
1748          value
1749          `(multiple-value-call #'list 'dummy))
1750         (filter-continuation
1751          value
1752          ;; FIXME: Derived type.
1753          `(%compile-time-type-error 'dummy
1754                                     ',(type-specifier atype)
1755                                     ',(type-specifier value-type)))
1756         ;; KLUDGE: FILTER-CONTINUATION does not work for
1757         ;; non-returning functions, so we declare the return type of
1758         ;; %COMPILE-TIME-TYPE-ERROR to be * and derive the real type
1759         ;; here.
1760         (derive-node-type (continuation-use value) *empty-type*)
1761         (maybe-terminate-block (continuation-use value) nil)
1762         ;; FIXME: Is it necessary?
1763         (aver (null (block-pred (node-block cast))))
1764         (setf (block-delete-p (node-block cast)) t)
1765         (return-from ir1-optimize-cast)))
1766     (when (eq (node-derived-type cast) *empty-type*)
1767       (maybe-terminate-block cast nil))
1768
1769     (when (and (not do-not-optimize)
1770                (values-subtypep value-type
1771                                 (cast-asserted-type cast)))
1772       (delete-filter cast cont value)
1773       (reoptimize-continuation cont)
1774       (when (continuation-single-value-p cont)
1775         (note-single-valuified-continuation cont))
1776       (when (not dest)
1777         (reoptimize-continuation-uses cont))
1778       (return-from ir1-optimize-cast t))
1779
1780     (when (and (not do-not-optimize)
1781                (not (continuation-use value))
1782                dest)
1783       (collect ((merges))
1784         (do-uses (use value)
1785           (when (and (values-subtypep (node-derived-type use) atype)
1786                      (immediately-used-p value use))
1787             (ensure-block-start cont)
1788             (delete-continuation-use use)
1789             (add-continuation-use use cont)
1790             (unlink-blocks (node-block use) (node-block cast))
1791             (link-blocks (node-block use) (continuation-block cont))
1792             (when (and (return-p dest)
1793                        (basic-combination-p use)
1794                        (eq (basic-combination-kind use) :local))
1795               (merges use))))
1796         (dolist (use (merges))
1797           (merge-tail-sets use))))
1798
1799     (when (and (cast-%type-check cast)
1800                (values-subtypep value-type
1801                                 (cast-type-to-check cast)))
1802       (setf (cast-%type-check cast) nil)))
1803
1804   (unless do-not-optimize
1805     (setf (node-reoptimize cast) nil)))