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