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