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