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