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