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