5959b9f744d3c52dc8c3d37dd49cfd2304ae37fb
[sbcl.git] / src / compiler / ir1util.lisp
1 ;;;; This file contains miscellaneous utilities used for manipulating
2 ;;;; the IR1 representation.
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14 \f
15 ;;;; cleanup hackery
16
17 ;;; Return the innermost cleanup enclosing NODE, or NIL if there is
18 ;;; none in its function. If NODE has no cleanup, but is in a LET,
19 ;;; then we must still check the environment that the call is in.
20 (defun node-enclosing-cleanup (node)
21   (declare (type node node))
22   (do ((lexenv (node-lexenv node)
23                (lambda-call-lexenv (lexenv-lambda lexenv))))
24       ((null lexenv) nil)
25     (let ((cup (lexenv-cleanup lexenv)))
26       (when cup (return cup)))))
27
28 ;;; Convert the FORM in a block inserted between BLOCK1 and BLOCK2 as
29 ;;; an implicit MV-PROG1. The inserted block is returned. NODE is used
30 ;;; for IR1 context when converting the form. Note that the block is
31 ;;; not assigned a number, and is linked into the DFO at the
32 ;;; beginning. We indicate that we have trashed the DFO by setting
33 ;;; COMPONENT-REANALYZE. If CLEANUP is supplied, then convert with
34 ;;; that cleanup.
35 (defun insert-cleanup-code (block1 block2 node form &optional cleanup)
36   (declare (type cblock block1 block2) (type node node)
37            (type (or cleanup null) cleanup))
38   (setf (component-reanalyze (block-component block1)) t)
39   (with-ir1-environment-from-node node
40     (with-component-last-block (*current-component*
41                                 (block-next (component-head *current-component*)))
42       (let* ((start (make-ctran))
43              (block (ctran-starts-block start))
44              (next (make-ctran))
45              (*lexenv* (if cleanup
46                            (make-lexenv :cleanup cleanup)
47                            *lexenv*)))
48         (change-block-successor block1 block2 block)
49         (link-blocks block block2)
50         (ir1-convert start next nil form)
51         (setf (block-last block) (ctran-use next))
52         (setf (node-next (block-last block)) nil)
53         block))))
54 \f
55 ;;;; lvar use hacking
56
57 ;;; Return a list of all the nodes which use LVAR.
58 (declaim (ftype (sfunction (lvar) list) find-uses))
59 (defun find-uses (lvar)
60   (let ((uses (lvar-uses lvar)))
61     (if (listp uses)
62         uses
63         (list uses))))
64
65 (declaim (ftype (sfunction (lvar) lvar) principal-lvar))
66 (defun principal-lvar (lvar)
67   (labels ((pl (lvar)
68              (let ((use (lvar-uses lvar)))
69                (if (cast-p use)
70                    (pl (cast-value use))
71                    lvar))))
72     (pl lvar)))
73
74 (defun principal-lvar-use (lvar)
75   (labels ((plu (lvar)
76              (declare (type lvar lvar))
77              (let ((use (lvar-uses lvar)))
78                (if (cast-p use)
79                    (plu (cast-value use))
80                    use))))
81     (plu lvar)))
82
83 ;;; Update lvar use information so that NODE is no longer a use of its
84 ;;; LVAR.
85 ;;;
86 ;;; Note: if you call this function, you may have to do a
87 ;;; REOPTIMIZE-LVAR to inform IR1 optimization that something has
88 ;;; changed.
89 (declaim (ftype (sfunction (node) (values))
90                 delete-lvar-use
91                 %delete-lvar-use))
92 ;;; Just delete NODE from its LVAR uses; LVAR is preserved so it may
93 ;;; be given a new use.
94 (defun %delete-lvar-use (node)
95   (let ((lvar (node-lvar node)))
96     (when lvar
97       (if (listp (lvar-uses lvar))
98           (let ((new-uses (delq node (lvar-uses lvar))))
99             (setf (lvar-uses lvar)
100                   (if (singleton-p new-uses)
101                       (first new-uses)
102                       new-uses)))
103           (setf (lvar-uses lvar) nil))
104       (setf (node-lvar node) nil)))
105   (values))
106 ;;; Delete NODE from its LVAR uses; if LVAR has no other uses, delete
107 ;;; its DEST's block, which must be unreachable.
108 (defun delete-lvar-use (node)
109   (let ((lvar (node-lvar node)))
110     (when lvar
111       (%delete-lvar-use node)
112       (if (null (lvar-uses lvar))
113           (binding* ((dest (lvar-dest lvar) :exit-if-null)
114                      (() (not (node-deleted dest)) :exit-if-null)
115                      (block (node-block dest)))
116             (mark-for-deletion block))
117           (reoptimize-lvar lvar))))
118   (values))
119
120 ;;; Update lvar use information so that NODE uses LVAR.
121 ;;;
122 ;;; Note: if you call this function, you may have to do a
123 ;;; REOPTIMIZE-LVAR to inform IR1 optimization that something has
124 ;;; changed.
125 (declaim (ftype (sfunction (node (or lvar null)) (values)) add-lvar-use))
126 (defun add-lvar-use (node lvar)
127   (aver (not (node-lvar node)))
128   (when lvar
129     (let ((uses (lvar-uses lvar)))
130       (setf (lvar-uses lvar)
131             (cond ((null uses)
132                    node)
133                   ((listp uses)
134                    (cons node uses))
135                   (t
136                    (list node uses))))
137       (setf (node-lvar node) lvar)))
138
139   (values))
140
141 ;;; Return true if LVAR destination is executed immediately after
142 ;;; NODE. Cleanups are ignored.
143 (defun immediately-used-p (lvar node)
144   (declare (type lvar lvar) (type node node))
145   (aver (eq (node-lvar node) lvar))
146   (let ((dest (lvar-dest lvar)))
147     (acond ((node-next node)
148             (eq (ctran-next it) dest))
149            (t (eq (block-start (first (block-succ (node-block node))))
150                   (node-prev dest))))))
151
152 ;;; Returns the defined (usually untrusted) type of the combination,
153 ;;; or NIL if we couldn't figure it out.
154 (defun combination-defined-type (combination)
155   (let ((use (principal-lvar-use (basic-combination-fun combination))))
156     (or (when (ref-p use)
157           (let ((type (leaf-defined-type (ref-leaf use))))
158             (when (fun-type-p type)
159               (fun-type-returns type))))
160         *wild-type*)))
161
162 ;;; Return true if LVAR destination is executed after node with only
163 ;;; uninteresting nodes intervening.
164 ;;;
165 ;;; Uninteresting nodes are nodes in the same block which are either
166 ;;; REFs, external CASTs to the same destination, or known combinations
167 ;;; that never unwind.
168 (defun almost-immediately-used-p (lvar node)
169   (declare (type lvar lvar)
170            (type node node))
171   (aver (eq (node-lvar node) lvar))
172   (let ((dest (lvar-dest lvar)))
173     (tagbody
174      :next
175        (let ((ctran (node-next node)))
176          (cond (ctran
177                 (setf node (ctran-next ctran))
178                 (if (eq node dest)
179                     (return-from almost-immediately-used-p t)
180                     (typecase node
181                       (ref
182                        (go :next))
183                       (cast
184                        (when (and (eq :external (cast-type-check node))
185                                   (eq dest (node-dest node)))
186                          (go :next)))
187                       (combination
188                        ;; KLUDGE: Unfortunately we don't have an attribute for
189                        ;; "never unwinds", so we just special case
190                        ;; %ALLOCATE-CLOSURES: it is easy to run into with eg.
191                        ;; FORMAT and a non-constant first argument.
192                        (when (eq '%allocate-closures (combination-fun-source-name node nil))
193                          (go :next))))))
194                (t
195                 (when (eq (block-start (first (block-succ (node-block node))))
196                           (node-prev dest))
197                   (return-from almost-immediately-used-p t))))))))
198 \f
199 ;;;; lvar substitution
200
201 ;;; In OLD's DEST, replace OLD with NEW. NEW's DEST must initially be
202 ;;; NIL. We do not flush OLD's DEST.
203 (defun substitute-lvar (new old)
204   (declare (type lvar old new))
205   (aver (not (lvar-dest new)))
206   (let ((dest (lvar-dest old)))
207     (etypecase dest
208       ((or ref bind))
209       (cif (setf (if-test dest) new))
210       (cset (setf (set-value dest) new))
211       (creturn (setf (return-result dest) new))
212       (exit (setf (exit-value dest) new))
213       (basic-combination
214        (if (eq old (basic-combination-fun dest))
215            (setf (basic-combination-fun dest) new)
216            (setf (basic-combination-args dest)
217                  (nsubst new old (basic-combination-args dest)))))
218       (cast (setf (cast-value dest) new)))
219
220     (setf (lvar-dest old) nil)
221     (setf (lvar-dest new) dest)
222     (flush-lvar-externally-checkable-type new))
223   (values))
224
225 ;;; Replace all uses of OLD with uses of NEW, where NEW has an
226 ;;; arbitary number of uses. NEW is supposed to be "later" than OLD.
227 (defun substitute-lvar-uses (new old propagate-dx)
228   (declare (type lvar old)
229            (type (or lvar null) new)
230            (type boolean propagate-dx))
231
232   (cond (new
233          (do-uses (node old)
234            (%delete-lvar-use node)
235            (add-lvar-use node new))
236          (reoptimize-lvar new)
237          (awhen (and propagate-dx (lvar-dynamic-extent old))
238            (setf (lvar-dynamic-extent old) nil)
239            (unless (lvar-dynamic-extent new)
240              (setf (lvar-dynamic-extent new) it)
241              (setf (cleanup-info it) (subst new old (cleanup-info it)))))
242          (when (lvar-dynamic-extent new)
243            (do-uses (node new)
244              (node-ends-block node))))
245         (t (flush-dest old)))
246
247   (values))
248 \f
249 ;;;; block starting/creation
250
251 ;;; Return the block that CTRAN is the start of, making a block if
252 ;;; necessary. This function is called by IR1 translators which may
253 ;;; cause a CTRAN to be used more than once. Every CTRAN which may be
254 ;;; used more than once must start a block by the time that anyone
255 ;;; does a USE-CTRAN on it.
256 ;;;
257 ;;; We also throw the block into the next/prev list for the
258 ;;; *CURRENT-COMPONENT* so that we keep track of which blocks we have
259 ;;; made.
260 (defun ctran-starts-block (ctran)
261   (declare (type ctran ctran))
262   (ecase (ctran-kind ctran)
263     (:unused
264      (aver (not (ctran-block ctran)))
265      (let* ((next (component-last-block *current-component*))
266             (prev (block-prev next))
267             (new-block (make-block ctran)))
268        (setf (block-next new-block) next
269              (block-prev new-block) prev
270              (block-prev next) new-block
271              (block-next prev) new-block
272              (ctran-block ctran) new-block
273              (ctran-kind ctran) :block-start)
274        (aver (not (ctran-use ctran)))
275        new-block))
276     (:block-start
277      (ctran-block ctran))))
278
279 ;;; Ensure that CTRAN is the start of a block so that the use set can
280 ;;; be freely manipulated.
281 (defun ensure-block-start (ctran)
282   (declare (type ctran ctran))
283   (let ((kind (ctran-kind ctran)))
284     (ecase kind
285       ((:block-start))
286       ((:unused)
287        (setf (ctran-block ctran)
288              (make-block-key :start ctran))
289        (setf (ctran-kind ctran) :block-start))
290       ((:inside-block)
291        (node-ends-block (ctran-use ctran)))))
292   (values))
293
294 ;;; CTRAN must be the last ctran in an incomplete block; finish the
295 ;;; block and start a new one if necessary.
296 (defun start-block (ctran)
297   (declare (type ctran ctran))
298   (aver (not (ctran-next ctran)))
299   (ecase (ctran-kind ctran)
300     (:inside-block
301      (let ((block (ctran-block ctran))
302            (node (ctran-use ctran)))
303        (aver (not (block-last block)))
304        (aver node)
305        (setf (block-last block) node)
306        (setf (node-next node) nil)
307        (setf (ctran-use ctran) nil)
308        (setf (ctran-kind ctran) :unused)
309        (setf (ctran-block ctran) nil)
310        (link-blocks block (ctran-starts-block ctran))))
311     (:block-start)))
312 \f
313 ;;;;
314
315 ;;; Filter values of LVAR through FORM, which must be an ordinary/mv
316 ;;; call. First argument must be 'DUMMY, which will be replaced with
317 ;;; LVAR. In case of an ordinary call the function should not have
318 ;;; return type NIL. We create a new "filtered" lvar.
319 ;;;
320 ;;; TODO: remove preconditions.
321 (defun filter-lvar (lvar form)
322   (declare (type lvar lvar) (type list form))
323   (let* ((dest (lvar-dest lvar))
324          (ctran (node-prev dest)))
325     (with-ir1-environment-from-node dest
326
327       (ensure-block-start ctran)
328       (let* ((old-block (ctran-block ctran))
329              (new-start (make-ctran))
330              (filtered-lvar (make-lvar))
331              (new-block (ctran-starts-block new-start)))
332
333         ;; Splice in the new block before DEST, giving the new block
334         ;; all of DEST's predecessors.
335         (dolist (block (block-pred old-block))
336           (change-block-successor block old-block new-block))
337
338         (ir1-convert new-start ctran filtered-lvar form)
339
340         ;; KLUDGE: Comments at the head of this function in CMU CL
341         ;; said that somewhere in here we
342         ;;   Set the new block's start and end cleanups to the *start*
343         ;;   cleanup of PREV's block. This overrides the incorrect
344         ;;   default from WITH-IR1-ENVIRONMENT-FROM-NODE.
345         ;; Unfortunately I can't find any code which corresponds to this.
346         ;; Perhaps it was a stale comment? Or perhaps I just don't
347         ;; understand.. -- WHN 19990521
348
349         ;; Replace 'DUMMY with the LVAR. (We can find 'DUMMY because
350         ;; no LET conversion has been done yet.) The [mv-]combination
351         ;; code from the call in the form will be the use of the new
352         ;; check lvar. We substitute for the first argument of
353         ;; this node.
354         (let* ((node (lvar-use filtered-lvar))
355                (args (basic-combination-args node))
356                (victim (first args)))
357           (aver (eq (constant-value (ref-leaf (lvar-use victim)))
358                     'dummy))
359
360           (substitute-lvar filtered-lvar lvar)
361           (substitute-lvar lvar victim)
362           (flush-dest victim))
363
364         ;; Invoking local call analysis converts this call to a LET.
365         (locall-analyze-component *current-component*))))
366   (values))
367
368 ;;; Delete NODE and VALUE. It may result in some calls becoming tail.
369 (defun delete-filter (node lvar value)
370   (aver (eq (lvar-dest value) node))
371   (aver (eq (node-lvar node) lvar))
372   (cond (lvar (collect ((merges))
373                 (when (return-p (lvar-dest lvar))
374                   (do-uses (use value)
375                     (when (and (basic-combination-p use)
376                                (eq (basic-combination-kind use) :local))
377                       (merges use))))
378                 (substitute-lvar-uses lvar value
379                                       (and lvar (eq (lvar-uses lvar) node)))
380                 (%delete-lvar-use node)
381                 (prog1
382                     (unlink-node node)
383                   (dolist (merge (merges))
384                     (merge-tail-sets merge)))))
385         (t (flush-dest value)
386            (unlink-node node))))
387
388 ;;; Make a CAST and insert it into IR1 before node NEXT.
389 (defun insert-cast-before (next lvar type policy)
390   (declare (type node next) (type lvar lvar) (type ctype type))
391   (with-ir1-environment-from-node next
392     (let* ((ctran (node-prev next))
393            (cast (make-cast lvar type policy))
394            (internal-ctran (make-ctran)))
395       (setf (ctran-next ctran) cast
396             (node-prev cast) ctran)
397       (use-ctran cast internal-ctran)
398       (link-node-to-previous-ctran next internal-ctran)
399       (setf (lvar-dest lvar) cast)
400       (reoptimize-lvar lvar)
401       (when (return-p next)
402         (node-ends-block cast))
403       (setf (block-attributep (block-flags (node-block cast))
404                               type-check type-asserted)
405             t)
406       cast)))
407 \f
408 ;;;; miscellaneous shorthand functions
409
410 ;;; Return the home (i.e. enclosing non-LET) CLAMBDA for NODE. Since
411 ;;; the LEXENV-LAMBDA may be deleted, we must chain up the
412 ;;; LAMBDA-CALL-LEXENV thread until we find a CLAMBDA that isn't
413 ;;; deleted, and then return its home.
414 (defun node-home-lambda (node)
415   (declare (type node node))
416   (do ((fun (lexenv-lambda (node-lexenv node))
417             (lexenv-lambda (lambda-call-lexenv fun))))
418       ((not (memq (functional-kind fun) '(:deleted :zombie)))
419        (lambda-home fun))
420     (when (eq (lambda-home fun) fun)
421       (return fun))))
422
423 #!-sb-fluid (declaim (inline node-block))
424 (defun node-block (node)
425   (ctran-block (node-prev node)))
426 (declaim (ftype (sfunction (node) component) node-component))
427 (defun node-component (node)
428   (block-component (node-block node)))
429 (declaim (ftype (sfunction (node) physenv) node-physenv))
430 (defun node-physenv (node)
431   (lambda-physenv (node-home-lambda node)))
432 #!-sb-fluid (declaim (inline node-dest))
433 (defun node-dest (node)
434   (awhen (node-lvar node) (lvar-dest it)))
435
436 #!-sb-fluid (declaim (inline node-stack-allocate-p))
437 (defun node-stack-allocate-p (node)
438   (awhen (node-lvar node)
439     (lvar-dynamic-extent it)))
440
441 (defun flushable-combination-p (call)
442   (declare (type combination call))
443   (let ((kind (combination-kind call))
444         (info (combination-fun-info call)))
445     (when (and (eq kind :known) (fun-info-p info))
446       (let ((attr (fun-info-attributes info)))
447         (when (and (not (ir1-attributep attr call))
448                    ;; FIXME: For now, don't consider potentially flushable
449                    ;; calls flushable when they have the CALL attribute.
450                    ;; Someday we should look at the functional args to
451                    ;; determine if they have any side effects.
452                    (if (policy call (= safety 3))
453                        (ir1-attributep attr flushable)
454                        (ir1-attributep attr unsafely-flushable)))
455           t)))))
456
457 ;;;; DYNAMIC-EXTENT related
458
459 (defun note-no-stack-allocation (lvar &key flush)
460   (do-uses (use (principal-lvar lvar))
461     (unless (or
462              ;; Don't complain about not being able to stack allocate constants.
463              (and (ref-p use) (constant-p (ref-leaf use)))
464              ;; If we're flushing, don't complain if we can flush the combination.
465              (and flush (combination-p use) (flushable-combination-p use)))
466       (let ((*compiler-error-context* use))
467         (compiler-notify "could not stack allocate the result of ~S"
468                          (find-original-source (node-source-path use)))))))
469
470 (defun use-good-for-dx-p (use dx &optional component)
471   ;; FIXME: Can casts point to LVARs in other components?
472   ;; RECHECK-DYNAMIC-EXTENT-LVARS assumes that they can't -- that is, that the
473   ;; PRINCIPAL-LVAR is always in the same component as the original one. It
474   ;; would be either good to have an explanation of why casts don't point
475   ;; across components, or an explanation of when they do it. ...in the
476   ;; meanwhile AVER that our assumption holds true.
477   (aver (or (not component) (eq component (node-component use))))
478   (or (dx-combination-p use dx)
479       (and (cast-p use)
480            (not (cast-type-check use))
481            (lvar-good-for-dx-p (cast-value use) dx component))
482       (and (trivial-lambda-var-ref-p use)
483            (let ((uses (lvar-uses (trivial-lambda-var-ref-lvar use))))
484              (or (eq use uses)
485                  (lvar-good-for-dx-p (trivial-lambda-var-ref-lvar use) dx component))))))
486
487 (defun lvar-good-for-dx-p (lvar dx &optional component)
488   (let ((uses (lvar-uses lvar)))
489     (if (listp uses)
490         (when uses
491           (every (lambda (use)
492                    (use-good-for-dx-p use dx component))
493                  uses))
494         (use-good-for-dx-p uses dx component))))
495
496 (defun known-dx-combination-p (use dx)
497   (and (eq (combination-kind use) :known)
498        (let ((info (combination-fun-info use)))
499          (or (awhen (fun-info-stack-allocate-result info)
500                (funcall it use dx))
501              (awhen (fun-info-result-arg info)
502                (let ((args (combination-args use)))
503                  (lvar-good-for-dx-p (if (zerop it)
504                                          (car args)
505                                          (nth it args))
506                                      dx)))))))
507
508 (defun dx-combination-p (use dx)
509   (and (combination-p use)
510        (or
511         ;; Known, and can do DX.
512         (known-dx-combination-p use dx)
513         ;; Possibly a not-yet-eliminated lambda which ends up returning the
514         ;; results of an actual known DX combination.
515         (let* ((fun (combination-fun use))
516                (ref (principal-lvar-use fun))
517                (clambda (when (ref-p ref)
518                           (ref-leaf ref)))
519                (creturn (when (lambda-p clambda)
520                           (lambda-return clambda)))
521                (result-use (when (return-p creturn)
522                              (principal-lvar-use (return-result creturn)))))
523           ;; FIXME: We should be able to deal with multiple uses here as well.
524           (and (dx-combination-p result-use dx)
525                (combination-args-flow-cleanly-p use result-use dx))))))
526
527 (defun combination-args-flow-cleanly-p (combination1 combination2 dx)
528   (labels ((recurse (combination)
529              (or (eq combination combination2)
530                  (if (known-dx-combination-p combination dx)
531                      (let ((dest (lvar-dest (combination-lvar combination))))
532                        (and (combination-p dest)
533                             (recurse dest)))
534                      (let* ((fun1 (combination-fun combination))
535                             (ref1 (principal-lvar-use fun1))
536                             (clambda1 (when (ref-p ref1) (ref-leaf ref1))))
537                        (when (lambda-p clambda1)
538                          (dolist (var (lambda-vars clambda1) t)
539                            (dolist (var-ref (lambda-var-refs var))
540                              (let ((dest (lvar-dest (ref-lvar var-ref))))
541                                (unless (and (combination-p dest) (recurse dest))
542                                  (return-from combination-args-flow-cleanly-p nil)))))))))))
543     (recurse combination1)))
544
545 (defun trivial-lambda-var-ref-p (use)
546   (and (ref-p use)
547        (let ((var (ref-leaf use)))
548          ;; lambda-var, no SETS, not explicitly indefinite-extent.
549          (when (and (lambda-var-p var) (not (lambda-var-sets var))
550                     (neq :indefinite (lambda-var-extent var)))
551            (let ((home (lambda-var-home var))
552                  (refs (lambda-var-refs var)))
553              ;; bound by a non-XEP system lambda, no other REFS
554              (when (and (lambda-system-lambda-p home)
555                         (neq :external (lambda-kind home))
556                         (eq use (car refs)) (not (cdr refs)))
557                ;; the LAMBDA this var is bound by has only a single REF, going
558                ;; to a combination
559                (let* ((lambda-refs (lambda-refs home))
560                       (primary (car lambda-refs)))
561                  (and (ref-p primary)
562                       (not (cdr lambda-refs))
563                       (combination-p (lvar-dest (ref-lvar primary)))))))))))
564
565 (defun trivial-lambda-var-ref-lvar (use)
566   (let* ((this (ref-leaf use))
567          (fun (lambda-var-home this))
568          (vars (lambda-vars fun))
569          (combination (lvar-dest (ref-lvar (car (lambda-refs fun)))))
570          (args (combination-args combination)))
571     (aver (= (length vars) (length args)))
572     (loop for var in vars
573           for arg in args
574           when (eq var this)
575           return arg)))
576
577 ;;; This needs to play nice with LVAR-GOOD-FOR-DX-P and friends.
578 (defun handle-nested-dynamic-extent-lvars (dx lvar &optional recheck-component)
579   (let ((uses (lvar-uses lvar)))
580     ;; DX value generators must end their blocks: see UPDATE-UVL-LIVE-SETS.
581     ;; Uses of mupltiple-use LVARs already end their blocks, so we just need
582     ;; to process uses of single-use LVARs.
583     (when (node-p uses)
584       (node-ends-block uses))
585     ;; If this LVAR's USE is good for DX, it is either a CAST, or it
586     ;; must be a regular combination whose arguments are potentially DX as well.
587     (flet ((recurse (use)
588              (etypecase use
589                (cast
590                 (handle-nested-dynamic-extent-lvars
591                  dx (cast-value use) recheck-component))
592                (combination
593                 (loop for arg in (combination-args use)
594                       ;; deleted args show up as NIL here
595                       when (and arg
596                                 (lvar-good-for-dx-p arg dx recheck-component))
597                       append (handle-nested-dynamic-extent-lvars
598                               dx arg recheck-component)))
599                (ref
600                 (let* ((other (trivial-lambda-var-ref-lvar use)))
601                   (unless (eq other lvar)
602                     (handle-nested-dynamic-extent-lvars
603                      dx other recheck-component)))))))
604       (cons (cons dx lvar)
605             (if (listp uses)
606                 (loop for use in uses
607                       when (use-good-for-dx-p use dx recheck-component)
608                       nconc (recurse use))
609                 (when (use-good-for-dx-p uses dx recheck-component)
610                   (recurse uses)))))))
611
612 ;;;;; BLOCK UTILS
613
614 (declaim (inline block-to-be-deleted-p))
615 (defun block-to-be-deleted-p (block)
616   (or (block-delete-p block)
617       (eq (functional-kind (block-home-lambda block)) :deleted)))
618
619 ;;; Checks whether NODE is in a block to be deleted
620 (declaim (inline node-to-be-deleted-p))
621 (defun node-to-be-deleted-p (node)
622   (block-to-be-deleted-p (node-block node)))
623
624 (declaim (ftype (sfunction (clambda) cblock) lambda-block))
625 (defun lambda-block (clambda)
626   (node-block (lambda-bind clambda)))
627 (declaim (ftype (sfunction (clambda) component) lambda-component))
628 (defun lambda-component (clambda)
629   (block-component (lambda-block clambda)))
630
631 (declaim (ftype (sfunction (cblock) node) block-start-node))
632 (defun block-start-node (block)
633   (ctran-next (block-start block)))
634
635 ;;; Return the enclosing cleanup for environment of the first or last
636 ;;; node in BLOCK.
637 (defun block-start-cleanup (block)
638   (node-enclosing-cleanup (block-start-node block)))
639 (defun block-end-cleanup (block)
640   (node-enclosing-cleanup (block-last block)))
641
642 ;;; Return the non-LET LAMBDA that holds BLOCK's code, or NIL
643 ;;; if there is none.
644 ;;;
645 ;;; There can legitimately be no home lambda in dead code early in the
646 ;;; IR1 conversion process, e.g. when IR1-converting the SETQ form in
647 ;;;   (BLOCK B (RETURN-FROM B) (SETQ X 3))
648 ;;; where the block is just a placeholder during parsing and doesn't
649 ;;; actually correspond to code which will be written anywhere.
650 (declaim (ftype (sfunction (cblock) (or clambda null)) block-home-lambda-or-null))
651 (defun block-home-lambda-or-null (block)
652   (if (node-p (block-last block))
653       ;; This is the old CMU CL way of doing it.
654       (node-home-lambda (block-last block))
655       ;; Now that SBCL uses this operation more aggressively than CMU
656       ;; CL did, the old CMU CL way of doing it can fail in two ways.
657       ;;   1. It can fail in a few cases even when a meaningful home
658       ;;      lambda exists, e.g. in IR1-CONVERT of one of the legs of
659       ;;      an IF.
660       ;;   2. It can fail when converting a form which is born orphaned
661       ;;      so that it never had a meaningful home lambda, e.g. a form
662       ;;      which follows a RETURN-FROM or GO form.
663       (let ((pred-list (block-pred block)))
664         ;; To deal with case 1, we reason that
665         ;; previous-in-target-execution-order blocks should be in the
666         ;; same lambda, and that they seem in practice to be
667         ;; previous-in-compilation-order blocks too, so we look back
668         ;; to find one which is sufficiently initialized to tell us
669         ;; what the home lambda is.
670         (if pred-list
671             ;; We could get fancy about this, flooding through the
672             ;; graph of all the previous blocks, but in practice it
673             ;; seems to work just to grab the first previous block and
674             ;; use it.
675             (node-home-lambda (block-last (first pred-list)))
676             ;; In case 2, we end up with an empty PRED-LIST and
677             ;; have to punt: There's no home lambda.
678             nil))))
679
680 ;;; Return the non-LET LAMBDA that holds BLOCK's code.
681 (declaim (ftype (sfunction (cblock) clambda) block-home-lambda))
682 (defun block-home-lambda (block)
683   (block-home-lambda-or-null block))
684
685 ;;; Return the IR1 physical environment for BLOCK.
686 (declaim (ftype (sfunction (cblock) physenv) block-physenv))
687 (defun block-physenv (block)
688   (lambda-physenv (block-home-lambda block)))
689
690 ;;; Return the Top Level Form number of PATH, i.e. the ordinal number
691 ;;; of its original source's top level form in its compilation unit.
692 (defun source-path-tlf-number (path)
693   (declare (list path))
694   (car (last path)))
695
696 ;;; Return the (reversed) list for the PATH in the original source
697 ;;; (with the Top Level Form number last).
698 (defun source-path-original-source (path)
699   (declare (list path) (inline member))
700   (cddr (member 'original-source-start path :test #'eq)))
701
702 ;;; Return the Form Number of PATH's original source inside the Top
703 ;;; Level Form that contains it. This is determined by the order that
704 ;;; we walk the subforms of the top level source form.
705 (defun source-path-form-number (path)
706   (declare (list path) (inline member))
707   (cadr (member 'original-source-start path :test #'eq)))
708
709 ;;; Return a list of all the enclosing forms not in the original
710 ;;; source that converted to get to this form, with the immediate
711 ;;; source for node at the start of the list.
712 (defun source-path-forms (path)
713   (subseq path 0 (position 'original-source-start path)))
714
715 ;;; Return the innermost source form for NODE.
716 (defun node-source-form (node)
717   (declare (type node node))
718   (let* ((path (node-source-path node))
719          (forms (source-path-forms path)))
720     (if forms
721         (first forms)
722         (values (find-original-source path)))))
723
724 ;;; Return NODE-SOURCE-FORM, T if lvar has a single use, otherwise
725 ;;; NIL, NIL.
726 (defun lvar-source (lvar)
727   (let ((use (lvar-uses lvar)))
728     (if (listp use)
729         (values nil nil)
730         (values (node-source-form use) t))))
731
732 ;;; Return the unique node, delivering a value to LVAR.
733 #!-sb-fluid (declaim (inline lvar-use))
734 (defun lvar-use (lvar)
735   (the (not list) (lvar-uses lvar)))
736
737 #!-sb-fluid (declaim (inline lvar-has-single-use-p))
738 (defun lvar-has-single-use-p (lvar)
739   (typep (lvar-uses lvar) '(not list)))
740
741 ;;; Return the LAMBDA that is CTRAN's home, or NIL if there is none.
742 (declaim (ftype (sfunction (ctran) (or clambda null))
743                 ctran-home-lambda-or-null))
744 (defun ctran-home-lambda-or-null (ctran)
745   ;; KLUDGE: This function is a post-CMU-CL hack by WHN, and this
746   ;; implementation might not be quite right, or might be uglier than
747   ;; necessary. It appears that the original Python never found a need
748   ;; to do this operation. The obvious things based on
749   ;; NODE-HOME-LAMBDA of CTRAN-USE usually work; then if that fails,
750   ;; BLOCK-HOME-LAMBDA of CTRAN-BLOCK works, given that we
751   ;; generalize it enough to grovel harder when the simple CMU CL
752   ;; approach fails, and furthermore realize that in some exceptional
753   ;; cases it might return NIL. -- WHN 2001-12-04
754   (cond ((ctran-use ctran)
755          (node-home-lambda (ctran-use ctran)))
756         ((ctran-block ctran)
757          (block-home-lambda-or-null (ctran-block ctran)))
758         (t
759          (bug "confused about home lambda for ~S" ctran))))
760
761 ;;; Return the LAMBDA that is CTRAN's home.
762 (declaim (ftype (sfunction (ctran) clambda) ctran-home-lambda))
763 (defun ctran-home-lambda (ctran)
764   (ctran-home-lambda-or-null ctran))
765
766 (declaim (inline cast-single-value-p))
767 (defun cast-single-value-p (cast)
768   (not (values-type-p (cast-asserted-type cast))))
769
770 #!-sb-fluid (declaim (inline lvar-single-value-p))
771 (defun lvar-single-value-p (lvar)
772   (or (not lvar)
773       (let ((dest (lvar-dest lvar)))
774         (typecase dest
775           ((or creturn exit)
776            nil)
777           (mv-combination
778            (eq (basic-combination-fun dest) lvar))
779           (cast
780            (locally
781                (declare (notinline lvar-single-value-p))
782              (and (cast-single-value-p dest)
783                   (lvar-single-value-p (node-lvar dest)))))
784           (t
785            t)))))
786
787 (defun principal-lvar-end (lvar)
788   (loop for prev = lvar then (node-lvar dest)
789         for dest = (and prev (lvar-dest prev))
790         while (cast-p dest)
791         finally (return (values dest prev))))
792
793 (defun principal-lvar-single-valuify (lvar)
794   (loop for prev = lvar then (node-lvar dest)
795         for dest = (and prev (lvar-dest prev))
796         while (cast-p dest)
797         do (setf (node-derived-type dest)
798                  (make-short-values-type (list (single-value-type
799                                                 (node-derived-type dest)))))
800         (reoptimize-lvar prev)))
801 \f
802 ;;; Return a new LEXENV just like DEFAULT except for the specified
803 ;;; slot values. Values for the alist slots are NCONCed to the
804 ;;; beginning of the current value, rather than replacing it entirely.
805 (defun make-lexenv (&key (default *lexenv*)
806                          funs vars blocks tags
807                          type-restrictions
808                          (lambda (lexenv-lambda default))
809                          (cleanup (lexenv-cleanup default))
810                          (handled-conditions (lexenv-handled-conditions default))
811                          (disabled-package-locks
812                           (lexenv-disabled-package-locks default))
813                          (policy (lexenv-policy default))
814                          (user-data (lexenv-user-data default)))
815   (macrolet ((frob (var slot)
816                `(let ((old (,slot default)))
817                   (if ,var
818                       (nconc ,var old)
819                       old))))
820     (internal-make-lexenv
821      (frob funs lexenv-funs)
822      (frob vars lexenv-vars)
823      (frob blocks lexenv-blocks)
824      (frob tags lexenv-tags)
825      (frob type-restrictions lexenv-type-restrictions)
826      lambda
827      cleanup handled-conditions disabled-package-locks
828      policy
829      user-data)))
830
831 ;;; Makes a LEXENV, suitable for using in a MACROLET introduced
832 ;;; macroexpander
833 (defun make-restricted-lexenv (lexenv)
834   (flet ((fun-good-p (fun)
835            (destructuring-bind (name . thing) fun
836              (declare (ignore name))
837              (etypecase thing
838                (functional nil)
839                (global-var t)
840                (cons (aver (eq (car thing) 'macro))
841                      t))))
842          (var-good-p (var)
843            (destructuring-bind (name . thing) var
844              (declare (ignore name))
845              (etypecase thing
846                ;; The evaluator will mark lexicals with :BOGUS when it
847                ;; translates an interpreter lexenv to a compiler
848                ;; lexenv.
849                ((or leaf #!+sb-eval (member :bogus)) nil)
850                (cons (aver (eq (car thing) 'macro))
851                      t)
852                (heap-alien-info nil)))))
853     (internal-make-lexenv
854      (remove-if-not #'fun-good-p (lexenv-funs lexenv))
855      (remove-if-not #'var-good-p (lexenv-vars lexenv))
856      nil
857      nil
858      (lexenv-type-restrictions lexenv) ; XXX
859      nil
860      nil
861      (lexenv-handled-conditions lexenv)
862      (lexenv-disabled-package-locks lexenv)
863      (lexenv-policy lexenv)
864      (lexenv-user-data lexenv))))
865 \f
866 ;;;; flow/DFO/component hackery
867
868 ;;; Join BLOCK1 and BLOCK2.
869 (defun link-blocks (block1 block2)
870   (declare (type cblock block1 block2))
871   (setf (block-succ block1)
872         (if (block-succ block1)
873             (%link-blocks block1 block2)
874             (list block2)))
875   (push block1 (block-pred block2))
876   (values))
877 (defun %link-blocks (block1 block2)
878   (declare (type cblock block1 block2))
879   (let ((succ1 (block-succ block1)))
880     (aver (not (memq block2 succ1)))
881     (cons block2 succ1)))
882
883 ;;; This is like LINK-BLOCKS, but we separate BLOCK1 and BLOCK2. If
884 ;;; this leaves a successor with a single predecessor that ends in an
885 ;;; IF, then set BLOCK-TEST-MODIFIED so that any test constraint will
886 ;;; now be able to be propagated to the successor.
887 (defun unlink-blocks (block1 block2)
888   (declare (type cblock block1 block2))
889   (let ((succ1 (block-succ block1)))
890     (if (eq block2 (car succ1))
891         (setf (block-succ block1) (cdr succ1))
892         (do ((succ (cdr succ1) (cdr succ))
893              (prev succ1 succ))
894             ((eq (car succ) block2)
895              (setf (cdr prev) (cdr succ)))
896           (aver succ))))
897
898   (let ((new-pred (delq block1 (block-pred block2))))
899     (setf (block-pred block2) new-pred)
900     (when (singleton-p new-pred)
901       (let ((pred-block (first new-pred)))
902         (when (if-p (block-last pred-block))
903           (setf (block-test-modified pred-block) t)))))
904   (values))
905
906 ;;; Swing the succ/pred link between BLOCK and OLD to be between BLOCK
907 ;;; and NEW. If BLOCK ends in an IF, then we have to fix up the
908 ;;; consequent/alternative blocks to point to NEW. We also set
909 ;;; BLOCK-TEST-MODIFIED so that any test constraint will be applied to
910 ;;; the new successor.
911 (defun change-block-successor (block old new)
912   (declare (type cblock new old block))
913   (unlink-blocks block old)
914   (let ((last (block-last block))
915         (comp (block-component block)))
916     (setf (component-reanalyze comp) t)
917     (typecase last
918       (cif
919        (setf (block-test-modified block) t)
920        (let* ((succ-left (block-succ block))
921               (new (if (and (eq new (component-tail comp))
922                             succ-left)
923                        (first succ-left)
924                        new)))
925          (unless (memq new succ-left)
926            (link-blocks block new))
927          (macrolet ((frob (slot)
928                       `(when (eq (,slot last) old)
929                          (setf (,slot last) new))))
930            (frob if-consequent)
931            (frob if-alternative)
932            (when (eq (if-consequent last)
933                      (if-alternative last))
934              (reoptimize-component (block-component block) :maybe)))))
935       (t
936        (unless (memq new (block-succ block))
937          (link-blocks block new)))))
938
939   (values))
940
941 ;;; Unlink a block from the next/prev chain. We also null out the
942 ;;; COMPONENT.
943 (declaim (ftype (sfunction (cblock) (values)) remove-from-dfo))
944 (defun remove-from-dfo (block)
945   (let ((next (block-next block))
946         (prev (block-prev block)))
947     (setf (block-component block) nil)
948     (setf (block-next prev) next)
949     (setf (block-prev next) prev))
950   (values))
951
952 ;;; Add BLOCK to the next/prev chain following AFTER. We also set the
953 ;;; COMPONENT to be the same as for AFTER.
954 (defun add-to-dfo (block after)
955   (declare (type cblock block after))
956   (let ((next (block-next after))
957         (comp (block-component after)))
958     (aver (not (eq (component-kind comp) :deleted)))
959     (setf (block-component block) comp)
960     (setf (block-next after) block)
961     (setf (block-prev block) after)
962     (setf (block-next block) next)
963     (setf (block-prev next) block))
964   (values))
965
966 ;;; List all NLX-INFOs which BLOCK can exit to.
967 ;;;
968 ;;; We hope that no cleanup actions are performed in the middle of
969 ;;; BLOCK, so it is enough to look only at cleanups in the block
970 ;;; end. The tricky thing is a special cleanup block; all its nodes
971 ;;; have the same cleanup info, corresponding to the start, so the
972 ;;; same approach returns safe result.
973 (defun map-block-nlxes (fun block &optional dx-cleanup-fun)
974   (loop for cleanup = (block-end-cleanup block)
975         then (node-enclosing-cleanup (cleanup-mess-up cleanup))
976         while cleanup
977         do (let ((mess-up (cleanup-mess-up cleanup)))
978              (case (cleanup-kind cleanup)
979                ((:block :tagbody)
980                 (aver (entry-p mess-up))
981                 (loop for exit in (entry-exits mess-up)
982                       for nlx-info = (exit-nlx-info exit)
983                       do (funcall fun nlx-info)))
984                ((:catch :unwind-protect)
985                 (aver (combination-p mess-up))
986                 (let* ((arg-lvar (first (basic-combination-args mess-up)))
987                        (nlx-info (constant-value (ref-leaf (lvar-use arg-lvar)))))
988                 (funcall fun nlx-info)))
989                ((:dynamic-extent)
990                 (when dx-cleanup-fun
991                   (funcall dx-cleanup-fun cleanup)))))))
992
993 ;;; Set the FLAG for all the blocks in COMPONENT to NIL, except for
994 ;;; the head and tail which are set to T.
995 (declaim (ftype (sfunction (component) (values)) clear-flags))
996 (defun clear-flags (component)
997   (let ((head (component-head component))
998         (tail (component-tail component)))
999     (setf (block-flag head) t)
1000     (setf (block-flag tail) t)
1001     (do-blocks (block component)
1002       (setf (block-flag block) nil)))
1003   (values))
1004
1005 ;;; Make a component with no blocks in it. The BLOCK-FLAG is initially
1006 ;;; true in the head and tail blocks.
1007 (declaim (ftype (sfunction () component) make-empty-component))
1008 (defun make-empty-component ()
1009   (let* ((head (make-block-key :start nil :component nil))
1010          (tail (make-block-key :start nil :component nil))
1011          (res (make-component head tail)))
1012     (setf (block-flag head) t)
1013     (setf (block-flag tail) t)
1014     (setf (block-component head) res)
1015     (setf (block-component tail) res)
1016     (setf (block-next head) tail)
1017     (setf (block-prev tail) head)
1018     res))
1019
1020 ;;; Make NODE the LAST node in its block, splitting the block if necessary.
1021 ;;; The new block is added to the DFO immediately following NODE's block.
1022 (defun node-ends-block (node)
1023   (declare (type node node))
1024   (let* ((block (node-block node))
1025          (start (node-next node))
1026          (last (block-last block)))
1027     (check-type last node)
1028     (unless (eq last node)
1029       (aver (and (eq (ctran-kind start) :inside-block)
1030                  (not (block-delete-p block))))
1031       (let* ((succ (block-succ block))
1032              (new-block
1033               (make-block-key :start start
1034                               :component (block-component block)
1035                               :succ succ :last last)))
1036         (setf (ctran-kind start) :block-start)
1037         (setf (ctran-use start) nil)
1038         (setf (block-last block) node)
1039         (setf (node-next node) nil)
1040         (dolist (b succ)
1041           (setf (block-pred b)
1042                 (cons new-block (remove block (block-pred b)))))
1043         (setf (block-succ block) ())
1044         (link-blocks block new-block)
1045         (add-to-dfo new-block block)
1046         (setf (component-reanalyze (block-component block)) t)
1047
1048         (do ((ctran start (node-next (ctran-next ctran))))
1049             ((not ctran))
1050           (setf (ctran-block ctran) new-block))
1051
1052         (setf (block-type-asserted block) t)
1053         (setf (block-test-modified block) t))))
1054   (values))
1055 \f
1056 ;;;; deleting stuff
1057
1058 ;;; Deal with deleting the last (read) reference to a LAMBDA-VAR.
1059 (defun delete-lambda-var (leaf)
1060   (declare (type lambda-var leaf))
1061
1062   (setf (lambda-var-deleted leaf) t)
1063   ;; Iterate over all local calls flushing the corresponding argument,
1064   ;; allowing the computation of the argument to be deleted. We also
1065   ;; mark the LET for reoptimization, since it may be that we have
1066   ;; deleted its last variable.
1067   (let* ((fun (lambda-var-home leaf))
1068          (n (position leaf (lambda-vars fun))))
1069     (dolist (ref (leaf-refs fun))
1070       (let* ((lvar (node-lvar ref))
1071              (dest (and lvar (lvar-dest lvar))))
1072         (when (and (combination-p dest)
1073                    (eq (basic-combination-fun dest) lvar)
1074                    (eq (basic-combination-kind dest) :local))
1075           (let* ((args (basic-combination-args dest))
1076                  (arg (elt args n)))
1077             (reoptimize-lvar arg)
1078             (flush-dest arg)
1079             (setf (elt args n) nil))))))
1080
1081   ;; The LAMBDA-VAR may still have some SETs, but this doesn't cause
1082   ;; too much difficulty, since we can efficiently implement
1083   ;; write-only variables. We iterate over the SETs, marking their
1084   ;; blocks for dead code flushing, since we can delete SETs whose
1085   ;; value is unused.
1086   (dolist (set (lambda-var-sets leaf))
1087     (setf (block-flush-p (node-block set)) t))
1088
1089   (values))
1090
1091 ;;; Note that something interesting has happened to VAR.
1092 (defun reoptimize-lambda-var (var)
1093   (declare (type lambda-var var))
1094   (let ((fun (lambda-var-home var)))
1095     ;; We only deal with LET variables, marking the corresponding
1096     ;; initial value arg as needing to be reoptimized.
1097     (when (and (eq (functional-kind fun) :let)
1098                (leaf-refs var))
1099       (do ((args (basic-combination-args
1100                   (lvar-dest (node-lvar (first (leaf-refs fun)))))
1101                  (cdr args))
1102            (vars (lambda-vars fun) (cdr vars)))
1103           ((eq (car vars) var)
1104            (reoptimize-lvar (car args))))))
1105   (values))
1106
1107 ;;; Delete a function that has no references. This need only be called
1108 ;;; on functions that never had any references, since otherwise
1109 ;;; DELETE-REF will handle the deletion.
1110 (defun delete-functional (fun)
1111   (aver (and (null (leaf-refs fun))
1112              (not (functional-entry-fun fun))))
1113   (etypecase fun
1114     (optional-dispatch (delete-optional-dispatch fun))
1115     (clambda (delete-lambda fun)))
1116   (values))
1117
1118 ;;; Deal with deleting the last reference to a CLAMBDA, which means
1119 ;;; that the lambda is unreachable, so that its body may be
1120 ;;; deleted. We set FUNCTIONAL-KIND to :DELETED and rely on
1121 ;;; IR1-OPTIMIZE to delete its blocks.
1122 (defun delete-lambda (clambda)
1123   (declare (type clambda clambda))
1124   (let ((original-kind (functional-kind clambda))
1125         (bind (lambda-bind clambda)))
1126     (aver (not (member original-kind '(:deleted :toplevel))))
1127     (aver (not (functional-has-external-references-p clambda)))
1128     (aver (or (eq original-kind :zombie) bind))
1129     (setf (functional-kind clambda) :deleted)
1130     (setf (lambda-bind clambda) nil)
1131
1132     (labels ((delete-children (lambda)
1133                (dolist (child (lambda-children lambda))
1134                  (cond ((eq (functional-kind child) :deleted)
1135                         (delete-children child))
1136                        (t
1137                         (delete-lambda child))))
1138                (setf (lambda-children lambda) nil)
1139                (setf (lambda-parent lambda) nil)))
1140       (delete-children clambda))
1141
1142     ;; (The IF test is (FUNCTIONAL-SOMEWHAT-LETLIKE-P CLAMBDA), except
1143     ;; that we're using the old value of the KIND slot, not the
1144     ;; current slot value, which has now been set to :DELETED.)
1145     (case original-kind
1146       (:zombie)
1147       ((:let :mv-let :assignment)
1148        (let ((bind-block (node-block bind)))
1149          (mark-for-deletion bind-block))
1150        (let ((home (lambda-home clambda)))
1151          (setf (lambda-lets home) (delete clambda (lambda-lets home))))
1152        ;; KLUDGE: In presence of NLEs we cannot always understand that
1153        ;; LET's BIND dominates its body [for a LET "its" body is not
1154        ;; quite its]; let's delete too dangerous for IR2 stuff. --
1155        ;; APD, 2004-01-01
1156        (dolist (var (lambda-vars clambda))
1157          (flet ((delete-node (node)
1158                   (mark-for-deletion (node-block node))))
1159          (mapc #'delete-node (leaf-refs var))
1160          (mapc #'delete-node (lambda-var-sets var)))))
1161       (t
1162        ;; Function has no reachable references.
1163        (dolist (ref (lambda-refs clambda))
1164          (mark-for-deletion (node-block ref)))
1165        ;; If the function isn't a LET, we unlink the function head
1166        ;; and tail from the component head and tail to indicate that
1167        ;; the code is unreachable. We also delete the function from
1168        ;; COMPONENT-LAMBDAS (it won't be there before local call
1169        ;; analysis, but no matter.) If the lambda was never
1170        ;; referenced, we give a note.
1171        (let* ((bind-block (node-block bind))
1172               (component (block-component bind-block))
1173               (return (lambda-return clambda))
1174               (return-block (and return (node-block return))))
1175          (unless (leaf-ever-used clambda)
1176            (let ((*compiler-error-context* bind))
1177              (compiler-notify 'code-deletion-note
1178                               :format-control "deleting unused function~:[.~;~:*~%  ~S~]"
1179                               :format-arguments (list (leaf-debug-name clambda)))))
1180          (unless (block-delete-p bind-block)
1181            (unlink-blocks (component-head component) bind-block))
1182          (when (and return-block (not (block-delete-p return-block)))
1183            (mark-for-deletion return-block)
1184            (unlink-blocks return-block (component-tail component)))
1185          (setf (component-reanalyze component) t)
1186          (let ((tails (lambda-tail-set clambda)))
1187            (setf (tail-set-funs tails)
1188                  (delete clambda (tail-set-funs tails)))
1189            (setf (lambda-tail-set clambda) nil))
1190          (setf (component-lambdas component)
1191                (delq clambda (component-lambdas component))))))
1192
1193     ;; If the lambda is an XEP, then we null out the ENTRY-FUN in its
1194     ;; ENTRY-FUN so that people will know that it is not an entry
1195     ;; point anymore.
1196     (when (eq original-kind :external)
1197       (let ((fun (functional-entry-fun clambda)))
1198         (setf (functional-entry-fun fun) nil)
1199         (when (optional-dispatch-p fun)
1200           (delete-optional-dispatch fun)))))
1201
1202   (values))
1203
1204 ;;; Deal with deleting the last reference to an OPTIONAL-DISPATCH. We
1205 ;;; have to be a bit more careful than with lambdas, since DELETE-REF
1206 ;;; is used both before and after local call analysis. Afterward, all
1207 ;;; references to still-existing OPTIONAL-DISPATCHes have been moved
1208 ;;; to the XEP, leaving it with no references at all. So we look at
1209 ;;; the XEP to see whether an optional-dispatch is still really being
1210 ;;; used. But before local call analysis, there are no XEPs, and all
1211 ;;; references are direct.
1212 ;;;
1213 ;;; When we do delete the OPTIONAL-DISPATCH, we grovel all of its
1214 ;;; entry-points, making them be normal lambdas, and then deleting the
1215 ;;; ones with no references. This deletes any e-p lambdas that were
1216 ;;; either never referenced, or couldn't be deleted when the last
1217 ;;; reference was deleted (due to their :OPTIONAL kind.)
1218 ;;;
1219 ;;; Note that the last optional entry point may alias the main entry,
1220 ;;; so when we process the main entry, its KIND may have been changed
1221 ;;; to NIL or even converted to a LETlike value.
1222 (defun delete-optional-dispatch (leaf)
1223   (declare (type optional-dispatch leaf))
1224   (let ((entry (functional-entry-fun leaf)))
1225     (unless (and entry (leaf-refs entry))
1226       (aver (or (not entry) (eq (functional-kind entry) :deleted)))
1227       (setf (functional-kind leaf) :deleted)
1228
1229       (flet ((frob (fun)
1230                (unless (eq (functional-kind fun) :deleted)
1231                  (aver (eq (functional-kind fun) :optional))
1232                  (setf (functional-kind fun) nil)
1233                  (let ((refs (leaf-refs fun)))
1234                    (cond ((null refs)
1235                           (delete-lambda fun))
1236                          ((null (rest refs))
1237                           (or (maybe-let-convert fun)
1238                               (maybe-convert-to-assignment fun)))
1239                          (t
1240                           (maybe-convert-to-assignment fun)))))))
1241
1242         (dolist (ep (optional-dispatch-entry-points leaf))
1243           (when (promise-ready-p ep)
1244             (frob (force ep))))
1245         (when (optional-dispatch-more-entry leaf)
1246           (frob (optional-dispatch-more-entry leaf)))
1247         (let ((main (optional-dispatch-main-entry leaf)))
1248           (when entry
1249             (setf (functional-entry-fun entry) main)
1250             (setf (functional-entry-fun main) entry))
1251           (when (eq (functional-kind main) :optional)
1252             (frob main))))))
1253
1254   (values))
1255
1256 (defun note-local-functional (fun)
1257   (declare (type functional fun))
1258   (when (and (leaf-has-source-name-p fun)
1259              (eq (leaf-source-name fun) (functional-debug-name fun)))
1260     (let ((name (leaf-source-name fun)))
1261       (let ((defined-fun (gethash name *free-funs*)))
1262         (when (and defined-fun
1263                    (defined-fun-p defined-fun)
1264                    (eq (defined-fun-functional defined-fun) fun))
1265           (remhash name *free-funs*))))))
1266
1267 ;;; Return functional for DEFINED-FUN which has been converted in policy
1268 ;;; corresponding to the current one, or NIL if no such functional exists.
1269 ;;;
1270 ;;; Also check that the parent of the functional is visible in the current
1271 ;;; environment.
1272 (defun defined-fun-functional (defined-fun)
1273   (let ((functionals (defined-fun-functionals defined-fun)))
1274     (when functionals
1275       (let* ((sample (car functionals))
1276              (there (lambda-parent (if (lambda-p sample)
1277                                        sample
1278                                        (optional-dispatch-main-entry sample)))))
1279         (when there
1280           (labels ((lookup (here)
1281                      (unless (eq here there)
1282                        (if here
1283                            (lookup (lambda-parent here))
1284                            ;; We looked up all the way up, and didn't find the parent
1285                            ;; of the functional -- therefore it is nested in a lambda
1286                            ;; we don't see, so return nil.
1287                            (return-from defined-fun-functional nil)))))
1288             (lookup (lexenv-lambda *lexenv*)))))
1289       ;; Now find a functional whose policy matches the current one, if we already
1290       ;; have one.
1291       (let ((policy (lexenv-%policy *lexenv*)))
1292         (dolist (functional functionals)
1293           (when (equal policy (lexenv-%policy (functional-lexenv functional)))
1294             (return functional)))))))
1295
1296 ;;; Do stuff to delete the semantic attachments of a REF node. When
1297 ;;; this leaves zero or one reference, we do a type dispatch off of
1298 ;;; the leaf to determine if a special action is appropriate.
1299 (defun delete-ref (ref)
1300   (declare (type ref ref))
1301   (let* ((leaf (ref-leaf ref))
1302          (refs (delq ref (leaf-refs leaf))))
1303     (setf (leaf-refs leaf) refs)
1304
1305     (cond ((null refs)
1306            (typecase leaf
1307              (lambda-var
1308               (delete-lambda-var leaf))
1309              (clambda
1310               (ecase (functional-kind leaf)
1311                 ((nil :let :mv-let :assignment :escape :cleanup)
1312                  (aver (null (functional-entry-fun leaf)))
1313                  (delete-lambda leaf))
1314                 (:external
1315                  (unless (functional-has-external-references-p leaf)
1316                    (delete-lambda leaf)))
1317                 ((:deleted :zombie :optional))))
1318              (optional-dispatch
1319               (unless (eq (functional-kind leaf) :deleted)
1320                 (delete-optional-dispatch leaf)))))
1321           ((null (rest refs))
1322            (typecase leaf
1323              (clambda (or (maybe-let-convert leaf)
1324                           (maybe-convert-to-assignment leaf)))
1325              (lambda-var (reoptimize-lambda-var leaf))))
1326           (t
1327            (typecase leaf
1328              (clambda (maybe-convert-to-assignment leaf))))))
1329
1330   (values))
1331
1332 ;;; This function is called by people who delete nodes; it provides a
1333 ;;; way to indicate that the value of a lvar is no longer used. We
1334 ;;; null out the LVAR-DEST, set FLUSH-P in the blocks containing uses
1335 ;;; of LVAR and set COMPONENT-REOPTIMIZE.
1336 (defun flush-dest (lvar)
1337   (declare (type (or lvar null) lvar))
1338   (unless (null lvar)
1339     (when (lvar-dynamic-extent lvar)
1340       (note-no-stack-allocation lvar :flush t))
1341     (setf (lvar-dest lvar) nil)
1342     (flush-lvar-externally-checkable-type lvar)
1343     (do-uses (use lvar)
1344       (let ((prev (node-prev use)))
1345         (let ((block (ctran-block prev)))
1346           (reoptimize-component (block-component block) t)
1347           (setf (block-attributep (block-flags block)
1348                                   flush-p type-asserted type-check)
1349                 t)))
1350       (setf (node-lvar use) nil))
1351     (setf (lvar-uses lvar) nil))
1352   (values))
1353
1354 (defun delete-dest (lvar)
1355   (when lvar
1356     (let* ((dest (lvar-dest lvar))
1357            (prev (node-prev dest)))
1358       (let ((block (ctran-block prev)))
1359         (unless (block-delete-p block)
1360           (mark-for-deletion block))))))
1361
1362 ;;; Queue the block for deletion
1363 (defun delete-block-lazily (block)
1364   (declare (type cblock block))
1365   (unless (block-delete-p block)
1366     (setf (block-delete-p block) t)
1367     (push block (component-delete-blocks (block-component block)))))
1368
1369 ;;; Do a graph walk backward from BLOCK, marking all predecessor
1370 ;;; blocks with the DELETE-P flag.
1371 (defun mark-for-deletion (block)
1372   (declare (type cblock block))
1373   (let* ((component (block-component block))
1374          (head (component-head component)))
1375     (labels ((helper (block)
1376                (delete-block-lazily block)
1377                (dolist (pred (block-pred block))
1378                  (unless (or (block-delete-p pred)
1379                              (eq pred head))
1380                    (helper pred)))))
1381       (unless (block-delete-p block)
1382         (helper block)
1383         (setf (component-reanalyze component) t))))
1384   (values))
1385
1386 ;;; This function does what is necessary to eliminate the code in it
1387 ;;; from the IR1 representation. This involves unlinking it from its
1388 ;;; predecessors and successors and deleting various node-specific
1389 ;;; semantic information. BLOCK must be already removed from
1390 ;;; COMPONENT-DELETE-BLOCKS.
1391 (defun delete-block (block &optional silent)
1392   (declare (type cblock block))
1393   (aver (block-component block))      ; else block is already deleted!
1394   #!+high-security (aver (not (memq block (component-delete-blocks (block-component block)))))
1395   (unless silent
1396     (note-block-deletion block))
1397   (setf (block-delete-p block) t)
1398
1399   (dolist (b (block-pred block))
1400     (unlink-blocks b block)
1401     ;; In bug 147 the almost-all-blocks-have-a-successor invariant was
1402     ;; broken when successors were deleted without setting the
1403     ;; BLOCK-DELETE-P flags of their predececessors. Make sure that
1404     ;; doesn't happen again.
1405     (aver (not (and (null (block-succ b))
1406                     (not (block-delete-p b))
1407                     (not (eq b (component-head (block-component b))))))))
1408   (dolist (b (block-succ block))
1409     (unlink-blocks block b))
1410
1411   (do-nodes-carefully (node block)
1412     (when (valued-node-p node)
1413       (delete-lvar-use node))
1414     (etypecase node
1415       (ref (delete-ref node))
1416       (cif (flush-dest (if-test node)))
1417       ;; The next two cases serve to maintain the invariant that a LET
1418       ;; always has a well-formed COMBINATION, REF and BIND. We delete
1419       ;; the lambda whenever we delete any of these, but we must be
1420       ;; careful that this LET has not already been partially deleted.
1421       (basic-combination
1422        (when (and (eq (basic-combination-kind node) :local)
1423                   ;; Guards COMBINATION-LAMBDA agains the REF being deleted.
1424                   (lvar-uses (basic-combination-fun node)))
1425          (let ((fun (combination-lambda node)))
1426            ;; If our REF was the second-to-last ref, and has been
1427            ;; deleted, then FUN may be a LET for some other
1428            ;; combination.
1429            (when (and (functional-letlike-p fun)
1430                       (eq (let-combination fun) node))
1431              (delete-lambda fun))))
1432        (flush-dest (basic-combination-fun node))
1433        (dolist (arg (basic-combination-args node))
1434          (when arg (flush-dest arg))))
1435       (bind
1436        (let ((lambda (bind-lambda node)))
1437          (unless (eq (functional-kind lambda) :deleted)
1438            (delete-lambda lambda))))
1439       (exit
1440        (let ((value (exit-value node))
1441              (entry (exit-entry node)))
1442          (when value
1443            (flush-dest value))
1444          (when entry
1445            (setf (entry-exits entry)
1446                  (delq node (entry-exits entry))))))
1447       (entry
1448        (dolist (exit (entry-exits node))
1449          (mark-for-deletion (node-block exit)))
1450        (let ((home (node-home-lambda node)))
1451          (setf (lambda-entries home) (delq node (lambda-entries home)))))
1452       (creturn
1453        (flush-dest (return-result node))
1454        (delete-return node))
1455       (cset
1456        (flush-dest (set-value node))
1457        (let ((var (set-var node)))
1458          (setf (basic-var-sets var)
1459                (delete node (basic-var-sets var)))))
1460       (cast
1461        (flush-dest (cast-value node)))))
1462
1463   (remove-from-dfo block)
1464   (values))
1465
1466 ;;; Do stuff to indicate that the return node NODE is being deleted.
1467 (defun delete-return (node)
1468   (declare (type creturn node))
1469   (let* ((fun (return-lambda node))
1470          (tail-set (lambda-tail-set fun)))
1471     (aver (lambda-return fun))
1472     (setf (lambda-return fun) nil)
1473     (when (and tail-set (not (find-if #'lambda-return
1474                                       (tail-set-funs tail-set))))
1475       (setf (tail-set-type tail-set) *empty-type*)))
1476   (values))
1477
1478 ;;; If any of the VARS in FUN was never referenced and was not
1479 ;;; declared IGNORE, then complain.
1480 (defun note-unreferenced-vars (fun)
1481   (declare (type clambda fun))
1482   (dolist (var (lambda-vars fun))
1483     (unless (or (leaf-ever-used var)
1484                 (lambda-var-ignorep var))
1485       (let ((*compiler-error-context* (lambda-bind fun)))
1486         (unless (policy *compiler-error-context* (= inhibit-warnings 3))
1487           ;; ANSI section "3.2.5 Exceptional Situations in the Compiler"
1488           ;; requires this to be no more than a STYLE-WARNING.
1489           #-sb-xc-host
1490           (compiler-style-warn "The variable ~S is defined but never used."
1491                                (leaf-debug-name var))
1492           ;; There's no reason to accept this kind of equivocation
1493           ;; when compiling our own code, though.
1494           #+sb-xc-host
1495           (warn "The variable ~S is defined but never used."
1496                 (leaf-debug-name var)))
1497         (setf (leaf-ever-used var) t)))) ; to avoid repeated warnings? -- WHN
1498   (values))
1499
1500 (defvar *deletion-ignored-objects* '(t nil))
1501
1502 ;;; Return true if we can find OBJ in FORM, NIL otherwise. We bound
1503 ;;; our recursion so that we don't get lost in circular structures. We
1504 ;;; ignore the car of forms if they are a symbol (to prevent confusing
1505 ;;; function referencess with variables), and we also ignore anything
1506 ;;; inside ' or #'.
1507 (defun present-in-form (obj form depth)
1508   (declare (type (integer 0 20) depth))
1509   (cond ((= depth 20) nil)
1510         ((eq obj form) t)
1511         ((atom form) nil)
1512         (t
1513          (let ((first (car form))
1514                (depth (1+ depth)))
1515            (if (member first '(quote function))
1516                nil
1517                (or (and (not (symbolp first))
1518                         (present-in-form obj first depth))
1519                    (do ((l (cdr form) (cdr l))
1520                         (n 0 (1+ n)))
1521                        ((or (atom l) (> n 100))
1522                         nil)
1523                      (declare (fixnum n))
1524                      (when (present-in-form obj (car l) depth)
1525                        (return t)))))))))
1526
1527 ;;; This function is called on a block immediately before we delete
1528 ;;; it. We check to see whether any of the code about to die appeared
1529 ;;; in the original source, and emit a note if so.
1530 ;;;
1531 ;;; If the block was in a lambda is now deleted, then we ignore the
1532 ;;; whole block, since this case is picked off in DELETE-LAMBDA. We
1533 ;;; also ignore the deletion of CRETURN nodes, since it is somewhat
1534 ;;; reasonable for a function to not return, and there is a different
1535 ;;; note for that case anyway.
1536 ;;;
1537 ;;; If the actual source is an atom, then we use a bunch of heuristics
1538 ;;; to guess whether this reference really appeared in the original
1539 ;;; source:
1540 ;;; -- If a symbol, it must be interned and not a keyword.
1541 ;;; -- It must not be an easily introduced constant (T or NIL, a fixnum
1542 ;;;    or a character.)
1543 ;;; -- The atom must be "present" in the original source form, and
1544 ;;;    present in all intervening actual source forms.
1545 (defun note-block-deletion (block)
1546   (let ((home (block-home-lambda block)))
1547     (unless (eq (functional-kind home) :deleted)
1548       (do-nodes (node nil block)
1549         (let* ((path (node-source-path node))
1550                (first (first path)))
1551           (when (or (eq first 'original-source-start)
1552                     (and (atom first)
1553                          (or (not (symbolp first))
1554                              (let ((pkg (symbol-package first)))
1555                                (and pkg
1556                                     (not (eq pkg (symbol-package :end))))))
1557                          (not (member first *deletion-ignored-objects*))
1558                          (not (typep first '(or fixnum character)))
1559                          (every (lambda (x)
1560                                   (present-in-form first x 0))
1561                                 (source-path-forms path))
1562                          (present-in-form first (find-original-source path)
1563                                           0)))
1564             (unless (return-p node)
1565               (let ((*compiler-error-context* node))
1566                 (compiler-notify 'code-deletion-note
1567                                  :format-control "deleting unreachable code"
1568                                  :format-arguments nil)))
1569             (return))))))
1570   (values))
1571
1572 ;;; Delete a node from a block, deleting the block if there are no
1573 ;;; nodes left. We remove the node from the uses of its LVAR.
1574 ;;;
1575 ;;; If the node is the last node, there must be exactly one successor.
1576 ;;; We link all of our precedessors to the successor and unlink the
1577 ;;; block. In this case, we return T, otherwise NIL. If no nodes are
1578 ;;; left, and the block is a successor of itself, then we replace the
1579 ;;; only node with a degenerate exit node. This provides a way to
1580 ;;; represent the bodyless infinite loop, given the prohibition on
1581 ;;; empty blocks in IR1.
1582 (defun unlink-node (node)
1583   (declare (type node node))
1584   (when (valued-node-p node)
1585     (delete-lvar-use node))
1586
1587   (let* ((ctran (node-next node))
1588          (next (and ctran (ctran-next ctran)))
1589          (prev (node-prev node))
1590          (block (ctran-block prev))
1591          (prev-kind (ctran-kind prev))
1592          (last (block-last block)))
1593
1594     (setf (block-type-asserted block) t)
1595     (setf (block-test-modified block) t)
1596
1597     (cond ((or (eq prev-kind :inside-block)
1598                (and (eq prev-kind :block-start)
1599                     (not (eq node last))))
1600            (cond ((eq node last)
1601                   (setf (block-last block) (ctran-use prev))
1602                   (setf (node-next (ctran-use prev)) nil))
1603                  (t
1604                   (setf (ctran-next prev) next)
1605                   (setf (node-prev next) prev)
1606                   (when (if-p next) ; AOP wanted
1607                     (reoptimize-lvar (if-test next)))))
1608            (setf (node-prev node) nil)
1609            nil)
1610           (t
1611            (aver (eq prev-kind :block-start))
1612            (aver (eq node last))
1613            (let* ((succ (block-succ block))
1614                   (next (first succ)))
1615              (aver (singleton-p succ))
1616              (cond
1617               ((eq block (first succ))
1618                (with-ir1-environment-from-node node
1619                  (let ((exit (make-exit)))
1620                    (setf (ctran-next prev) nil)
1621                    (link-node-to-previous-ctran exit prev)
1622                    (setf (block-last block) exit)))
1623                (setf (node-prev node) nil)
1624                nil)
1625               (t
1626                (aver (eq (block-start-cleanup block)
1627                          (block-end-cleanup block)))
1628                (unlink-blocks block next)
1629                (dolist (pred (block-pred block))
1630                  (change-block-successor pred block next))
1631                (when (block-delete-p block)
1632                  (let ((component (block-component block)))
1633                    (setf (component-delete-blocks component)
1634                          (delq block (component-delete-blocks component)))))
1635                (remove-from-dfo block)
1636                (setf (block-delete-p block) t)
1637                (setf (node-prev node) nil)
1638                t)))))))
1639
1640 ;;; Return true if CTRAN has been deleted, false if it is still a valid
1641 ;;; part of IR1.
1642 (defun ctran-deleted-p (ctran)
1643   (declare (type ctran ctran))
1644   (let ((block (ctran-block ctran)))
1645     (or (not (block-component block))
1646         (block-delete-p block))))
1647
1648 ;;; Return true if NODE has been deleted, false if it is still a valid
1649 ;;; part of IR1.
1650 (defun node-deleted (node)
1651   (declare (type node node))
1652   (let ((prev (node-prev node)))
1653     (or (not prev)
1654         (ctran-deleted-p prev))))
1655
1656 ;;; Delete all the blocks and functions in COMPONENT. We scan first
1657 ;;; marking the blocks as DELETE-P to prevent weird stuff from being
1658 ;;; triggered by deletion.
1659 (defun delete-component (component)
1660   (declare (type component component))
1661   (aver (null (component-new-functionals component)))
1662   (setf (component-kind component) :deleted)
1663   (do-blocks (block component)
1664     (delete-block-lazily block))
1665   (dolist (fun (component-lambdas component))
1666     (unless (eq (functional-kind fun) :deleted)
1667       (setf (functional-kind fun) nil)
1668       (setf (functional-entry-fun fun) nil)
1669       (setf (leaf-refs fun) nil)
1670       (delete-functional fun)))
1671   (clean-component component)
1672   (values))
1673
1674 ;;; Remove all pending blocks to be deleted. Return the nearest live
1675 ;;; block after or equal to BLOCK.
1676 (defun clean-component (component &optional block)
1677   (loop while (component-delete-blocks component)
1678         ;; actual deletion of a block may queue new blocks
1679         do (let ((current (pop (component-delete-blocks component))))
1680              (when (eq block current)
1681                (setq block (block-next block)))
1682              (delete-block current)))
1683   block)
1684
1685 ;;; Convert code of the form
1686 ;;;   (FOO ... (FUN ...) ...)
1687 ;;; to
1688 ;;;   (FOO ...    ...    ...).
1689 ;;; In other words, replace the function combination FUN by its
1690 ;;; arguments. If there are any problems with doing this, use GIVE-UP
1691 ;;; to blow out of whatever transform called this. Note, as the number
1692 ;;; of arguments changes, the transform must be prepared to return a
1693 ;;; lambda with a new lambda-list with the correct number of
1694 ;;; arguments.
1695 (defun splice-fun-args (lvar fun num-args)
1696   #!+sb-doc
1697   "If LVAR is a call to FUN with NUM-ARGS args, change those arguments to feed
1698 directly to the LVAR-DEST of LVAR, which must be a combination. If FUN
1699 is :ANY, the function name is not checked."
1700   (declare (type lvar lvar)
1701            (type symbol fun)
1702            (type index num-args))
1703   (let ((outside (lvar-dest lvar))
1704         (inside (lvar-uses lvar)))
1705     (aver (combination-p outside))
1706     (unless (combination-p inside)
1707       (give-up-ir1-transform))
1708     (let ((inside-fun (combination-fun inside)))
1709       (unless (or (eq fun :any)
1710                   (eq (lvar-fun-name inside-fun) fun))
1711         (give-up-ir1-transform))
1712       (let ((inside-args (combination-args inside)))
1713         (unless (= (length inside-args) num-args)
1714           (give-up-ir1-transform))
1715         (let* ((outside-args (combination-args outside))
1716                (arg-position (position lvar outside-args))
1717                (before-args (subseq outside-args 0 arg-position))
1718                (after-args (subseq outside-args (1+ arg-position))))
1719           (dolist (arg inside-args)
1720             (setf (lvar-dest arg) outside)
1721             (flush-lvar-externally-checkable-type arg))
1722           (setf (combination-args inside) nil)
1723           (setf (combination-args outside)
1724                 (append before-args inside-args after-args))
1725           (change-ref-leaf (lvar-uses inside-fun)
1726                            (find-free-fun 'list "???"))
1727           (setf (combination-fun-info inside) (info :function :info 'list)
1728                 (combination-kind inside) :known)
1729           (setf (node-derived-type inside) *wild-type*)
1730           (flush-dest lvar)
1731           inside-args)))))
1732
1733 ;;; Eliminate keyword arguments from the call (leaving the
1734 ;;; parameters in place.
1735 ;;;
1736 ;;;    (FOO ... :BAR X :QUUX Y)
1737 ;;; becomes
1738 ;;;    (FOO ... X Y)
1739 ;;;
1740 ;;; SPECS is a list of (:KEYWORD PARAMETER) specifications.
1741 ;;; Returns the list of specified parameters names in the
1742 ;;; order they appeared in the call. N-POSITIONAL is the
1743 ;;; number of positional arguments in th call.
1744 (defun eliminate-keyword-args (call n-positional specs)
1745   (let* ((specs (copy-tree specs))
1746          (all (combination-args call))
1747          (new-args (reverse (subseq all 0 n-positional)))
1748          (key-args (subseq all n-positional))
1749          (parameters nil)
1750          (flushed-keys nil))
1751     (loop while key-args
1752           do (let* ((key (pop key-args))
1753                     (val (pop key-args))
1754                     (keyword (if (constant-lvar-p key)
1755                                  (lvar-value key)
1756                                  (give-up-ir1-transform)))
1757                     (spec (or (assoc keyword specs :test #'eq)
1758                               (give-up-ir1-transform))))
1759                (push val new-args)
1760                (push key flushed-keys)
1761                (push (second spec) parameters)
1762                ;; In case of duplicate keys.
1763                (setf (second spec) (gensym))))
1764     (dolist (key flushed-keys)
1765       (flush-dest key))
1766     (setf (combination-args call) (reverse new-args))
1767     (reverse parameters)))
1768
1769 (defun extract-fun-args (lvar fun num-args)
1770   (declare (type lvar lvar)
1771            (type (or symbol list) fun)
1772            (type index num-args))
1773   (let ((fun (if (listp fun) fun (list fun))))
1774     (let ((inside (lvar-uses lvar)))
1775       (unless (combination-p inside)
1776         (give-up-ir1-transform))
1777       (let ((inside-fun (combination-fun inside)))
1778         (unless (member (lvar-fun-name inside-fun) fun)
1779           (give-up-ir1-transform))
1780         (let ((inside-args (combination-args inside)))
1781           (unless (= (length inside-args) num-args)
1782             (give-up-ir1-transform))
1783           (values (lvar-fun-name inside-fun) inside-args))))))
1784
1785 (defun flush-combination (combination)
1786   (declare (type combination combination))
1787   (flush-dest (combination-fun combination))
1788   (dolist (arg (combination-args combination))
1789     (flush-dest arg))
1790   (unlink-node combination)
1791   (values))
1792
1793 \f
1794 ;;;; leaf hackery
1795
1796 ;;; Change the LEAF that a REF refers to.
1797 (defun change-ref-leaf (ref leaf)
1798   (declare (type ref ref) (type leaf leaf))
1799   (unless (eq (ref-leaf ref) leaf)
1800     (push ref (leaf-refs leaf))
1801     (delete-ref ref)
1802     (setf (ref-leaf ref) leaf)
1803     (setf (leaf-ever-used leaf) t)
1804     (let* ((ltype (leaf-type leaf))
1805            (vltype (make-single-value-type ltype)))
1806       (if (let* ((lvar (node-lvar ref))
1807                  (dest (and lvar (lvar-dest lvar))))
1808             (and (basic-combination-p dest)
1809                  (eq lvar (basic-combination-fun dest))
1810                  (csubtypep ltype (specifier-type 'function))))
1811           (setf (node-derived-type ref) vltype)
1812           (derive-node-type ref vltype)))
1813     (reoptimize-lvar (node-lvar ref)))
1814   (values))
1815
1816 ;;; Change all REFS for OLD-LEAF to NEW-LEAF.
1817 (defun substitute-leaf (new-leaf old-leaf)
1818   (declare (type leaf new-leaf old-leaf))
1819   (dolist (ref (leaf-refs old-leaf))
1820     (change-ref-leaf ref new-leaf))
1821   (values))
1822
1823 ;;; like SUBSITUTE-LEAF, only there is a predicate on the REF to tell
1824 ;;; whether to substitute
1825 (defun substitute-leaf-if (test new-leaf old-leaf)
1826   (declare (type leaf new-leaf old-leaf) (type function test))
1827   (dolist (ref (leaf-refs old-leaf))
1828     (when (funcall test ref)
1829       (change-ref-leaf ref new-leaf)))
1830   (values))
1831
1832 ;;; Return a LEAF which represents the specified constant object. If
1833 ;;; the object is not in *CONSTANTS*, then we create a new constant
1834 ;;; LEAF and enter it. If we are producing a fasl file, make sure that
1835 ;;; MAKE-LOAD-FORM gets used on any parts of the constant that it
1836 ;;; needs to be.
1837 ;;;
1838 ;;; We are allowed to coalesce things like EQUAL strings and bit-vectors
1839 ;;; when file-compiling, but not when using COMPILE.
1840 (defun find-constant (object &optional (name nil namep))
1841   (let ((faslp (producing-fasl-file)))
1842     (labels ((make-it ()
1843                (when faslp
1844                  (if namep
1845                      (maybe-emit-make-load-forms object name)
1846                      (maybe-emit-make-load-forms object)))
1847                (make-constant object))
1848              (core-coalesce-p (x)
1849                ;; True for things which retain their identity under EQUAL,
1850                ;; so we can safely share the same CONSTANT leaf between
1851                ;; multiple references.
1852                (or (typep x '(or symbol number character))
1853                    ;; Amusingly enough, we see CLAMBDAs --among other things--
1854                    ;; here, from compiling things like %ALLOCATE-CLOSUREs forms.
1855                    ;; No point in stuffing them in the hash-table.
1856                    (and (typep x 'instance)
1857                         (not (or (leaf-p x) (node-p x))))))
1858              (file-coalesce-p (x)
1859                ;; CLHS 3.2.4.2.2: We are also allowed to coalesce various
1860                ;; other things when file-compiling.
1861                (or (core-coalesce-p x)
1862                    (if (consp x)
1863                        (if (eq +code-coverage-unmarked+ (cdr x))
1864                            ;; These are already coalesced, and the CAR should
1865                            ;; always be OK, so no need to check.
1866                            t
1867                            (unless (maybe-cyclic-p x) ; safe for EQUAL?
1868                              (do ((y x (cdr y)))
1869                                  ((atom y) (file-coalesce-p y))
1870                                (unless (file-coalesce-p (car y))
1871                                  (return nil)))))
1872                        ;; We *could* coalesce base-strings as well,
1873                        ;; but we'd need a separate hash-table for
1874                        ;; that, since we are not allowed to coalesce
1875                        ;; base-strings with non-base-strings.
1876                        (typep x
1877                               '(or bit-vector
1878                                 ;; in the cross-compiler, we coalesce
1879                                 ;; all strings with the same contents,
1880                                 ;; because we will end up dumping them
1881                                 ;; as base-strings anyway.  In the
1882                                 ;; real compiler, we're not allowed to
1883                                 ;; coalesce regardless of string
1884                                 ;; specialized element type, so we
1885                                 ;; KLUDGE by coalescing only character
1886                                 ;; strings (the common case) and
1887                                 ;; punting on the other types.
1888                                 #+sb-xc-host
1889                                 string
1890                                 #-sb-xc-host
1891                                 (vector character))))))
1892              (coalescep (x)
1893                (if faslp (file-coalesce-p x) (core-coalesce-p x))))
1894       (if (and (boundp '*constants*) (coalescep object))
1895           (or (gethash object *constants*)
1896               (setf (gethash object *constants*)
1897                     (make-it)))
1898           (make-it)))))
1899 \f
1900 ;;; Return true if VAR would have to be closed over if environment
1901 ;;; analysis ran now (i.e. if there are any uses that have a different
1902 ;;; home lambda than VAR's home.)
1903 (defun closure-var-p (var)
1904   (declare (type lambda-var var))
1905   (let ((home (lambda-var-home var)))
1906     (cond ((eq (functional-kind home) :deleted)
1907            nil)
1908           (t (let ((home (lambda-home home)))
1909                (flet ((frob (l)
1910                         (find home l
1911                               :key #'node-home-lambda
1912                               :test #'neq)))
1913                  (or (frob (leaf-refs var))
1914                      (frob (basic-var-sets var)))))))))
1915
1916 ;;; If there is a non-local exit noted in ENTRY's environment that
1917 ;;; exits to CONT in that entry, then return it, otherwise return NIL.
1918 (defun find-nlx-info (exit)
1919   (declare (type exit exit))
1920   (let* ((entry (exit-entry exit))
1921          (cleanup (entry-cleanup entry))
1922         (block (first (block-succ (node-block exit)))))
1923     (dolist (nlx (physenv-nlx-info (node-physenv entry)) nil)
1924       (when (and (eq (nlx-info-block nlx) block)
1925                  (eq (nlx-info-cleanup nlx) cleanup))
1926         (return nlx)))))
1927
1928 (defun nlx-info-lvar (nlx)
1929   (declare (type nlx-info nlx))
1930   (node-lvar (block-last (nlx-info-target nlx))))
1931 \f
1932 ;;;; functional hackery
1933
1934 (declaim (ftype (sfunction (functional) clambda) main-entry))
1935 (defun main-entry (functional)
1936   (etypecase functional
1937     (clambda functional)
1938     (optional-dispatch
1939      (optional-dispatch-main-entry functional))))
1940
1941 ;;; RETURN true if FUNCTIONAL is a thing that can be treated like
1942 ;;; MV-BIND when it appears in an MV-CALL. All fixed arguments must be
1943 ;;; optional with null default and no SUPPLIED-P. There must be a
1944 ;;; &REST arg with no references.
1945 (declaim (ftype (sfunction (functional) boolean) looks-like-an-mv-bind))
1946 (defun looks-like-an-mv-bind (functional)
1947   (and (optional-dispatch-p functional)
1948        (do ((arg (optional-dispatch-arglist functional) (cdr arg)))
1949            ((null arg) nil)
1950          (let ((info (lambda-var-arg-info (car arg))))
1951            (unless info (return nil))
1952            (case (arg-info-kind info)
1953              (:optional
1954               (when (or (arg-info-supplied-p info) (arg-info-default info))
1955                 (return nil)))
1956              (:rest
1957               (return (and (null (cdr arg)) (null (leaf-refs (car arg))))))
1958              (t
1959               (return nil)))))))
1960
1961 ;;; Return true if function is an external entry point. This is true
1962 ;;; of normal XEPs (:EXTERNAL kind) and also of top level lambdas
1963 ;;; (:TOPLEVEL kind.)
1964 (defun xep-p (fun)
1965   (declare (type functional fun))
1966   (not (null (member (functional-kind fun) '(:external :toplevel)))))
1967
1968 ;;; If LVAR's only use is a non-notinline global function reference,
1969 ;;; then return the referenced symbol, otherwise NIL. If NOTINLINE-OK
1970 ;;; is true, then we don't care if the leaf is NOTINLINE.
1971 (defun lvar-fun-name (lvar &optional notinline-ok)
1972   (declare (type lvar lvar))
1973   (let ((use (lvar-uses lvar)))
1974     (if (ref-p use)
1975         (let ((leaf (ref-leaf use)))
1976           (if (and (global-var-p leaf)
1977                    (eq (global-var-kind leaf) :global-function)
1978                    (or (not (defined-fun-p leaf))
1979                        (not (eq (defined-fun-inlinep leaf) :notinline))
1980                        notinline-ok))
1981               (leaf-source-name leaf)
1982               nil))
1983         nil)))
1984
1985 (defun lvar-fun-debug-name (lvar)
1986   (declare (type lvar lvar))
1987   (let ((uses (lvar-uses lvar)))
1988     (flet ((name1 (use)
1989              (leaf-debug-name (ref-leaf use))))
1990       (if (ref-p uses)
1991         (name1 uses)
1992         (mapcar #'name1 uses)))))
1993
1994 ;;; Return the source name of a combination -- or signals an error
1995 ;;; if the function leaf is anonymous.
1996 (defun combination-fun-source-name (combination &optional (errorp t))
1997   (let ((leaf (ref-leaf (lvar-uses (combination-fun combination)))))
1998     (if (or errorp (leaf-has-source-name-p leaf))
1999         (values (leaf-source-name leaf) t)
2000         (values nil nil))))
2001
2002 ;;; Return the COMBINATION node that is the call to the LET FUN.
2003 (defun let-combination (fun)
2004   (declare (type clambda fun))
2005   (aver (functional-letlike-p fun))
2006   (lvar-dest (node-lvar (first (leaf-refs fun)))))
2007
2008 ;;; Return the initial value lvar for a LET variable, or NIL if there
2009 ;;; is none.
2010 (defun let-var-initial-value (var)
2011   (declare (type lambda-var var))
2012   (let ((fun (lambda-var-home var)))
2013     (elt (combination-args (let-combination fun))
2014          (position-or-lose var (lambda-vars fun)))))
2015
2016 ;;; Return the LAMBDA that is called by the local CALL.
2017 (defun combination-lambda (call)
2018   (declare (type basic-combination call))
2019   (aver (eq (basic-combination-kind call) :local))
2020   (ref-leaf (lvar-uses (basic-combination-fun call))))
2021
2022 (defvar *inline-expansion-limit* 200
2023   #!+sb-doc
2024   "an upper limit on the number of inline function calls that will be expanded
2025    in any given code object (single function or block compilation)")
2026
2027 ;;; Check whether NODE's component has exceeded its inline expansion
2028 ;;; limit, and warn if so, returning NIL.
2029 (defun inline-expansion-ok (node)
2030   (let ((expanded (incf (component-inline-expansions
2031                          (block-component
2032                           (node-block node))))))
2033     (cond ((> expanded *inline-expansion-limit*) nil)
2034           ((= expanded *inline-expansion-limit*)
2035            ;; FIXME: If the objective is to stop the recursive
2036            ;; expansion of inline functions, wouldn't it be more
2037            ;; correct to look back through surrounding expansions
2038            ;; (which are, I think, stored in the *CURRENT-PATH*, and
2039            ;; possibly stored elsewhere too) and suppress expansion
2040            ;; and print this warning when the function being proposed
2041            ;; for inline expansion is found there? (I don't like the
2042            ;; arbitrary numerical limit in principle, and I think
2043            ;; it'll be a nuisance in practice if we ever want the
2044            ;; compiler to be able to use WITH-COMPILATION-UNIT on
2045            ;; arbitrarily huge blocks of code. -- WHN)
2046            (let ((*compiler-error-context* node))
2047              (compiler-notify "*INLINE-EXPANSION-LIMIT* (~W) was exceeded, ~
2048                                probably trying to~%  ~
2049                                inline a recursive function."
2050                               *inline-expansion-limit*))
2051            nil)
2052           (t t))))
2053
2054 ;;; Make sure that FUNCTIONAL is not let-converted or deleted.
2055 (defun assure-functional-live-p (functional)
2056   (declare (type functional functional))
2057   (when (and (or
2058               ;; looks LET-converted
2059               (functional-somewhat-letlike-p functional)
2060               ;; It's possible for a LET-converted function to end up
2061               ;; deleted later. In that case, for the purposes of this
2062               ;; analysis, it is LET-converted: LET-converted functionals
2063               ;; are too badly trashed to expand them inline, and deleted
2064               ;; LET-converted functionals are even worse.
2065               (memq (functional-kind functional) '(:deleted :zombie))))
2066     (throw 'locall-already-let-converted functional)))
2067
2068 (defun assure-leaf-live-p (leaf)
2069   (typecase leaf
2070     (lambda-var
2071      (when (lambda-var-deleted leaf)
2072        (throw 'locall-already-let-converted leaf)))
2073     (functional
2074      (assure-functional-live-p leaf))))
2075
2076
2077 (defun call-full-like-p (call)
2078   (declare (type combination call))
2079   (let ((kind (basic-combination-kind call)))
2080     (or (eq kind :full)
2081         (and (eq kind :known)
2082              (let ((info (basic-combination-fun-info call)))
2083                (and
2084                 (not (fun-info-ir2-convert info))
2085                 (dolist (template (fun-info-templates info) t)
2086                   (when (eq (template-ltn-policy template) :fast-safe)
2087                     (multiple-value-bind (val win)
2088                        (valid-fun-use call (template-type template))
2089                       (when (or val (not win)) (return nil)))))))))))
2090 \f
2091 ;;;; careful call
2092
2093 ;;; Apply a function to some arguments, returning a list of the values
2094 ;;; resulting of the evaluation. If an error is signalled during the
2095 ;;; application, then we produce a warning message using WARN-FUN and
2096 ;;; return NIL as our second value to indicate this. NODE is used as
2097 ;;; the error context for any error message, and CONTEXT is a string
2098 ;;; that is spliced into the warning.
2099 (declaim (ftype (sfunction ((or symbol function) list node function string)
2100                           (values list boolean))
2101                 careful-call))
2102 (defun careful-call (function args node warn-fun context)
2103   (values
2104    (multiple-value-list
2105     (handler-case (apply function args)
2106       (error (condition)
2107         (let ((*compiler-error-context* node))
2108           (funcall warn-fun "Lisp error during ~A:~%~A" context condition)
2109           (return-from careful-call (values nil nil))))))
2110    t))
2111
2112 ;;; Variations of SPECIFIER-TYPE for parsing possibly wrong
2113 ;;; specifiers.
2114 (macrolet
2115     ((deffrob (basic careful compiler transform)
2116        `(progn
2117           (defun ,careful (specifier)
2118             (handler-case (,basic specifier)
2119               (sb!kernel::arg-count-error (condition)
2120                 (values nil (list (format nil "~A" condition))))
2121               (simple-error (condition)
2122                 (values nil (list* (simple-condition-format-control condition)
2123                                    (simple-condition-format-arguments condition))))))
2124           (defun ,compiler (specifier)
2125             (multiple-value-bind (type error-args) (,careful specifier)
2126               (or type
2127                   (apply #'compiler-error error-args))))
2128           (defun ,transform (specifier)
2129             (multiple-value-bind (type error-args) (,careful specifier)
2130               (or type
2131                   (apply #'give-up-ir1-transform
2132                          error-args)))))))
2133   (deffrob specifier-type careful-specifier-type compiler-specifier-type ir1-transform-specifier-type)
2134   (deffrob values-specifier-type careful-values-specifier-type compiler-values-specifier-type ir1-transform-values-specifier-type))
2135
2136 \f
2137 ;;;; utilities used at run-time for parsing &KEY args in IR1
2138
2139 ;;; This function is used by the result of PARSE-DEFTRANSFORM to find
2140 ;;; the lvar for the value of the &KEY argument KEY in the list of
2141 ;;; lvars ARGS. It returns the lvar if the keyword is present, or NIL
2142 ;;; otherwise. The legality and constantness of the keywords should
2143 ;;; already have been checked.
2144 (declaim (ftype (sfunction (list keyword) (or lvar null))
2145                 find-keyword-lvar))
2146 (defun find-keyword-lvar (args key)
2147   (do ((arg args (cddr arg)))
2148       ((null arg) nil)
2149     (when (eq (lvar-value (first arg)) key)
2150       (return (second arg)))))
2151
2152 ;;; This function is used by the result of PARSE-DEFTRANSFORM to
2153 ;;; verify that alternating lvars in ARGS are constant and that there
2154 ;;; is an even number of args.
2155 (declaim (ftype (sfunction (list) boolean) check-key-args-constant))
2156 (defun check-key-args-constant (args)
2157   (do ((arg args (cddr arg)))
2158       ((null arg) t)
2159     (unless (and (rest arg)
2160                  (constant-lvar-p (first arg)))
2161       (return nil))))
2162
2163 ;;; This function is used by the result of PARSE-DEFTRANSFORM to
2164 ;;; verify that the list of lvars ARGS is a well-formed &KEY arglist
2165 ;;; and that only keywords present in the list KEYS are supplied.
2166 (declaim (ftype (sfunction (list list) boolean) check-transform-keys))
2167 (defun check-transform-keys (args keys)
2168   (and (check-key-args-constant args)
2169        (do ((arg args (cddr arg)))
2170            ((null arg) t)
2171          (unless (member (lvar-value (first arg)) keys)
2172            (return nil)))))
2173 \f
2174 ;;;; miscellaneous
2175
2176 ;;; Called by the expansion of the EVENT macro.
2177 (declaim (ftype (sfunction (event-info (or node null)) *) %event))
2178 (defun %event (info node)
2179   (incf (event-info-count info))
2180   (when (and (>= (event-info-level info) *event-note-threshold*)
2181              (policy (or node *lexenv*)
2182                      (= inhibit-warnings 0)))
2183     (let ((*compiler-error-context* node))
2184       (compiler-notify (event-info-description info))))
2185
2186   (let ((action (event-info-action info)))
2187     (when action (funcall action node))))
2188
2189 ;;;
2190 (defun make-cast (value type policy)
2191   (declare (type lvar value)
2192            (type ctype type)
2193            (type policy policy))
2194   (%make-cast :asserted-type type
2195               :type-to-check (maybe-weaken-check type policy)
2196               :value value
2197               :derived-type (coerce-to-values type)))
2198
2199 (defun cast-type-check (cast)
2200   (declare (type cast cast))
2201   (when (cast-reoptimize cast)
2202     (ir1-optimize-cast cast t))
2203   (cast-%type-check cast))
2204
2205 (defun note-single-valuified-lvar (lvar)
2206   (declare (type (or lvar null) lvar))
2207   (when lvar
2208     (let ((use (lvar-uses lvar)))
2209       (cond ((ref-p use)
2210              (let ((leaf (ref-leaf use)))
2211                (when (and (lambda-var-p leaf)
2212                           (null (rest (leaf-refs leaf))))
2213                  (reoptimize-lambda-var leaf))))
2214             ((or (listp use) (combination-p use))
2215              (do-uses (node lvar)
2216                (setf (node-reoptimize node) t)
2217                (setf (block-reoptimize (node-block node)) t)
2218                (reoptimize-component (node-component node) :maybe)))))))
2219
2220 ;;; Return true if LVAR's only use is a reference to a global function
2221 ;;; designator with one of the specified NAMES, that hasn't been
2222 ;;; declared NOTINLINE.
2223 (defun lvar-fun-is (lvar names)
2224   (declare (type lvar lvar) (list names))
2225   (let ((use (lvar-uses lvar)))
2226     (and (ref-p use)
2227          (let* ((*lexenv* (node-lexenv use))
2228                 (leaf (ref-leaf use))
2229                 (name
2230                  (cond ((global-var-p leaf)
2231                         ;; Case 1: #'NAME
2232                         (and (eq (global-var-kind leaf) :global-function)
2233                              (car (member (leaf-source-name leaf) names
2234                                           :test #'equal))))
2235                        ((constant-p leaf)
2236                         (let ((value (constant-value leaf)))
2237                           (car (if (functionp value)
2238                                    ;; Case 2: #.#'NAME
2239                                    (member value names
2240                                            :key (lambda (name)
2241                                                   (and (fboundp name)
2242                                                        (fdefinition name)))
2243                                            :test #'eq)
2244                                    ;; Case 3: 'NAME
2245                                    (member value names
2246                                            :test #'equal))))))))
2247            (and name
2248                 (not (fun-lexically-notinline-p name)))))))
2249
2250 ;;; Return true if LVAR's only use is a call to one of the named functions
2251 ;;; (or any function if none are specified) with the specified number of
2252 ;;; of arguments (or any number if number is not specified)
2253 (defun lvar-matches (lvar &key fun-names arg-count)
2254   (let ((use (lvar-uses lvar)))
2255     (and (combination-p use)
2256          (or (not fun-names)
2257              (multiple-value-bind (name ok)
2258                  (combination-fun-source-name use nil)
2259                (and ok (member name fun-names :test #'eq))))
2260          (or (not arg-count)
2261              (= arg-count (length (combination-args use)))))))