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