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