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