0.8.0.3:
[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-continuation))
43              (block (continuation-starts-block start))
44              (cont (make-continuation))
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 cont form)
51         (setf (block-last block) (continuation-use cont))
52         block))))
53 \f
54 ;;;; continuation use hacking
55
56 ;;; Return a list of all the nodes which use Cont.
57 (declaim (ftype (function (continuation) list) find-uses))
58 (defun find-uses (cont)
59   (ecase (continuation-kind cont)
60     ((:block-start :deleted-block-start)
61      (block-start-uses (continuation-block cont)))
62     (:inside-block (list (continuation-use cont)))
63     (:unused nil)
64     (:deleted nil)))
65
66 (defun principal-continuation-use (cont)
67   (let ((use (continuation-use cont)))
68     (if (cast-p use)
69         (principal-continuation-use (cast-value use))
70         use)))
71
72 ;;; Update continuation use information so that NODE is no longer a
73 ;;; use of its CONT. If the old continuation doesn't start its block,
74 ;;; then we don't update the BLOCK-START-USES, since it will be
75 ;;; deleted when we are done.
76 ;;;
77 ;;; Note: if you call this function, you may have to do a
78 ;;; REOPTIMIZE-CONTINUATION to inform IR1 optimization that something
79 ;;; has changed.
80 (declaim (ftype (function (node) (values)) delete-continuation-use))
81 (defun delete-continuation-use (node)
82   (let* ((cont (node-cont node))
83          (block (continuation-block cont)))
84     (ecase (continuation-kind cont)
85       (:deleted)
86       ((:block-start :deleted-block-start)
87        (let ((uses (delete node (block-start-uses block))))
88          (setf (block-start-uses block) uses)
89          (setf (continuation-use cont)
90                (if (cdr uses) nil (car uses)))))
91       (:inside-block
92        (setf (continuation-kind cont) :unused)
93        (setf (continuation-block cont) nil)
94        (setf (continuation-use cont) nil)
95        (setf (continuation-next cont) nil)))
96     (setf (node-cont node) nil))
97   (values))
98
99 ;;; Update continuation use information so that NODE uses CONT. If
100 ;;; CONT is :UNUSED, then we set its block to NODE's NODE-BLOCK (which
101 ;;; must be set.)
102 ;;;
103 ;;; Note: if you call this function, you may have to do a
104 ;;; REOPTIMIZE-CONTINUATION to inform IR1 optimization that something
105 ;;; has changed.
106 (declaim (ftype (function (node continuation) (values)) add-continuation-use))
107 (defun add-continuation-use (node cont)
108   (aver (not (node-cont node)))
109   (let ((block (continuation-block cont)))
110     (ecase (continuation-kind cont)
111       (:deleted)
112       (:unused
113        (aver (not block))
114        (let ((block (node-block node)))
115          (aver block)
116          (setf (continuation-block cont) block))
117        (setf (continuation-kind cont) :inside-block)
118        (setf (continuation-use cont) node))
119       ((:block-start :deleted-block-start)
120        (let ((uses (cons node (block-start-uses block))))
121          (setf (block-start-uses block) uses)
122          (setf (continuation-use cont)
123                (if (cdr uses) nil (car uses)))
124          (let ((block (node-block node)))
125            (unless (block-last block)
126              (setf (block-last block) node)))))))
127   (setf (node-cont node) cont)
128   (values))
129
130 ;;; Return true if CONT is the NODE-CONT for NODE and CONT is
131 ;;; transferred to immediately after the evaluation of NODE.
132 (defun immediately-used-p (cont node)
133   (declare (type continuation cont) (type node node))
134   (and (eq (node-cont node) cont)
135        (not (eq (continuation-kind cont) :deleted))
136        (eq (continuation-dest cont)
137            (continuation-next cont))
138        (let ((cblock (continuation-block cont))
139              (nblock (node-block node)))
140          (or (eq cblock nblock)
141              (let ((succ (block-succ nblock)))
142                (and (= (length succ) 1)
143                     (eq (first succ) cblock)))))))
144 \f
145 ;;;; continuation substitution
146
147 ;;; In OLD's DEST, replace OLD with NEW. NEW's DEST must initially be
148 ;;; NIL. When we are done, we call FLUSH-DEST on OLD to clear its DEST
149 ;;; and to note potential optimization opportunities.
150 (defun substitute-continuation (new old)
151   (declare (type continuation old new))
152   (aver (not (continuation-dest new)))
153   (let ((dest (continuation-dest old)))
154     (etypecase dest
155       ((or ref bind))
156       (cif (setf (if-test dest) new))
157       (cset (setf (set-value dest) new))
158       (creturn (setf (return-result dest) new))
159       (exit (setf (exit-value dest) new))
160       (basic-combination
161        (if (eq old (basic-combination-fun dest))
162            (setf (basic-combination-fun dest) new)
163            (setf (basic-combination-args dest)
164                  (nsubst new old (basic-combination-args dest)))))
165       (cast (setf (cast-value dest) new))
166       (null))
167
168     (when dest (flush-dest old))
169     (setf (continuation-dest new) dest)
170     (flush-continuation-externally-checkable-type new))
171   (values))
172
173 ;;; Replace all uses of OLD with uses of NEW, where NEW has an
174 ;;; arbitary number of uses. If NEW will end up with more than one
175 ;;; use, then we must arrange for it to start a block if it doesn't
176 ;;; already.
177 (defun substitute-continuation-uses (new old)
178   (declare (type continuation old new))
179   (unless (and (eq (continuation-kind new) :unused)
180                (eq (continuation-kind old) :inside-block))
181     (ensure-block-start new))
182
183   (do-uses (node old)
184     (delete-continuation-use node)
185     (add-continuation-use node new))
186   (dolist (lexenv-use (continuation-lexenv-uses old)) ; FIXME - APD
187     (setf (cadr lexenv-use) new))
188
189   (reoptimize-continuation new)
190   (values))
191 \f
192 ;;;; block starting/creation
193
194 ;;; Return the block that CONT is the start of, making a block if
195 ;;; necessary. This function is called by IR1 translators which may
196 ;;; cause a continuation to be used more than once. Every continuation
197 ;;; which may be used more than once must start a block by the time
198 ;;; that anyone does a USE-CONTINUATION on it.
199 ;;;
200 ;;; We also throw the block into the next/prev list for the
201 ;;; *CURRENT-COMPONENT* so that we keep track of which blocks we have
202 ;;; made.
203 (defun continuation-starts-block (cont)
204   (declare (type continuation cont))
205   (ecase (continuation-kind cont)
206     (:unused
207      (aver (not (continuation-block cont)))
208      (let* ((next (component-last-block *current-component*))
209             (prev (block-prev next))
210             (new-block (make-block cont)))
211        (setf (block-next new-block) next
212              (block-prev new-block) prev
213              (block-prev next) new-block
214              (block-next prev) new-block
215              (continuation-block cont) new-block
216              (continuation-use cont) nil
217              (continuation-kind cont) :block-start)
218        new-block))
219     (:block-start
220      (continuation-block cont))))
221
222 ;;; Ensure that CONT is the start of a block (or deleted) so that
223 ;;; the use set can be freely manipulated.
224 ;;; -- If the continuation is :UNUSED or is :INSIDE-BLOCK and the
225 ;;;    CONT of LAST in its block, then we make it the start of a new
226 ;;;    deleted block.
227 ;;; -- If the continuation is :INSIDE-BLOCK inside a block, then we
228 ;;;    split the block using NODE-ENDS-BLOCK, which makes the
229 ;;;    continuation be a :BLOCK-START.
230 (defun ensure-block-start (cont)
231   (declare (type continuation cont))
232   (let ((kind (continuation-kind cont)))
233     (ecase kind
234       ((:deleted :block-start :deleted-block-start))
235       ((:unused :inside-block)
236        (let ((block (continuation-block cont)))
237          (cond ((or (eq kind :unused)
238                     (eq (node-cont (block-last block)) cont))
239                 (setf (continuation-block cont)
240                       (make-block-key :start cont
241                                       :component nil
242                                       :start-uses (find-uses cont)))
243                 (setf (continuation-kind cont) :deleted-block-start))
244                (t
245                 (node-ends-block (continuation-use cont))))))))
246   (values))
247 \f
248 ;;;;
249
250 ;;; Filter values of CONT with a destination through FORM, which must
251 ;;; be an ordinary/mv call. First argument must be 'DUMMY, which will
252 ;;; be replaced with CONT. In case of an ordinary call the function
253 ;;; should not have return type NIL.
254 ;;;
255 ;;; TODO: remove preconditions.
256 (defun filter-continuation (cont form)
257   (declare (type continuation cont) (type list form))
258   (let ((dest (continuation-dest cont)))
259     (declare (type node dest))
260     (with-ir1-environment-from-node dest
261
262       ;; Ensuring that CONT starts a block lets us freely manipulate its uses.
263       (ensure-block-start cont)
264
265       ;; Make a new continuation and move CONT's uses to it.
266       (let ((new-start (make-continuation))
267             (prev (node-prev dest)))
268         (continuation-starts-block new-start)
269         (substitute-continuation-uses new-start cont)
270
271         ;; Make the DEST node start its block so that we can splice in
272         ;; the LAMBDA code.
273         (when (continuation-use prev)
274           (node-ends-block (continuation-use prev)))
275
276         (let* ((prev-block (continuation-block prev))
277                (new-block (continuation-block new-start))
278                (dummy (make-continuation)))
279
280           ;; Splice in the new block before DEST, giving the new block
281           ;; all of DEST's predecessors.
282           (dolist (block (block-pred prev-block))
283             (change-block-successor block prev-block new-block))
284
285           ;; Convert the lambda form, using the new block start as
286           ;; START and a dummy continuation as CONT.
287           (ir1-convert new-start dummy form)
288
289           ;; TODO: Why should this be true? -- WHN 19990601
290           ;;
291           ;; It is somehow related to the precondition of non-NIL
292           ;; return type of the function. -- APD 2003-3-24
293           (aver (eq (continuation-block dummy) new-block))
294
295           ;; KLUDGE: Comments at the head of this function in CMU CL
296           ;; said that somewhere in here we
297           ;;   Set the new block's start and end cleanups to the *start*
298           ;;   cleanup of PREV's block. This overrides the incorrect
299           ;;   default from WITH-IR1-ENVIRONMENT-FROM-NODE.
300           ;; Unfortunately I can't find any code which corresponds to this.
301           ;; Perhaps it was a stale comment? Or perhaps I just don't
302           ;; understand.. -- WHN 19990521
303
304           (let ((node (continuation-use dummy)))
305             (setf (block-last new-block) node)
306             ;; Change the use to a use of CONT. (We need to use the
307             ;; dummy continuation to get the control transfer right,
308             ;; because we want to go to PREV's block, not CONT's.)
309             (delete-continuation-use node)
310             (add-continuation-use node cont))
311           ;; Link the new block to PREV's block.
312           (link-blocks new-block prev-block))
313
314         ;; Replace 'DUMMY with the new continuation. (We can find
315         ;; 'DUMMY because no LET conversion has been done yet.) The
316         ;; [mv-]combination code from the call in the form will be the
317         ;; use of the new check continuation. We substitute for the
318         ;; first argument of this node.
319         (let* ((node (continuation-use cont))
320                (args (basic-combination-args node))
321                (victim (first args)))
322           (aver (eq (constant-value (ref-leaf (continuation-use victim)))
323                     'dummy))
324           (substitute-continuation new-start victim)))
325
326       ;; Invoking local call analysis converts this call to a LET.
327       (locall-analyze-component *current-component*)
328
329       (values))))
330
331 ;;; Deleting a filter may result in some calls becoming tail.
332 (defun delete-filter (node cont value)
333   (collect ((merges))
334     (prog2
335         (when (return-p (continuation-dest cont))
336           (do-uses (use value)
337             (when (and (basic-combination-p use)
338                        (eq (basic-combination-kind use) :local))
339               (merges use))))
340         (cond ((and (eq (continuation-kind cont) :inside-block)
341                     (eq (continuation-kind value) :inside-block))
342                (setf (continuation-dest value) nil)
343                (substitute-continuation value cont)
344                (prog1 (unlink-node node)
345                  (setq cont value)))
346               (t (ensure-block-start value)
347                  (ensure-block-start cont)
348                  (substitute-continuation-uses cont value)
349                  (prog1 (unlink-node node)
350                    (setf (continuation-dest value) nil))))
351       (dolist (merge (merges))
352         (merge-tail-sets merge)))))
353 \f
354 ;;;; miscellaneous shorthand functions
355
356 ;;; Return the home (i.e. enclosing non-LET) CLAMBDA for NODE. Since
357 ;;; the LEXENV-LAMBDA may be deleted, we must chain up the
358 ;;; LAMBDA-CALL-LEXENV thread until we find a CLAMBDA that isn't
359 ;;; deleted, and then return its home.
360 (defun node-home-lambda (node)
361   (declare (type node node))
362   (do ((fun (lexenv-lambda (node-lexenv node))
363             (lexenv-lambda (lambda-call-lexenv fun))))
364       ((not (eq (functional-kind fun) :deleted))
365        (lambda-home fun))
366     (when (eq (lambda-home fun) fun)
367       (return fun))))
368
369 (defun node-block (node)
370   (declare (type node node))
371   (the cblock (continuation-block (node-prev node))))
372 (defun node-component (node)
373   (declare (type node node))
374   (block-component (node-block node)))
375 (defun node-physenv (node)
376   (declare (type node node))
377   (the physenv (lambda-physenv (node-home-lambda node))))
378
379 (defun lambda-block (clambda)
380   (declare (type clambda clambda))
381   (node-block (lambda-bind clambda)))
382 (defun lambda-component (clambda)
383   (block-component (lambda-block clambda)))
384
385 ;;; Return the enclosing cleanup for environment of the first or last
386 ;;; node in BLOCK.
387 (defun block-start-cleanup (block)
388   (declare (type cblock block))
389   (node-enclosing-cleanup (continuation-next (block-start block))))
390 (defun block-end-cleanup (block)
391   (declare (type cblock block))
392   (node-enclosing-cleanup (block-last block)))
393
394 ;;; Return the non-LET LAMBDA that holds BLOCK's code, or NIL
395 ;;; if there is none.
396 ;;;
397 ;;; There can legitimately be no home lambda in dead code early in the
398 ;;; IR1 conversion process, e.g. when IR1-converting the SETQ form in
399 ;;;   (BLOCK B (RETURN-FROM B) (SETQ X 3))
400 ;;; where the block is just a placeholder during parsing and doesn't
401 ;;; actually correspond to code which will be written anywhere.
402 (declaim (ftype (sfunction (cblock) (or clambda null)) block-home-lambda-or-null))
403 (defun block-home-lambda-or-null (block)
404   (if (node-p (block-last block))
405       ;; This is the old CMU CL way of doing it.
406       (node-home-lambda (block-last block))
407       ;; Now that SBCL uses this operation more aggressively than CMU
408       ;; CL did, the old CMU CL way of doing it can fail in two ways.
409       ;;   1. It can fail in a few cases even when a meaningful home
410       ;;      lambda exists, e.g. in IR1-CONVERT of one of the legs of
411       ;;      an IF.
412       ;;   2. It can fail when converting a form which is born orphaned 
413       ;;      so that it never had a meaningful home lambda, e.g. a form
414       ;;      which follows a RETURN-FROM or GO form.
415       (let ((pred-list (block-pred block)))
416         ;; To deal with case 1, we reason that
417         ;; previous-in-target-execution-order blocks should be in the
418         ;; same lambda, and that they seem in practice to be
419         ;; previous-in-compilation-order blocks too, so we look back
420         ;; to find one which is sufficiently initialized to tell us
421         ;; what the home lambda is.
422         (if pred-list
423             ;; We could get fancy about this, flooding through the
424             ;; graph of all the previous blocks, but in practice it
425             ;; seems to work just to grab the first previous block and
426             ;; use it.
427             (node-home-lambda (block-last (first pred-list)))
428             ;; In case 2, we end up with an empty PRED-LIST and
429             ;; have to punt: There's no home lambda.
430             nil))))
431
432 ;;; Return the non-LET LAMBDA that holds BLOCK's code.
433 (defun block-home-lambda (block)
434   (the clambda
435     (block-home-lambda-or-null block)))
436
437 ;;; Return the IR1 physical environment for BLOCK.
438 (defun block-physenv (block)
439   (declare (type cblock block))
440   (lambda-physenv (block-home-lambda block)))
441
442 ;;; Return the Top Level Form number of PATH, i.e. the ordinal number
443 ;;; of its original source's top level form in its compilation unit.
444 (defun source-path-tlf-number (path)
445   (declare (list path))
446   (car (last path)))
447
448 ;;; Return the (reversed) list for the PATH in the original source
449 ;;; (with the Top Level Form number last).
450 (defun source-path-original-source (path)
451   (declare (list path) (inline member))
452   (cddr (member 'original-source-start path :test #'eq)))
453
454 ;;; Return the Form Number of PATH's original source inside the Top
455 ;;; Level Form that contains it. This is determined by the order that
456 ;;; we walk the subforms of the top level source form.
457 (defun source-path-form-number (path)
458   (declare (list path) (inline member))
459   (cadr (member 'original-source-start path :test #'eq)))
460
461 ;;; Return a list of all the enclosing forms not in the original
462 ;;; source that converted to get to this form, with the immediate
463 ;;; source for node at the start of the list.
464 (defun source-path-forms (path)
465   (subseq path 0 (position 'original-source-start path)))
466
467 ;;; Return the innermost source form for NODE.
468 (defun node-source-form (node)
469   (declare (type node node))
470   (let* ((path (node-source-path node))
471          (forms (source-path-forms path)))
472     (if forms
473         (first forms)
474         (values (find-original-source path)))))
475
476 ;;; Return NODE-SOURCE-FORM, T if continuation has a single use,
477 ;;; otherwise NIL, NIL.
478 (defun continuation-source (cont)
479   (let ((use (continuation-use cont)))
480     (if use
481         (values (node-source-form use) t)
482         (values nil nil))))
483
484 ;;; Return the LAMBDA that is CONT's home, or NIL if there is none.
485 (declaim (ftype (sfunction (continuation) (or clambda null))
486                 continuation-home-lambda-or-null))
487 (defun continuation-home-lambda-or-null (cont)
488   ;; KLUDGE: This function is a post-CMU-CL hack by WHN, and this
489   ;; implementation might not be quite right, or might be uglier than
490   ;; necessary. It appears that the original Python never found a need
491   ;; to do this operation. The obvious things based on
492   ;; NODE-HOME-LAMBDA of CONTINUATION-USE usually work; then if that
493   ;; fails, BLOCK-HOME-LAMBDA of CONTINUATION-BLOCK works, given that
494   ;; we generalize it enough to grovel harder when the simple CMU CL
495   ;; approach fails, and furthermore realize that in some exceptional
496   ;; cases it might return NIL. -- WHN 2001-12-04
497   (cond ((continuation-use cont)
498          (node-home-lambda (continuation-use cont)))
499         ((continuation-block cont)
500          (block-home-lambda-or-null (continuation-block cont)))
501         (t
502          (bug "confused about home lambda for ~S"))))
503
504 ;;; Return the LAMBDA that is CONT's home.
505 (defun continuation-home-lambda (cont)
506   (the clambda
507     (continuation-home-lambda-or-null cont)))
508
509 #!-sb-fluid (declaim (inline continuation-single-value-p))
510 (defun continuation-single-value-p (cont)
511   (let ((dest (continuation-dest cont)))
512     (typecase dest
513       ((or creturn exit cast)
514        nil)
515       (mv-combination
516        (eq (basic-combination-fun dest) cont))
517       (t
518        t))))
519
520 (defun principal-continuation-end (cont)
521   (loop for prev = cont then (node-cont dest)
522         for dest = (continuation-dest prev)
523         while (cast-p dest)
524         finally (return (values dest prev))))
525 \f
526 ;;; Return a new LEXENV just like DEFAULT except for the specified
527 ;;; slot values. Values for the alist slots are NCONCed to the
528 ;;; beginning of the current value, rather than replacing it entirely.
529 (defun make-lexenv (&key (default *lexenv*)
530                          funs vars blocks tags
531                          type-restrictions weakend-type-restrictions
532                          (lambda (lexenv-lambda default))
533                          (cleanup (lexenv-cleanup default))
534                          (policy (lexenv-policy default)))
535   (macrolet ((frob (var slot)
536                `(let ((old (,slot default)))
537                   (if ,var
538                       (nconc ,var old)
539                       old))))
540     (internal-make-lexenv
541      (frob funs lexenv-funs)
542      (frob vars lexenv-vars)
543      (frob blocks lexenv-blocks)
544      (frob tags lexenv-tags)
545      (frob type-restrictions lexenv-type-restrictions)
546      (frob weakend-type-restrictions lexenv-weakend-type-restrictions)
547      lambda cleanup policy)))
548
549 ;;; Makes a LEXENV, suitable for using in a MACROLET introduced
550 ;;; macroexpander
551 (defun make-restricted-lexenv (lexenv)
552   (flet ((fun-good-p (fun)
553            (destructuring-bind (name . thing) fun
554              (declare (ignore name))
555              (etypecase thing
556                (functional nil)
557                (global-var t)
558                (cons (aver (eq (car thing) 'macro))
559                      t))))
560          (var-good-p (var)
561            (destructuring-bind (name . thing) var
562              (declare (ignore name))
563              (etypecase thing
564                (leaf nil)
565                (cons (aver (eq (car thing) 'macro))
566                      t)
567                (heap-alien-info nil)))))
568     (internal-make-lexenv
569      (remove-if-not #'fun-good-p (lexenv-funs lexenv))
570      (remove-if-not #'var-good-p (lexenv-vars lexenv))
571      nil
572      nil
573      (lexenv-type-restrictions lexenv) ; XXX
574      (lexenv-weakend-type-restrictions lexenv)
575      nil
576      nil
577      (lexenv-policy lexenv))))
578 \f
579 ;;;; flow/DFO/component hackery
580
581 ;;; Join BLOCK1 and BLOCK2.
582 (defun link-blocks (block1 block2)
583   (declare (type cblock block1 block2))
584   (setf (block-succ block1)
585         (if (block-succ block1)
586             (%link-blocks block1 block2)
587             (list block2)))
588   (push block1 (block-pred block2))
589   (values))
590 (defun %link-blocks (block1 block2)
591   (declare (type cblock block1 block2) (inline member))
592   (let ((succ1 (block-succ block1)))
593     (aver (not (member block2 succ1 :test #'eq)))
594     (cons block2 succ1)))
595
596 ;;; This is like LINK-BLOCKS, but we separate BLOCK1 and BLOCK2. If
597 ;;; this leaves a successor with a single predecessor that ends in an
598 ;;; IF, then set BLOCK-TEST-MODIFIED so that any test constraint will
599 ;;; now be able to be propagated to the successor.
600 (defun unlink-blocks (block1 block2)
601   (declare (type cblock block1 block2))
602   (let ((succ1 (block-succ block1)))
603     (if (eq block2 (car succ1))
604         (setf (block-succ block1) (cdr succ1))
605         (do ((succ (cdr succ1) (cdr succ))
606              (prev succ1 succ))
607             ((eq (car succ) block2)
608              (setf (cdr prev) (cdr succ)))
609           (aver succ))))
610
611   (let ((new-pred (delq block1 (block-pred block2))))
612     (setf (block-pred block2) new-pred)
613     (when (singleton-p new-pred)
614       (let ((pred-block (first new-pred)))
615         (when (if-p (block-last pred-block))
616           (setf (block-test-modified pred-block) t)))))
617   (values))
618
619 ;;; Swing the succ/pred link between BLOCK and OLD to be between BLOCK
620 ;;; and NEW. If BLOCK ends in an IF, then we have to fix up the
621 ;;; consequent/alternative blocks to point to NEW. We also set
622 ;;; BLOCK-TEST-MODIFIED so that any test constraint will be applied to
623 ;;; the new successor.
624 (defun change-block-successor (block old new)
625   (declare (type cblock new old block) (inline member))
626   (unlink-blocks block old)
627   (let ((last (block-last block))
628         (comp (block-component block)))
629     (setf (component-reanalyze comp) t)
630     (typecase last
631       (cif
632        (setf (block-test-modified block) t)
633        (let* ((succ-left (block-succ block))
634               (new (if (and (eq new (component-tail comp))
635                             succ-left)
636                        (first succ-left)
637                        new)))
638          (unless (member new succ-left :test #'eq)
639            (link-blocks block new))
640          (macrolet ((frob (slot)
641                       `(when (eq (,slot last) old)
642                          (setf (,slot last) new))))
643            (frob if-consequent)
644            (frob if-alternative)
645            (when (eq (if-consequent last)
646                      (if-alternative last))
647              (setf (component-reoptimize (block-component block)) t)))))
648       (t
649        (unless (member new (block-succ block) :test #'eq)
650          (link-blocks block new)))))
651
652   (values))
653
654 ;;; Unlink a block from the next/prev chain. We also null out the
655 ;;; COMPONENT.
656 (declaim (ftype (function (cblock) (values)) remove-from-dfo))
657 (defun remove-from-dfo (block)
658   (let ((next (block-next block))
659         (prev (block-prev block)))
660     (setf (block-component block) nil)
661     (setf (block-next prev) next)
662     (setf (block-prev next) prev))
663   (values))
664
665 ;;; Add BLOCK to the next/prev chain following AFTER. We also set the
666 ;;; COMPONENT to be the same as for AFTER.
667 (defun add-to-dfo (block after)
668   (declare (type cblock block after))
669   (let ((next (block-next after))
670         (comp (block-component after)))
671     (aver (not (eq (component-kind comp) :deleted)))
672     (setf (block-component block) comp)
673     (setf (block-next after) block)
674     (setf (block-prev block) after)
675     (setf (block-next block) next)
676     (setf (block-prev next) block))
677   (values))
678
679 ;;; Set the FLAG for all the blocks in COMPONENT to NIL, except for
680 ;;; the head and tail which are set to T.
681 (declaim (ftype (function (component) (values)) clear-flags))
682 (defun clear-flags (component)
683   (let ((head (component-head component))
684         (tail (component-tail component)))
685     (setf (block-flag head) t)
686     (setf (block-flag tail) t)
687     (do-blocks (block component)
688       (setf (block-flag block) nil)))
689   (values))
690
691 ;;; Make a component with no blocks in it. The BLOCK-FLAG is initially
692 ;;; true in the head and tail blocks.
693 (declaim (ftype (function nil component) make-empty-component))
694 (defun make-empty-component ()
695   (let* ((head (make-block-key :start nil :component nil))
696          (tail (make-block-key :start nil :component nil))
697          (res (make-component head tail)))
698     (setf (block-flag head) t)
699     (setf (block-flag tail) t)
700     (setf (block-component head) res)
701     (setf (block-component tail) res)
702     (setf (block-next head) tail)
703     (setf (block-prev tail) head)
704     res))
705
706 ;;; Make NODE the LAST node in its block, splitting the block if necessary.
707 ;;; The new block is added to the DFO immediately following NODE's block.
708 (defun node-ends-block (node)
709   (declare (type node node))
710   (let* ((block (node-block node))
711          (start (node-cont node))
712          (last (block-last block))
713          (last-cont (node-cont last)))
714     (unless (eq last node)
715       (aver (and (eq (continuation-kind start) :inside-block)
716                    (not (block-delete-p block))))
717       (let* ((succ (block-succ block))
718              (new-block
719               (make-block-key :start start
720                               :component (block-component block)
721                               :start-uses (list (continuation-use start))
722                               :succ succ :last last)))
723         (setf (continuation-kind start) :block-start)
724         (dolist (b succ)
725           (setf (block-pred b)
726                 (cons new-block (remove block (block-pred b)))))
727         (setf (block-succ block) ())
728         (setf (block-last block) node)
729         (link-blocks block new-block)
730         (add-to-dfo new-block block)
731         (setf (component-reanalyze (block-component block)) t)
732
733         (do ((cont start (node-cont (continuation-next cont))))
734             ((eq cont last-cont)
735              (when (eq (continuation-kind last-cont) :inside-block)
736                (setf (continuation-block last-cont) new-block)))
737           (setf (continuation-block cont) new-block))
738
739         (setf (block-type-asserted block) t)
740         (setf (block-test-modified block) t))))
741
742   (values))
743 \f
744 ;;;; deleting stuff
745
746 ;;; Deal with deleting the last (read) reference to a LAMBDA-VAR.
747 (defun delete-lambda-var (leaf)
748   (declare (type lambda-var leaf))
749
750   ;; Iterate over all local calls flushing the corresponding argument,
751   ;; allowing the computation of the argument to be deleted. We also
752   ;; mark the LET for reoptimization, since it may be that we have
753   ;; deleted its last variable.
754   (let* ((fun (lambda-var-home leaf))
755          (n (position leaf (lambda-vars fun))))
756     (dolist (ref (leaf-refs fun))
757       (let* ((cont (node-cont ref))
758              (dest (continuation-dest cont)))
759         (when (and (combination-p dest)
760                    (eq (basic-combination-fun dest) cont)
761                    (eq (basic-combination-kind dest) :local))
762           (let* ((args (basic-combination-args dest))
763                  (arg (elt args n)))
764             (reoptimize-continuation arg)
765             (flush-dest arg)
766             (setf (elt args n) nil))))))
767
768   ;; The LAMBDA-VAR may still have some SETs, but this doesn't cause
769   ;; too much difficulty, since we can efficiently implement
770   ;; write-only variables. We iterate over the SETs, marking their
771   ;; blocks for dead code flushing, since we can delete SETs whose
772   ;; value is unused.
773   (dolist (set (lambda-var-sets leaf))
774     (setf (block-flush-p (node-block set)) t))
775
776   (values))
777
778 ;;; Note that something interesting has happened to VAR.
779 (defun reoptimize-lambda-var (var)
780   (declare (type lambda-var var))
781   (let ((fun (lambda-var-home var)))
782     ;; We only deal with LET variables, marking the corresponding
783     ;; initial value arg as needing to be reoptimized.
784     (when (and (eq (functional-kind fun) :let)
785                (leaf-refs var))
786       (do ((args (basic-combination-args
787                   (continuation-dest
788                    (node-cont
789                     (first (leaf-refs fun)))))
790                  (cdr args))
791            (vars (lambda-vars fun) (cdr vars)))
792           ((eq (car vars) var)
793            (reoptimize-continuation (car args))))))
794   (values))
795
796 ;;; Delete a function that has no references. This need only be called
797 ;;; on functions that never had any references, since otherwise
798 ;;; DELETE-REF will handle the deletion.
799 (defun delete-functional (fun)
800   (aver (and (null (leaf-refs fun))
801              (not (functional-entry-fun fun))))
802   (etypecase fun
803     (optional-dispatch (delete-optional-dispatch fun))
804     (clambda (delete-lambda fun)))
805   (values))
806
807 ;;; Deal with deleting the last reference to a CLAMBDA. Since there is
808 ;;; only one way into a CLAMBDA, deleting the last reference to a
809 ;;; CLAMBDA ensures that there is no way to reach any of the code in
810 ;;; it. So we just set the FUNCTIONAL-KIND for FUN and its LETs to
811 ;;; :DELETED, causing IR1 optimization to delete blocks in that
812 ;;; CLAMBDA.
813 (defun delete-lambda (clambda)
814   (declare (type clambda clambda))
815   (let ((original-kind (functional-kind clambda))
816         (bind (lambda-bind clambda)))
817     (aver (not (member original-kind '(:deleted :optional :toplevel))))
818     (aver (not (functional-has-external-references-p clambda)))
819     (setf (functional-kind clambda) :deleted)
820     (setf (lambda-bind clambda) nil)
821     (dolist (let (lambda-lets clambda))
822       (setf (lambda-bind let) nil)
823       (setf (functional-kind let) :deleted))
824
825     ;; LET may be deleted if its BIND is unreachable. Autonomous
826     ;; function may be deleted if it has no reachable references.
827     (unless (member original-kind '(:let :mv-let :assignment))
828       (dolist (ref (lambda-refs clambda))
829         (mark-for-deletion (node-block ref))))
830
831     ;; (The IF test is (FUNCTIONAL-SOMEWHAT-LETLIKE-P CLAMBDA), except
832     ;; that we're using the old value of the KIND slot, not the
833     ;; current slot value, which has now been set to :DELETED.)
834     (if (member original-kind '(:let :mv-let :assignment))
835         (let ((home (lambda-home clambda)))
836           (setf (lambda-lets home) (delete clambda (lambda-lets home))))
837         ;; If the function isn't a LET, we unlink the function head
838         ;; and tail from the component head and tail to indicate that
839         ;; the code is unreachable. We also delete the function from
840         ;; COMPONENT-LAMBDAS (it won't be there before local call
841         ;; analysis, but no matter.) If the lambda was never
842         ;; referenced, we give a note.
843         (let* ((bind-block (node-block bind))
844                (component (block-component bind-block))
845                (return (lambda-return clambda))
846                (return-block (and return (node-block return))))
847           (unless (leaf-ever-used clambda)
848             (let ((*compiler-error-context* bind))
849               (compiler-note "deleting unused function~:[.~;~:*~%  ~S~]"
850                              (leaf-debug-name clambda))))
851           (unless (block-delete-p bind-block)
852             (unlink-blocks (component-head component) bind-block))
853           (when (and return-block (not (block-delete-p return-block)))
854             (mark-for-deletion return-block)
855             (unlink-blocks return-block (component-tail component)))
856           (setf (component-reanalyze component) t)
857           (let ((tails (lambda-tail-set clambda)))
858             (setf (tail-set-funs tails)
859                   (delete clambda (tail-set-funs tails)))
860             (setf (lambda-tail-set clambda) nil))
861           (setf (component-lambdas component)
862                 (delete clambda (component-lambdas component)))))
863
864     ;; If the lambda is an XEP, then we null out the ENTRY-FUN in its
865     ;; ENTRY-FUN so that people will know that it is not an entry
866     ;; point anymore.
867     (when (eq original-kind :external)
868       (let ((fun (functional-entry-fun clambda)))
869         (setf (functional-entry-fun fun) nil)
870         (when (optional-dispatch-p fun)
871           (delete-optional-dispatch fun)))))
872
873   (values))
874
875 ;;; Deal with deleting the last reference to an OPTIONAL-DISPATCH. We
876 ;;; have to be a bit more careful than with lambdas, since DELETE-REF
877 ;;; is used both before and after local call analysis. Afterward, all
878 ;;; references to still-existing OPTIONAL-DISPATCHes have been moved
879 ;;; to the XEP, leaving it with no references at all. So we look at
880 ;;; the XEP to see whether an optional-dispatch is still really being
881 ;;; used. But before local call analysis, there are no XEPs, and all
882 ;;; references are direct.
883 ;;;
884 ;;; When we do delete the OPTIONAL-DISPATCH, we grovel all of its
885 ;;; entry-points, making them be normal lambdas, and then deleting the
886 ;;; ones with no references. This deletes any e-p lambdas that were
887 ;;; either never referenced, or couldn't be deleted when the last
888 ;;; reference was deleted (due to their :OPTIONAL kind.)
889 ;;;
890 ;;; Note that the last optional entry point may alias the main entry,
891 ;;; so when we process the main entry, its KIND may have been changed
892 ;;; to NIL or even converted to a LETlike value.
893 (defun delete-optional-dispatch (leaf)
894   (declare (type optional-dispatch leaf))
895   (let ((entry (functional-entry-fun leaf)))
896     (unless (and entry (leaf-refs entry))
897       (aver (or (not entry) (eq (functional-kind entry) :deleted)))
898       (setf (functional-kind leaf) :deleted)
899
900       (flet ((frob (fun)
901                (unless (eq (functional-kind fun) :deleted)
902                  (aver (eq (functional-kind fun) :optional))
903                  (setf (functional-kind fun) nil)
904                  (let ((refs (leaf-refs fun)))
905                    (cond ((null refs)
906                           (delete-lambda fun))
907                          ((null (rest refs))
908                           (or (maybe-let-convert fun)
909                               (maybe-convert-to-assignment fun)))
910                          (t
911                           (maybe-convert-to-assignment fun)))))))
912
913         (dolist (ep (optional-dispatch-entry-points leaf))
914           (frob ep))
915         (when (optional-dispatch-more-entry leaf)
916           (frob (optional-dispatch-more-entry leaf)))
917         (let ((main (optional-dispatch-main-entry leaf)))
918           (when (eq (functional-kind main) :optional)
919             (frob main))))))
920
921   (values))
922
923 ;;; Do stuff to delete the semantic attachments of a REF node. When
924 ;;; this leaves zero or one reference, we do a type dispatch off of
925 ;;; the leaf to determine if a special action is appropriate.
926 (defun delete-ref (ref)
927   (declare (type ref ref))
928   (let* ((leaf (ref-leaf ref))
929          (refs (delete ref (leaf-refs leaf))))
930     (setf (leaf-refs leaf) refs)
931
932     (cond ((null refs)
933            (typecase leaf
934              (lambda-var
935               (delete-lambda-var leaf))
936              (clambda
937               (ecase (functional-kind leaf)
938                 ((nil :let :mv-let :assignment :escape :cleanup)
939                  (aver (null (functional-entry-fun leaf)))
940                  (delete-lambda leaf))
941                 (:external
942                  (delete-lambda leaf))
943                 ((:deleted :optional))))
944              (optional-dispatch
945               (unless (eq (functional-kind leaf) :deleted)
946                 (delete-optional-dispatch leaf)))))
947           ((null (rest refs))
948            (typecase leaf
949              (clambda (or (maybe-let-convert leaf)
950                           (maybe-convert-to-assignment leaf)))
951              (lambda-var (reoptimize-lambda-var leaf))))
952           (t
953            (typecase leaf
954              (clambda (maybe-convert-to-assignment leaf))))))
955
956   (values))
957
958 ;;; This function is called by people who delete nodes; it provides a
959 ;;; way to indicate that the value of a continuation is no longer
960 ;;; used. We null out the CONTINUATION-DEST, set FLUSH-P in the blocks
961 ;;; containing uses of CONT and set COMPONENT-REOPTIMIZE. If the PREV
962 ;;; of the use is deleted, then we blow off reoptimization.
963 ;;;
964 ;;; If the continuation is :DELETED, then we don't do anything, since
965 ;;; all semantics have already been flushed. :DELETED-BLOCK-START
966 ;;; start continuations are treated just like :BLOCK-START; it is
967 ;;; possible that the continuation may be given a new dest (e.g. by
968 ;;; SUBSTITUTE-CONTINUATION), so we don't want to delete it.
969 (defun flush-dest (cont)
970   (declare (type continuation cont))
971
972   (unless (eq (continuation-kind cont) :deleted)
973     (aver (continuation-dest cont))
974     (setf (continuation-dest cont) nil)
975     (flush-continuation-externally-checkable-type cont)
976     (do-uses (use cont)
977       (let ((prev (node-prev use)))
978         (unless (eq (continuation-kind prev) :deleted)
979           (let ((block (continuation-block prev)))
980             (setf (component-reoptimize (block-component block)) t)
981             (setf (block-attributep (block-flags block) flush-p type-asserted)
982                   t))))))
983
984   (values))
985
986 (defun delete-dest (cont)
987   (let ((dest (continuation-dest cont)))
988     (when dest
989       (let ((prev (node-prev dest)))
990         (when (and prev
991                    (not (eq (continuation-kind prev) :deleted)))
992           (let ((block (continuation-block prev)))
993             (unless (block-delete-p block)
994               (mark-for-deletion block))))))))
995
996 ;;; Do a graph walk backward from BLOCK, marking all predecessor
997 ;;; blocks with the DELETE-P flag.
998 (defun mark-for-deletion (block)
999   (declare (type cblock block))
1000   (let* ((component (block-component block))
1001          (head (component-head component)))
1002     (labels ((helper (block)
1003                (setf (block-delete-p block) t)
1004                (dolist (pred (block-pred block))
1005                  (unless (or (block-delete-p pred)
1006                              (eq pred head))
1007                    (helper pred)))))
1008       (unless (block-delete-p block)
1009         (helper block)
1010         (setf (component-reanalyze component) t))))
1011   (values))
1012
1013 ;;; Delete CONT, eliminating both control and value semantics. We set
1014 ;;; FLUSH-P and COMPONENT-REOPTIMIZE similarly to in FLUSH-DEST. Here
1015 ;;; we must get the component from the use block, since the
1016 ;;; continuation may be a :DELETED-BLOCK-START.
1017 ;;;
1018 ;;; If CONT has DEST, then it must be the case that the DEST is
1019 ;;; unreachable, since we can't compute the value desired. In this
1020 ;;; case, we call MARK-FOR-DELETION to cause the DEST block and its
1021 ;;; predecessors to tell people to ignore them, and to cause them to
1022 ;;; be deleted eventually.
1023 (defun delete-continuation (cont)
1024   (declare (type continuation cont))
1025   (aver (not (eq (continuation-kind cont) :deleted)))
1026
1027   (do-uses (use cont)
1028     (let ((prev (node-prev use)))
1029       (unless (eq (continuation-kind prev) :deleted)
1030         (let ((block (continuation-block prev)))
1031           (setf (block-attributep (block-flags block) flush-p type-asserted) t)
1032           (setf (component-reoptimize (block-component block)) t)))))
1033
1034   (delete-dest cont)
1035
1036   (setf (continuation-kind cont) :deleted)
1037   (setf (continuation-dest cont) nil)
1038   (flush-continuation-externally-checkable-type cont)
1039   (setf (continuation-next cont) nil)
1040   (setf (continuation-%derived-type cont) *empty-type*)
1041   (setf (continuation-use cont) nil)
1042   (setf (continuation-block cont) nil)
1043   (setf (continuation-reoptimize cont) nil)
1044   (setf (continuation-info cont) nil)
1045
1046   (values))
1047
1048 ;;; This function does what is necessary to eliminate the code in it
1049 ;;; from the IR1 representation. This involves unlinking it from its
1050 ;;; predecessors and successors and deleting various node-specific
1051 ;;; semantic information.
1052 ;;;
1053 ;;; We mark the START as has having no next and remove the last node
1054 ;;; from its CONT's uses. We also flush the DEST for all continuations
1055 ;;; whose values are received by nodes in the block.
1056 (defun delete-block (block)
1057   (declare (type cblock block))
1058   (aver (block-component block))      ; else block is already deleted!
1059   (note-block-deletion block)
1060   (setf (block-delete-p block) t)
1061
1062   (let* ((last (block-last block))
1063          (cont (node-cont last)))
1064     (delete-continuation-use last)
1065     (if (eq (continuation-kind cont) :unused)
1066         (delete-continuation cont)
1067         (reoptimize-continuation cont)))
1068
1069   (dolist (b (block-pred block))
1070     (unlink-blocks b block)
1071     ;; In bug 147 the almost-all-blocks-have-a-successor invariant was
1072     ;; broken when successors were deleted without setting the
1073     ;; BLOCK-DELETE-P flags of their predececessors. Make sure that
1074     ;; doesn't happen again.
1075     (aver (not (and (null (block-succ b))
1076                     (not (block-delete-p b))
1077                     (not (eq b (component-head (block-component b))))))))
1078   (dolist (b (block-succ block))
1079     (unlink-blocks block b))
1080
1081   (do-nodes (node cont block)
1082     (typecase node
1083       (ref (delete-ref node))
1084       (cif
1085        (flush-dest (if-test node)))
1086       ;; The next two cases serve to maintain the invariant that a LET
1087       ;; always has a well-formed COMBINATION, REF and BIND. We delete
1088       ;; the lambda whenever we delete any of these, but we must be
1089       ;; careful that this LET has not already been partially deleted.
1090       (basic-combination
1091        (when (and (eq (basic-combination-kind node) :local)
1092                   ;; Guards COMBINATION-LAMBDA agains the REF being deleted.
1093                   (continuation-use (basic-combination-fun node)))
1094          (let ((fun (combination-lambda node)))
1095            ;; If our REF was the second-to-last ref, and has been
1096            ;; deleted, then FUN may be a LET for some other
1097            ;; combination.
1098            (when (and (functional-letlike-p fun)
1099                       (eq (let-combination fun) node))
1100              (delete-lambda fun))))
1101        (flush-dest (basic-combination-fun node))
1102        (dolist (arg (basic-combination-args node))
1103          (when arg (flush-dest arg))))
1104       (bind
1105        (let ((lambda (bind-lambda node)))
1106          (unless (eq (functional-kind lambda) :deleted)
1107            (delete-lambda lambda))))
1108       (exit
1109        (let ((value (exit-value node))
1110              (entry (exit-entry node)))
1111          (when value
1112            (flush-dest value))
1113          (when entry
1114            (setf (entry-exits entry)
1115                  (delete node (entry-exits entry))))))
1116       (creturn
1117        (flush-dest (return-result node))
1118        (delete-return node))
1119       (cset
1120        (flush-dest (set-value node))
1121        (let ((var (set-var node)))
1122          (setf (basic-var-sets var)
1123                (delete node (basic-var-sets var)))))
1124       (cast
1125        (flush-dest (cast-value node))))
1126
1127     (delete-continuation (node-prev node)))
1128
1129   (remove-from-dfo block)
1130   (values))
1131
1132 ;;; Do stuff to indicate that the return node NODE is being deleted.
1133 (defun delete-return (node)
1134   (declare (type creturn node))
1135   (let* ((fun (return-lambda node))
1136          (tail-set (lambda-tail-set fun)))
1137     (aver (lambda-return fun))
1138     (setf (lambda-return fun) nil)
1139     (when (and tail-set (not (find-if #'lambda-return
1140                                       (tail-set-funs tail-set))))
1141       (setf (tail-set-type tail-set) *empty-type*)))
1142   (values))
1143
1144 ;;; If any of the VARS in FUN was never referenced and was not
1145 ;;; declared IGNORE, then complain.
1146 (defun note-unreferenced-vars (fun)
1147   (declare (type clambda fun))
1148   (dolist (var (lambda-vars fun))
1149     (unless (or (leaf-ever-used var)
1150                 (lambda-var-ignorep var))
1151       (let ((*compiler-error-context* (lambda-bind fun)))
1152         (unless (policy *compiler-error-context* (= inhibit-warnings 3))
1153           ;; ANSI section "3.2.5 Exceptional Situations in the Compiler"
1154           ;; requires this to be no more than a STYLE-WARNING.
1155           (compiler-style-warn "The variable ~S is defined but never used."
1156                                (leaf-debug-name var)))
1157         (setf (leaf-ever-used var) t)))) ; to avoid repeated warnings? -- WHN
1158   (values))
1159
1160 (defvar *deletion-ignored-objects* '(t nil))
1161
1162 ;;; Return true if we can find OBJ in FORM, NIL otherwise. We bound
1163 ;;; our recursion so that we don't get lost in circular structures. We
1164 ;;; ignore the car of forms if they are a symbol (to prevent confusing
1165 ;;; function referencess with variables), and we also ignore anything
1166 ;;; inside ' or #'.
1167 (defun present-in-form (obj form depth)
1168   (declare (type (integer 0 20) depth))
1169   (cond ((= depth 20) nil)
1170         ((eq obj form) t)
1171         ((atom form) nil)
1172         (t
1173          (let ((first (car form))
1174                (depth (1+ depth)))
1175            (if (member first '(quote function))
1176                nil
1177                (or (and (not (symbolp first))
1178                         (present-in-form obj first depth))
1179                    (do ((l (cdr form) (cdr l))
1180                         (n 0 (1+ n)))
1181                        ((or (atom l) (> n 100))
1182                         nil)
1183                      (declare (fixnum n))
1184                      (when (present-in-form obj (car l) depth)
1185                        (return t)))))))))
1186
1187 ;;; This function is called on a block immediately before we delete
1188 ;;; it. We check to see whether any of the code about to die appeared
1189 ;;; in the original source, and emit a note if so.
1190 ;;;
1191 ;;; If the block was in a lambda is now deleted, then we ignore the
1192 ;;; whole block, since this case is picked off in DELETE-LAMBDA. We
1193 ;;; also ignore the deletion of CRETURN nodes, since it is somewhat
1194 ;;; reasonable for a function to not return, and there is a different
1195 ;;; note for that case anyway.
1196 ;;;
1197 ;;; If the actual source is an atom, then we use a bunch of heuristics
1198 ;;; to guess whether this reference really appeared in the original
1199 ;;; source:
1200 ;;; -- If a symbol, it must be interned and not a keyword.
1201 ;;; -- It must not be an easily introduced constant (T or NIL, a fixnum
1202 ;;;    or a character.)
1203 ;;; -- The atom must be "present" in the original source form, and
1204 ;;;    present in all intervening actual source forms.
1205 (defun note-block-deletion (block)
1206   (let ((home (block-home-lambda block)))
1207     (unless (eq (functional-kind home) :deleted)
1208       (do-nodes (node cont block)
1209         (let* ((path (node-source-path node))
1210                (first (first path)))
1211           (when (or (eq first 'original-source-start)
1212                     (and (atom first)
1213                          (or (not (symbolp first))
1214                              (let ((pkg (symbol-package first)))
1215                                (and pkg
1216                                     (not (eq pkg (symbol-package :end))))))
1217                          (not (member first *deletion-ignored-objects*))
1218                          (not (typep first '(or fixnum character)))
1219                          (every (lambda (x)
1220                                   (present-in-form first x 0))
1221                                 (source-path-forms path))
1222                          (present-in-form first (find-original-source path)
1223                                           0)))
1224             (unless (return-p node)
1225               (let ((*compiler-error-context* node))
1226                 (compiler-note "deleting unreachable code")))
1227             (return))))))
1228   (values))
1229
1230 ;;; Delete a node from a block, deleting the block if there are no
1231 ;;; nodes left. We remove the node from the uses of its CONT, but we
1232 ;;; don't deal with cleaning up any type-specific semantic
1233 ;;; attachments. If the CONT is :UNUSED after deleting this use, then
1234 ;;; we delete CONT. (Note :UNUSED is not the same as no uses. A
1235 ;;; continuation will only become :UNUSED if it was :INSIDE-BLOCK
1236 ;;; before.)
1237 ;;;
1238 ;;; If the node is the last node, there must be exactly one successor.
1239 ;;; We link all of our precedessors to the successor and unlink the
1240 ;;; block. In this case, we return T, otherwise NIL. If no nodes are
1241 ;;; left, and the block is a successor of itself, then we replace the
1242 ;;; only node with a degenerate exit node. This provides a way to
1243 ;;; represent the bodyless infinite loop, given the prohibition on
1244 ;;; empty blocks in IR1.
1245 (defun unlink-node (node)
1246   (declare (type node node))
1247   (let* ((cont (node-cont node))
1248          (next (continuation-next cont))
1249          (prev (node-prev node))
1250          (block (continuation-block prev))
1251          (prev-kind (continuation-kind prev))
1252          (last (block-last block)))
1253
1254     (unless (eq (continuation-kind cont) :deleted)
1255       (delete-continuation-use node)
1256       (when (eq (continuation-kind cont) :unused)
1257         (aver (not (continuation-dest cont)))
1258         (delete-continuation cont)))
1259
1260     (setf (block-type-asserted block) t)
1261     (setf (block-test-modified block) t)
1262
1263     (cond ((or (eq prev-kind :inside-block)
1264                (and (eq prev-kind :block-start)
1265                     (not (eq node last))))
1266            (cond ((eq node last)
1267                   (setf (block-last block) (continuation-use prev))
1268                   (setf (continuation-next prev) nil))
1269                  (t
1270                   (setf (continuation-next prev) next)
1271                   (setf (node-prev next) prev)
1272                   (when (and (if-p next) ; AOP wanted
1273                              (eq prev (if-test next)))
1274                     (reoptimize-continuation prev))))
1275            (setf (node-prev node) nil)
1276            nil)
1277           (t
1278            (aver (eq prev-kind :block-start))
1279            (aver (eq node last))
1280            (let* ((succ (block-succ block))
1281                   (next (first succ)))
1282              (aver (singleton-p succ))
1283              (cond
1284               ((member block succ)
1285                (with-ir1-environment-from-node node
1286                  (let ((exit (make-exit))
1287                        (dummy (make-continuation)))
1288                    (setf (continuation-next prev) nil)
1289                    (link-node-to-previous-continuation exit prev)
1290                    (add-continuation-use exit dummy)
1291                    (setf (block-last block) exit)))
1292                (setf (node-prev node) nil)
1293                nil)
1294               (t
1295                (aver (eq (block-start-cleanup block)
1296                          (block-end-cleanup block)))
1297                (unlink-blocks block next)
1298                (dolist (pred (block-pred block))
1299                  (change-block-successor pred block next))
1300                (remove-from-dfo block)
1301                (cond ((continuation-dest prev)
1302                       (setf (continuation-next prev) nil)
1303                       (setf (continuation-kind prev) :deleted-block-start))
1304                      (t
1305                       (delete-continuation prev)))
1306                (setf (node-prev node) nil)
1307                t)))))))
1308
1309 ;;; Return true if NODE has been deleted, false if it is still a valid
1310 ;;; part of IR1.
1311 (defun node-deleted (node)
1312   (declare (type node node))
1313   (let ((prev (node-prev node)))
1314     (not (and prev
1315               (not (eq (continuation-kind prev) :deleted))
1316               (let ((block (continuation-block prev)))
1317                 (and (block-component block)
1318                      (not (block-delete-p block))))))))
1319
1320 ;;; Delete all the blocks and functions in COMPONENT. We scan first
1321 ;;; marking the blocks as DELETE-P to prevent weird stuff from being
1322 ;;; triggered by deletion.
1323 (defun delete-component (component)
1324   (declare (type component component))
1325   (aver (null (component-new-functionals component)))
1326   (setf (component-kind component) :deleted)
1327   (do-blocks (block component)
1328     (setf (block-delete-p block) t))
1329   (dolist (fun (component-lambdas component))
1330     (setf (functional-kind fun) nil)
1331     (setf (functional-entry-fun fun) nil)
1332     (setf (leaf-refs fun) nil)
1333     (delete-functional fun))
1334   (do-blocks (block component)
1335     (delete-block block))
1336   (values))
1337
1338 ;;; Convert code of the form
1339 ;;;   (FOO ... (FUN ...) ...)
1340 ;;; to
1341 ;;;   (FOO ...    ...    ...).
1342 ;;; In other words, replace the function combination FUN by its
1343 ;;; arguments. If there are any problems with doing this, use GIVE-UP
1344 ;;; to blow out of whatever transform called this. Note, as the number
1345 ;;; of arguments changes, the transform must be prepared to return a
1346 ;;; lambda with a new lambda-list with the correct number of
1347 ;;; arguments.
1348 (defun extract-fun-args (cont fun num-args)
1349   #!+sb-doc
1350   "If CONT is a call to FUN with NUM-ARGS args, change those arguments
1351    to feed directly to the continuation-dest of CONT, which must be
1352    a combination."
1353   (declare (type continuation cont)
1354            (type symbol fun)
1355            (type index num-args))
1356   (let ((outside (continuation-dest cont))
1357         (inside (continuation-use cont)))
1358     (aver (combination-p outside))
1359     (unless (combination-p inside)
1360       (give-up-ir1-transform))
1361     (let ((inside-fun (combination-fun inside)))
1362       (unless (eq (continuation-fun-name inside-fun) fun)
1363         (give-up-ir1-transform))
1364       (let ((inside-args (combination-args inside)))
1365         (unless (= (length inside-args) num-args)
1366           (give-up-ir1-transform))
1367         (let* ((outside-args (combination-args outside))
1368                (arg-position (position cont outside-args))
1369                (before-args (subseq outside-args 0 arg-position))
1370                (after-args (subseq outside-args (1+ arg-position))))
1371           (dolist (arg inside-args)
1372             (setf (continuation-dest arg) outside)
1373             (flush-continuation-externally-checkable-type arg))
1374           (setf (combination-args inside) nil)
1375           (setf (combination-args outside)
1376                 (append before-args inside-args after-args))
1377           (change-ref-leaf (continuation-use inside-fun)
1378                            (find-free-fun 'list "???"))
1379           (setf (combination-kind inside)
1380                 (info :function :info 'list))
1381           (setf (node-derived-type inside) *wild-type*)
1382           (flush-dest cont)
1383           (values))))))
1384
1385 (defun flush-combination (combination)
1386   (declare (type combination combination))
1387   (flush-dest (combination-fun combination))
1388   (dolist (arg (combination-args combination))
1389     (flush-dest arg))
1390   (unlink-node combination)
1391   (values))
1392
1393 \f
1394 ;;;; leaf hackery
1395
1396 ;;; Change the LEAF that a REF refers to.
1397 (defun change-ref-leaf (ref leaf)
1398   (declare (type ref ref) (type leaf leaf))
1399   (unless (eq (ref-leaf ref) leaf)
1400     (push ref (leaf-refs leaf))
1401     (delete-ref ref)
1402     (setf (ref-leaf ref) leaf)
1403     (setf (leaf-ever-used leaf) t)
1404     (let* ((ltype (leaf-type leaf))
1405            (vltype (make-single-value-type ltype)))
1406       (if (let* ((cont (node-cont ref))
1407                  (dest (continuation-dest cont)))
1408             (and (basic-combination-p dest)
1409                  (eq cont (basic-combination-fun dest))
1410                  (csubtypep ltype (specifier-type 'function))))
1411           (setf (node-derived-type ref) vltype)
1412           (derive-node-type ref vltype)))
1413     (reoptimize-continuation (node-cont ref)))
1414   (values))
1415
1416 ;;; Change all REFS for OLD-LEAF to NEW-LEAF.
1417 (defun substitute-leaf (new-leaf old-leaf)
1418   (declare (type leaf new-leaf old-leaf))
1419   (dolist (ref (leaf-refs old-leaf))
1420     (change-ref-leaf ref new-leaf))
1421   (values))
1422
1423 ;;; like SUBSITUTE-LEAF, only there is a predicate on the REF to tell
1424 ;;; whether to substitute
1425 (defun substitute-leaf-if (test new-leaf old-leaf)
1426   (declare (type leaf new-leaf old-leaf) (type function test))
1427   (dolist (ref (leaf-refs old-leaf))
1428     (when (funcall test ref)
1429       (change-ref-leaf ref new-leaf)))
1430   (values))
1431
1432 ;;; Return a LEAF which represents the specified constant object. If
1433 ;;; the object is not in *CONSTANTS*, then we create a new constant
1434 ;;; LEAF and enter it.
1435 (defun find-constant (object)
1436   (if (typep object
1437              ;; FIXME: What is the significance of this test? ("things
1438              ;; that are worth uniquifying"?)
1439              '(or symbol number character instance))
1440       (or (gethash object *constants*)
1441           (setf (gethash object *constants*)
1442                 (make-constant :value object
1443                                :%source-name '.anonymous.
1444                                :type (ctype-of object)
1445                                :where-from :defined)))
1446       (make-constant :value object
1447                      :%source-name '.anonymous.
1448                      :type (ctype-of object)
1449                      :where-from :defined)))
1450 \f
1451 ;;; Return true if VAR would have to be closed over if environment
1452 ;;; analysis ran now (i.e. if there are any uses that have a different
1453 ;;; home lambda than VAR's home.)
1454 (defun closure-var-p (var)
1455   (declare (type lambda-var var))
1456   (let ((home (lambda-var-home var)))
1457     (cond ((eq (functional-kind home) :deleted)
1458            nil)
1459           (t (let ((home (lambda-home home)))
1460                (flet ((frob (l)
1461                         (find home l :key #'node-home-lambda
1462                               :test-not #'eq)))
1463                  (or (frob (leaf-refs var))
1464                      (frob (basic-var-sets var)))))))))
1465
1466 ;;; If there is a non-local exit noted in ENTRY's environment that
1467 ;;; exits to CONT in that entry, then return it, otherwise return NIL.
1468 (defun find-nlx-info (entry cont)
1469   (declare (type entry entry) (type continuation cont))
1470   (let ((entry-cleanup (entry-cleanup entry)))
1471     (dolist (nlx (physenv-nlx-info (node-physenv entry)) nil)
1472       (when (and (eq (nlx-info-continuation nlx) cont)
1473                  (eq (nlx-info-cleanup nlx) entry-cleanup))
1474         (return nlx)))))
1475 \f
1476 ;;;; functional hackery
1477
1478 (declaim (ftype (function (functional) clambda) main-entry))
1479 (defun main-entry (functional)
1480   (etypecase functional
1481     (clambda functional)
1482     (optional-dispatch
1483      (optional-dispatch-main-entry functional))))
1484
1485 ;;; RETURN true if FUNCTIONAL is a thing that can be treated like
1486 ;;; MV-BIND when it appears in an MV-CALL. All fixed arguments must be
1487 ;;; optional with null default and no SUPPLIED-P. There must be a
1488 ;;; &REST arg with no references.
1489 (declaim (ftype (function (functional) boolean) looks-like-an-mv-bind))
1490 (defun looks-like-an-mv-bind (functional)
1491   (and (optional-dispatch-p functional)
1492        (do ((arg (optional-dispatch-arglist functional) (cdr arg)))
1493            ((null arg) nil)
1494          (let ((info (lambda-var-arg-info (car arg))))
1495            (unless info (return nil))
1496            (case (arg-info-kind info)
1497              (:optional
1498               (when (or (arg-info-supplied-p info) (arg-info-default info))
1499                 (return nil)))
1500              (:rest
1501               (return (and (null (cdr arg)) (null (leaf-refs (car arg))))))
1502              (t
1503               (return nil)))))))
1504
1505 ;;; Return true if function is an external entry point. This is true
1506 ;;; of normal XEPs (:EXTERNAL kind) and also of top level lambdas
1507 ;;; (:TOPLEVEL kind.)
1508 (defun xep-p (fun)
1509   (declare (type functional fun))
1510   (not (null (member (functional-kind fun) '(:external :toplevel)))))
1511
1512 ;;; If CONT's only use is a non-notinline global function reference,
1513 ;;; then return the referenced symbol, otherwise NIL. If NOTINLINE-OK
1514 ;;; is true, then we don't care if the leaf is NOTINLINE.
1515 (defun continuation-fun-name (cont &optional notinline-ok)
1516   (declare (type continuation cont))
1517   (let ((use (continuation-use cont)))
1518     (if (ref-p use)
1519         (let ((leaf (ref-leaf use)))
1520           (if (and (global-var-p leaf)
1521                    (eq (global-var-kind leaf) :global-function)
1522                    (or (not (defined-fun-p leaf))
1523                        (not (eq (defined-fun-inlinep leaf) :notinline))
1524                        notinline-ok))
1525               (leaf-source-name leaf)
1526               nil))
1527         nil)))
1528
1529 ;;; Return the source name of a combination. (This is an idiom
1530 ;;; which was used in CMU CL. I gather it always works. -- WHN)
1531 (defun combination-fun-source-name (combination)
1532   (let ((ref (continuation-use (combination-fun combination))))
1533     (leaf-source-name (ref-leaf ref))))
1534
1535 ;;; Return the COMBINATION node that is the call to the LET FUN.
1536 (defun let-combination (fun)
1537   (declare (type clambda fun))
1538   (aver (functional-letlike-p fun))
1539   (continuation-dest (node-cont (first (leaf-refs fun)))))
1540
1541 ;;; Return the initial value continuation for a LET variable, or NIL
1542 ;;; if there is none.
1543 (defun let-var-initial-value (var)
1544   (declare (type lambda-var var))
1545   (let ((fun (lambda-var-home var)))
1546     (elt (combination-args (let-combination fun))
1547          (position-or-lose var (lambda-vars fun)))))
1548
1549 ;;; Return the LAMBDA that is called by the local CALL.
1550 (defun combination-lambda (call)
1551   (declare (type basic-combination call))
1552   (aver (eq (basic-combination-kind call) :local))
1553   (ref-leaf (continuation-use (basic-combination-fun call))))
1554
1555 (defvar *inline-expansion-limit* 200
1556   #!+sb-doc
1557   "an upper limit on the number of inline function calls that will be expanded
1558    in any given code object (single function or block compilation)")
1559
1560 ;;; Check whether NODE's component has exceeded its inline expansion
1561 ;;; limit, and warn if so, returning NIL.
1562 (defun inline-expansion-ok (node)
1563   (let ((expanded (incf (component-inline-expansions
1564                          (block-component
1565                           (node-block node))))))
1566     (cond ((> expanded *inline-expansion-limit*) nil)
1567           ((= expanded *inline-expansion-limit*)
1568            ;; FIXME: If the objective is to stop the recursive
1569            ;; expansion of inline functions, wouldn't it be more
1570            ;; correct to look back through surrounding expansions
1571            ;; (which are, I think, stored in the *CURRENT-PATH*, and
1572            ;; possibly stored elsewhere too) and suppress expansion
1573            ;; and print this warning when the function being proposed
1574            ;; for inline expansion is found there? (I don't like the
1575            ;; arbitrary numerical limit in principle, and I think
1576            ;; it'll be a nuisance in practice if we ever want the
1577            ;; compiler to be able to use WITH-COMPILATION-UNIT on
1578            ;; arbitrarily huge blocks of code. -- WHN)
1579            (let ((*compiler-error-context* node))
1580              (compiler-note "*INLINE-EXPANSION-LIMIT* (~W) was exceeded, ~
1581                              probably trying to~%  ~
1582                              inline a recursive function."
1583                             *inline-expansion-limit*))
1584            nil)
1585           (t t))))
1586 \f
1587 ;;;; careful call
1588
1589 ;;; Apply a function to some arguments, returning a list of the values
1590 ;;; resulting of the evaluation. If an error is signalled during the
1591 ;;; application, then we produce a warning message using WARN-FUN and
1592 ;;; return NIL as our second value to indicate this. NODE is used as
1593 ;;; the error context for any error message, and CONTEXT is a string
1594 ;;; that is spliced into the warning.
1595 (declaim (ftype (function ((or symbol function) list node function string)
1596                           (values list boolean))
1597                 careful-call))
1598 (defun careful-call (function args node warn-fun context)
1599   (values
1600    (multiple-value-list
1601     (handler-case (apply function args)
1602       (error (condition)
1603         (let ((*compiler-error-context* node))
1604           (funcall warn-fun "Lisp error during ~A:~%~A" context condition)
1605           (return-from careful-call (values nil nil))))))
1606    t))
1607
1608 ;;; Variations of SPECIFIER-TYPE for parsing possibly wrong
1609 ;;; specifiers.
1610 (macrolet
1611     ((deffrob (basic careful compiler transform)
1612        `(progn
1613           (defun ,careful (specifier)
1614             (handler-case (,basic specifier)
1615               (simple-error (condition)
1616                 (values nil (list* (simple-condition-format-control condition)
1617                                    (simple-condition-format-arguments condition))))))
1618           (defun ,compiler (specifier)
1619             (multiple-value-bind (type error-args) (,careful specifier)
1620               (or type
1621                   (apply #'compiler-error error-args))))
1622           (defun ,transform (specifier)
1623             (multiple-value-bind (type error-args) (,careful specifier)
1624               (or type
1625                   (apply #'give-up-ir1-transform
1626                          error-args)))))))
1627   (deffrob specifier-type careful-specifier-type compiler-specifier-type ir1-transform-specifier-type)
1628   (deffrob values-specifier-type careful-values-specifier-type compiler-values-specifier-type ir1-transform-values-specifier-type))
1629
1630 \f
1631 ;;;; utilities used at run-time for parsing &KEY args in IR1
1632
1633 ;;; This function is used by the result of PARSE-DEFTRANSFORM to find
1634 ;;; the continuation for the value of the &KEY argument KEY in the
1635 ;;; list of continuations ARGS. It returns the continuation if the
1636 ;;; keyword is present, or NIL otherwise. The legality and
1637 ;;; constantness of the keywords should already have been checked.
1638 (declaim (ftype (function (list keyword) (or continuation null))
1639                 find-keyword-continuation))
1640 (defun find-keyword-continuation (args key)
1641   (do ((arg args (cddr arg)))
1642       ((null arg) nil)
1643     (when (eq (continuation-value (first arg)) key)
1644       (return (second arg)))))
1645
1646 ;;; This function is used by the result of PARSE-DEFTRANSFORM to
1647 ;;; verify that alternating continuations in ARGS are constant and
1648 ;;; that there is an even number of args.
1649 (declaim (ftype (function (list) boolean) check-key-args-constant))
1650 (defun check-key-args-constant (args)
1651   (do ((arg args (cddr arg)))
1652       ((null arg) t)
1653     (unless (and (rest arg)
1654                  (constant-continuation-p (first arg)))
1655       (return nil))))
1656
1657 ;;; This function is used by the result of PARSE-DEFTRANSFORM to
1658 ;;; verify that the list of continuations ARGS is a well-formed &KEY
1659 ;;; arglist and that only keywords present in the list KEYS are
1660 ;;; supplied.
1661 (declaim (ftype (function (list list) boolean) check-transform-keys))
1662 (defun check-transform-keys (args keys)
1663   (and (check-key-args-constant args)
1664        (do ((arg args (cddr arg)))
1665            ((null arg) t)
1666          (unless (member (continuation-value (first arg)) keys)
1667            (return nil)))))
1668 \f
1669 ;;;; miscellaneous
1670
1671 ;;; Called by the expansion of the EVENT macro.
1672 (declaim (ftype (function (event-info (or node null)) *) %event))
1673 (defun %event (info node)
1674   (incf (event-info-count info))
1675   (when (and (>= (event-info-level info) *event-note-threshold*)
1676              (policy (or node *lexenv*)
1677                      (= inhibit-warnings 0)))
1678     (let ((*compiler-error-context* node))
1679       (compiler-note (event-info-description info))))
1680
1681   (let ((action (event-info-action info)))
1682     (when action (funcall action node))))
1683
1684 ;;;
1685 (defun make-cast (value type policy)
1686   (declare (type continuation value)
1687            (type ctype type)
1688            (type policy policy))
1689   (%make-cast :asserted-type type
1690               :type-to-check (maybe-weaken-check type policy)
1691               :value value
1692               :derived-type (coerce-to-values type)))
1693
1694 (defun cast-type-check (cast)
1695   (declare (type cast cast))
1696   (when (cast-reoptimize cast)
1697     (ir1-optimize-cast cast t))
1698   (cast-%type-check cast))
1699
1700 (defun note-single-valuified-continuation (cont)
1701   (declare (type continuation cont))
1702   (let ((use (continuation-use cont)))
1703     (cond ((ref-p use)
1704            (let ((leaf (ref-leaf use)))
1705              (when (and (lambda-var-p leaf)
1706                         (null (rest (leaf-refs leaf))))
1707                (reoptimize-lambda-var leaf))))
1708           ((or (null use) (combination-p use))
1709            (dolist (node (find-uses cont))
1710              (setf (node-reoptimize node) t)
1711              (setf (block-reoptimize (node-block node)) t)
1712              (setf (component-reoptimize (node-component node)) t))))))