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