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