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