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