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