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