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