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