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