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