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