Initial revision
[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
15 (file-comment
16   "$Header$")
17 \f
18 ;;;; cleanup hackery
19
20 ;;; Return the innermost cleanup enclosing Node, or NIL if there is none in
21 ;;; its function. If Node has no cleanup, but is in a let, then we must still
22 ;;; check the environment that the call is in.
23 (defun node-enclosing-cleanup (node)
24   (declare (type node node))
25   (do ((lexenv (node-lexenv node)
26                (lambda-call-lexenv (lexenv-lambda lexenv))))
27       ((null lexenv) nil)
28     (let ((cup (lexenv-cleanup lexenv)))
29       (when cup (return cup)))))
30
31 ;;; Convert the Form in a block inserted between Block1 and Block2 as an
32 ;;; implicit MV-Prog1. The inserted block is returned. Node is used for IR1
33 ;;; context when converting the form. Note that the block is not assigned a
34 ;;; number, and is linked into the DFO at the beginning. We indicate that we
35 ;;; have trashed the DFO by setting Component-Reanalyze. If Cleanup is
36 ;;; supplied, then convert with that cleanup.
37 (defun insert-cleanup-code (block1 block2 node form &optional cleanup)
38   (declare (type cblock block1 block2) (type node node)
39            (type (or cleanup null) cleanup))
40   (setf (component-reanalyze (block-component block1)) t)
41   (with-ir1-environment node
42     (let* ((start (make-continuation))
43            (block (continuation-starts-block start))
44            (cont (make-continuation))
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 cont form)
51       (setf (block-last block) (continuation-use cont))
52       block)))
53 \f
54 ;;;; continuation use hacking
55
56 ;;; Return a list of all the nodes which use Cont.
57 (declaim (ftype (function (continuation) list) find-uses))
58 (defun find-uses (cont)
59   (ecase (continuation-kind cont)
60     ((:block-start :deleted-block-start)
61      (block-start-uses (continuation-block cont)))
62     (:inside-block (list (continuation-use cont)))
63     (:unused nil)
64     (:deleted nil)))
65
66 ;;; Update continuation use information so that Node is no longer a
67 ;;; use of its Cont. If the old continuation doesn't start its block,
68 ;;; then we don't update the Block-Start-Uses, since it will be
69 ;;; deleted when we are done.
70 ;;;
71 ;;; Note: if you call this function, you may have to do a
72 ;;; REOPTIMIZE-CONTINUATION to inform IR1 optimization that something
73 ;;; has changed.
74 (declaim (ftype (function (node) (values)) delete-continuation-use))
75 (defun delete-continuation-use (node)
76   (let* ((cont (node-cont node))
77          (block (continuation-block cont)))
78     (ecase (continuation-kind cont)
79       (:deleted)
80       ((:block-start :deleted-block-start)
81        (let ((uses (delete node (block-start-uses block))))
82          (setf (block-start-uses block) uses)
83          (setf (continuation-use cont)
84                (if (cdr uses) nil (car uses)))))
85       (:inside-block
86        (setf (continuation-kind cont) :unused)
87        (setf (continuation-block cont) nil)
88        (setf (continuation-use cont) nil)
89        (setf (continuation-next cont) nil)))
90     (setf (node-cont node) nil))
91   (values))
92
93 ;;; Update continuation use information so that Node uses Cont. If
94 ;;; Cont is :Unused, then we set its block to Node's Node-Block (which
95 ;;; must be set.)
96 ;;;
97 ;;; Note: if you call this function, you may have to do a
98 ;;; REOPTIMIZE-CONTINUATION to inform IR1 optimization that something
99 ;;; has changed.
100 (declaim (ftype (function (node continuation) (values)) add-continuation-use))
101 (defun add-continuation-use (node cont)
102   (assert (not (node-cont node)))
103   (let ((block (continuation-block cont)))
104     (ecase (continuation-kind cont)
105       (:deleted)
106       (:unused
107        (assert (not block))
108        (let ((block (node-block node)))
109          (assert block)
110          (setf (continuation-block cont) block))
111        (setf (continuation-kind cont) :inside-block)
112        (setf (continuation-use cont) node))
113       ((:block-start :deleted-block-start)
114        (let ((uses (cons node (block-start-uses block))))
115          (setf (block-start-uses block) uses)
116          (setf (continuation-use cont)
117                (if (cdr uses) nil (car uses)))))))
118   (setf (node-cont node) cont)
119   (values))
120
121 ;;; Return true if Cont is the Node-Cont for Node and Cont is transferred to
122 ;;; immediately after the evaluation of Node.
123 (defun immediately-used-p (cont node)
124   (declare (type continuation cont) (type node node))
125   (and (eq (node-cont node) cont)
126        (not (eq (continuation-kind cont) :deleted))
127        (let ((cblock (continuation-block cont))
128              (nblock (node-block node)))
129          (or (eq cblock nblock)
130              (let ((succ (block-succ nblock)))
131                (and (= (length succ) 1)
132                     (eq (first succ) cblock)))))))
133 \f
134 ;;;; continuation substitution
135
136 ;;; In Old's Dest, replace Old with New. New's Dest must initially be NIL.
137 ;;; When we are done, we call Flush-Dest on Old to clear its Dest and to note
138 ;;; potential optimization opportunities.
139 (defun substitute-continuation (new old)
140   (declare (type continuation old new))
141   (assert (not (continuation-dest new)))
142   (let ((dest (continuation-dest old)))
143     (etypecase dest
144       ((or ref bind))
145       (cif (setf (if-test dest) new))
146       (cset (setf (set-value dest) new))
147       (creturn (setf (return-result dest) new))
148       (exit (setf (exit-value dest) new))
149       (basic-combination
150        (if (eq old (basic-combination-fun dest))
151            (setf (basic-combination-fun dest) new)
152            (setf (basic-combination-args dest)
153                  (nsubst new old (basic-combination-args dest))))))
154
155     (flush-dest old)
156     (setf (continuation-dest new) dest))
157   (values))
158
159 ;;; Replace all uses of Old with uses of New, where New has an arbitary
160 ;;; number of uses. If New will end up with more than one use, then we must
161 ;;; arrange for it to start a block if it doesn't already.
162 (defun substitute-continuation-uses (new old)
163   (declare (type continuation old new))
164   (unless (and (eq (continuation-kind new) :unused)
165                (eq (continuation-kind old) :inside-block))
166     (ensure-block-start new))
167
168   (do-uses (node old)
169     (delete-continuation-use node)
170     (add-continuation-use node new))
171
172   (reoptimize-continuation new)
173   (values))
174 \f
175 ;;;; block starting/creation
176
177 ;;; Return the block that Continuation is the start of, making a block if
178 ;;; necessary. This function is called by IR1 translators which may cause a
179 ;;; continuation to be used more than once. Every continuation which may be
180 ;;; used more than once must start a block by the time that anyone does a
181 ;;; Use-Continuation on it.
182 ;;;
183 ;;; We also throw the block into the next/prev list for the
184 ;;; *current-component* so that we keep track of which blocks we have made.
185 (defun continuation-starts-block (cont)
186   (declare (type continuation cont))
187   (ecase (continuation-kind cont)
188     (:unused
189      (assert (not (continuation-block cont)))
190      (let* ((head (component-head *current-component*))
191             (next (block-next head))
192             (new-block (make-block cont)))
193        (setf (block-next new-block) next)
194        (setf (block-prev new-block) head)
195        (setf (block-prev next) new-block)
196        (setf (block-next head) new-block)
197        (setf (continuation-block cont) new-block)
198        (setf (continuation-use cont) nil)
199        (setf (continuation-kind cont) :block-start)
200        new-block))
201     (:block-start
202      (continuation-block cont))))
203
204 ;;; Ensure that Cont is the start of a block (or deleted) so that the use
205 ;;; set can be freely manipulated.
206 ;;; -- If the continuation is :Unused or is :Inside-Block and the Cont of Last
207 ;;;    in its block, then we make it the start of a new deleted block.
208 ;;; -- If the continuation is :Inside-Block inside a block, then we split the
209 ;;;    block using Node-Ends-Block, which makes the continuation be a
210 ;;;    :Block-Start.
211 (defun ensure-block-start (cont)
212   (declare (type continuation cont))
213   (let ((kind (continuation-kind cont)))
214     (ecase kind
215       ((:deleted :block-start :deleted-block-start))
216       ((:unused :inside-block)
217        (let ((block (continuation-block cont)))
218          (cond ((or (eq kind :unused)
219                     (eq (node-cont (block-last block)) cont))
220                 (setf (continuation-block cont)
221                       (make-block-key :start cont
222                                       :component nil
223                                       :start-uses (find-uses cont)))
224                 (setf (continuation-kind cont) :deleted-block-start))
225                (t
226                 (node-ends-block (continuation-use cont))))))))
227   (values))
228 \f
229 ;;;; miscellaneous shorthand functions
230
231 ;;; Return the home (i.e. enclosing non-let) lambda for Node. Since the
232 ;;; LEXENV-LAMBDA may be deleted, we must chain up the LAMBDA-CALL-LEXENV
233 ;;; thread until we find a lambda that isn't deleted, and then return its home.
234 (declaim (maybe-inline node-home-lambda))
235 (defun node-home-lambda (node)
236   (declare (type node node))
237   (do ((fun (lexenv-lambda (node-lexenv node))
238             (lexenv-lambda (lambda-call-lexenv fun))))
239       ((not (eq (functional-kind fun) :deleted))
240        (lambda-home fun))
241     (when (eq (lambda-home fun) fun)
242       (return fun))))
243
244 #!-sb-fluid (declaim (inline node-block node-tlf-number))
245 (declaim (maybe-inline node-environment))
246 (defun node-block (node)
247   (declare (type node node))
248   (the cblock (continuation-block (node-prev node))))
249 (defun node-environment (node)
250   (declare (type node node))
251   #!-sb-fluid (declare (inline node-home-lambda))
252   (the environment (lambda-environment (node-home-lambda node))))
253
254 ;;; Return the enclosing cleanup for environment of the first or last node
255 ;;; in Block.
256 (defun block-start-cleanup (block)
257   (declare (type cblock block))
258   (node-enclosing-cleanup (continuation-next (block-start block))))
259 (defun block-end-cleanup (block)
260   (declare (type cblock block))
261   (node-enclosing-cleanup (block-last block)))
262
263 ;;; Return the non-let lambda that holds Block's code.
264 (defun block-home-lambda (block)
265   (declare (type cblock block))
266   #!-sb-fluid (declare (inline node-home-lambda))
267   (node-home-lambda (block-last block)))
268
269 ;;; Return the IR1 environment for Block.
270 (defun block-environment (block)
271   (declare (type cblock block))
272   #!-sb-fluid (declare (inline node-home-lambda))
273   (lambda-environment (node-home-lambda (block-last block))))
274
275 ;;; Return the Top Level Form number of path, i.e. the ordinal number of
276 ;;; its orignal source's top-level form in its compilation unit.
277 (defun source-path-tlf-number (path)
278   (declare (list path))
279   (car (last path)))
280
281 ;;; Return the (reversed) list for the path in the orignal source (with the
282 ;;; TLF number last.)
283 (defun source-path-original-source (path)
284   (declare (list path) (inline member))
285   (cddr (member 'original-source-start path :test #'eq)))
286
287 ;;; Return the Form Number of Path's orignal source inside the Top Level
288 ;;; Form that contains it. This is determined by the order that we walk the
289 ;;; subforms of the top level source form.
290 (defun source-path-form-number (path)
291   (declare (list path) (inline member))
292   (cadr (member 'original-source-start path :test #'eq)))
293
294 ;;; Return a list of all the enclosing forms not in the original source that
295 ;;; converted to get to this form, with the immediate source for node at the
296 ;;; start of the list.
297 (defun source-path-forms (path)
298   (subseq path 0 (position 'original-source-start path)))
299
300 ;;; Return the innermost source form for Node.
301 (defun node-source-form (node)
302   (declare (type node node))
303   (let* ((path (node-source-path node))
304          (forms (source-path-forms path)))
305     (if forms
306         (first forms)
307         (values (find-original-source path)))))
308
309 ;;; Return NODE-SOURCE-FORM, T if continuation has a single use, otherwise
310 ;;; NIL, NIL.
311 (defun continuation-source (cont)
312   (let ((use (continuation-use cont)))
313     (if use
314         (values (node-source-form use) t)
315         (values nil nil))))
316 \f
317 ;;; Return a new LEXENV just like Default except for the specified slot
318 ;;; values. Values for the alist slots are NCONC'ed to the beginning of the
319 ;;; current value, rather than replacing it entirely.
320 (defun make-lexenv (&key (default *lexenv*)
321                          functions variables blocks tags type-restrictions
322                          options
323                          (lambda (lexenv-lambda default))
324                          (cleanup (lexenv-cleanup default))
325                          (cookie (lexenv-cookie default))
326                          (interface-cookie (lexenv-interface-cookie default)))
327   (macrolet ((frob (var slot)
328                `(let ((old (,slot default)))
329                   (if ,var
330                       (nconc ,var old)
331                       old))))
332     (internal-make-lexenv
333      (frob functions lexenv-functions)
334      (frob variables lexenv-variables)
335      (frob blocks lexenv-blocks)
336      (frob tags lexenv-tags)
337      (frob type-restrictions lexenv-type-restrictions)
338      lambda cleanup cookie interface-cookie
339      (frob options lexenv-options))))
340
341 ;;; Return a cookie that defaults any unsupplied optimize qualities in the
342 ;;; Interface-Cookie with the corresponding ones from the Cookie.
343 (defun make-interface-cookie (lexenv)
344   (declare (type lexenv lexenv))
345   (let ((icookie (lexenv-interface-cookie lexenv))
346         (cookie (lexenv-cookie lexenv)))
347     (make-cookie
348      :speed (or (cookie-speed icookie) (cookie-speed cookie))
349      :space (or (cookie-space icookie) (cookie-space cookie))
350      :safety (or (cookie-safety icookie) (cookie-safety cookie))
351      :cspeed (or (cookie-cspeed icookie) (cookie-cspeed cookie))
352      :brevity (or (cookie-brevity icookie) (cookie-brevity cookie))
353      :debug (or (cookie-debug icookie) (cookie-debug cookie)))))
354 \f
355 ;;;; flow/DFO/component hackery
356
357 ;;; Join Block1 and Block2.
358 #!-sb-fluid (declaim (inline link-blocks))
359 (defun link-blocks (block1 block2)
360   (declare (type cblock block1 block2))
361   (setf (block-succ block1)
362         (if (block-succ block1)
363             (%link-blocks block1 block2)
364             (list block2)))
365   (push block1 (block-pred block2))
366   (values))
367 (defun %link-blocks (block1 block2)
368   (declare (type cblock block1 block2) (inline member))
369   (let ((succ1 (block-succ block1)))
370     (assert (not (member block2 succ1 :test #'eq)))
371     (cons block2 succ1)))
372
373 ;;; Like LINK-BLOCKS, but we separate BLOCK1 and BLOCK2. If this leaves a
374 ;;; successor with a single predecessor that ends in an IF, then set
375 ;;; BLOCK-TEST-MODIFIED so that any test constraint will now be able to be
376 ;;; propagated to the successor.
377 (defun unlink-blocks (block1 block2)
378   (declare (type cblock block1 block2))
379   (let ((succ1 (block-succ block1)))
380     (if (eq block2 (car succ1))
381         (setf (block-succ block1) (cdr succ1))
382         (do ((succ (cdr succ1) (cdr succ))
383              (prev succ1 succ))
384             ((eq (car succ) block2)
385              (setf (cdr prev) (cdr succ)))
386           (assert succ))))
387
388   (let ((new-pred (delq block1 (block-pred block2))))
389     (setf (block-pred block2) new-pred)
390     (when (and new-pred (null (rest new-pred)))
391       (let ((pred-block (first new-pred)))
392         (when (if-p (block-last pred-block))
393           (setf (block-test-modified pred-block) t)))))
394   (values))
395
396 ;;; Swing the succ/pred link between Block and Old to be between Block and
397 ;;; New. If Block ends in an IF, then we have to fix up the
398 ;;; consequent/alternative blocks to point to New. We also set
399 ;;; BLOCK-TEST-MODIFIED so that any test constraint will be applied to the new
400 ;;; successor.
401 (defun change-block-successor (block old new)
402   (declare (type cblock new old block) (inline member))
403   (unlink-blocks block old)
404   (let ((last (block-last block))
405         (comp (block-component block)))
406     (setf (component-reanalyze comp) t)
407     (typecase last
408       (cif
409        (setf (block-test-modified block) t)
410        (let* ((succ-left (block-succ block))
411               (new (if (and (eq new (component-tail comp))
412                             succ-left)
413                        (first succ-left)
414                        new)))
415          (unless (member new succ-left :test #'eq)
416            (link-blocks block new))
417          (macrolet ((frob (slot)
418                       `(when (eq (,slot last) old)
419                          (setf (,slot last) new))))
420            (frob if-consequent)
421            (frob if-alternative))))
422       (t
423        (unless (member new (block-succ block) :test #'eq)
424          (link-blocks block new)))))
425
426   (values))
427
428 ;;; Unlink a block from the next/prev chain. We also null out the
429 ;;; Component.
430 (declaim (ftype (function (cblock) (values)) remove-from-dfo))
431 #!-sb-fluid (declaim (inline remove-from-dfo))
432 (defun remove-from-dfo (block)
433   (let ((next (block-next block))
434         (prev (block-prev block)))
435     (setf (block-component block) nil)
436     (setf (block-next prev) next)
437     (setf (block-prev next) prev))
438   (values))
439
440 ;;; Add Block to the next/prev chain following After. We also set the
441 ;;; Component to be the same as for After.
442 #!-sb-fluid (declaim (inline add-to-dfo))
443 (defun add-to-dfo (block after)
444   (declare (type cblock block after))
445   (let ((next (block-next after))
446         (comp (block-component after)))
447     (assert (not (eq (component-kind comp) :deleted)))
448     (setf (block-component block) comp)
449     (setf (block-next after) block)
450     (setf (block-prev block) after)
451     (setf (block-next block) next)
452     (setf (block-prev next) block))
453   (values))
454
455 ;;; Set the Flag for all the blocks in Component to NIL, except for the head
456 ;;; and tail which are set to T.
457 (declaim (ftype (function (component) (values)) clear-flags))
458 (defun clear-flags (component)
459   (let ((head (component-head component))
460         (tail (component-tail component)))
461     (setf (block-flag head) t)
462     (setf (block-flag tail) t)
463     (do-blocks (block component)
464       (setf (block-flag block) nil)))
465   (values))
466
467 ;;; Make a component with no blocks in it. The Block-Flag is initially
468 ;;; true in the head and tail blocks.
469 (declaim (ftype (function nil component) make-empty-component))
470 (defun make-empty-component ()
471   (let* ((head (make-block-key :start nil :component nil))
472          (tail (make-block-key :start nil :component nil))
473          (res (make-component :head head :tail tail)))
474     (setf (block-flag head) t)
475     (setf (block-flag tail) t)
476     (setf (block-component head) res)
477     (setf (block-component tail) res)
478     (setf (block-next head) tail)
479     (setf (block-prev tail) head)
480     res))
481
482 ;;; Makes Node the Last node in its block, splitting the block if necessary.
483 ;;; The new block is added to the DFO immediately following Node's block.
484 (defun node-ends-block (node)
485   (declare (type node node))
486   (let* ((block (node-block node))
487          (start (node-cont node))
488          (last (block-last block))
489          (last-cont (node-cont last)))
490     (unless (eq last node)
491       (assert (and (eq (continuation-kind start) :inside-block)
492                    (not (block-delete-p block))))
493       (let* ((succ (block-succ block))
494              (new-block
495               (make-block-key :start start
496                               :component (block-component block)
497                               :start-uses (list (continuation-use start))
498                               :succ succ :last last)))
499         (setf (continuation-kind start) :block-start)
500         (dolist (b succ)
501           (setf (block-pred b)
502                 (cons new-block (remove block (block-pred b)))))
503         (setf (block-succ block) ())
504         (setf (block-last block) node)
505         (link-blocks block new-block)
506         (add-to-dfo new-block block)
507         (setf (component-reanalyze (block-component block)) t)
508         
509         (do ((cont start (node-cont (continuation-next cont))))
510             ((eq cont last-cont)
511              (when (eq (continuation-kind last-cont) :inside-block)
512                (setf (continuation-block last-cont) new-block)))
513           (setf (continuation-block cont) new-block))
514
515         (setf (block-type-asserted block) t)
516         (setf (block-test-modified block) t))))
517
518   (values))
519 \f
520 ;;;; deleting stuff
521
522 ;;; Deal with deleting the last (read) reference to a lambda-var. We
523 ;;; iterate over all local calls flushing the corresponding argument, allowing
524 ;;; the computation of the argument to be deleted. We also mark the let for
525 ;;; reoptimization, since it may be that we have deleted the last variable.
526 ;;;
527 ;;; The lambda-var may still have some sets, but this doesn't cause too much
528 ;;; difficulty, since we can efficiently implement write-only variables. We
529 ;;; iterate over the sets, marking their blocks for dead code flushing, since
530 ;;; we can delete sets whose value is unused.
531 (defun delete-lambda-var (leaf)
532   (declare (type lambda-var leaf))
533   (let* ((fun (lambda-var-home leaf))
534          (n (position leaf (lambda-vars fun))))
535     (dolist (ref (leaf-refs fun))
536       (let* ((cont (node-cont ref))
537              (dest (continuation-dest cont)))
538         (when (and (combination-p dest)
539                    (eq (basic-combination-fun dest) cont)
540                    (eq (basic-combination-kind dest) :local))
541           (let* ((args (basic-combination-args dest))
542                  (arg (elt args n)))
543             (reoptimize-continuation arg)
544             (flush-dest arg)
545             (setf (elt args n) nil))))))
546
547   (dolist (set (lambda-var-sets leaf))
548     (setf (block-flush-p (node-block set)) t))
549
550   (values))
551
552 ;;; Note that something interesting has happened to Var. We only deal with
553 ;;; LET variables, marking the corresponding initial value arg as needing to be
554 ;;; reoptimized.
555 (defun reoptimize-lambda-var (var)
556   (declare (type lambda-var var))
557   (let ((fun (lambda-var-home var)))
558     (when (and (eq (functional-kind fun) :let)
559                (leaf-refs var))
560       (do ((args (basic-combination-args
561                   (continuation-dest
562                    (node-cont
563                     (first (leaf-refs fun)))))
564                  (cdr args))
565            (vars (lambda-vars fun) (cdr vars)))
566           ((eq (car vars) var)
567            (reoptimize-continuation (car args))))))
568   (values))
569
570 ;;; This function deletes functions that have no references. This need only
571 ;;; be called on functions that never had any references, since otherwise
572 ;;; DELETE-REF will handle the deletion.
573 (defun delete-functional (fun)
574   (assert (and (null (leaf-refs fun))
575                (not (functional-entry-function fun))))
576   (etypecase fun
577     (optional-dispatch (delete-optional-dispatch fun))
578     (clambda (delete-lambda fun)))
579   (values))
580
581 ;;; Deal with deleting the last reference to a lambda. Since there is only
582 ;;; one way into a lambda, deleting the last reference to a lambda ensures that
583 ;;; there is no way to reach any of the code in it. So we just set the
584 ;;; Functional-Kind for Fun and its Lets to :Deleted, causing IR1 optimization
585 ;;; to delete blocks in that lambda.
586 ;;;
587 ;;; If the function isn't a Let, we unlink the function head and tail from
588 ;;; the component head and tail to indicate that the code is unreachable. We
589 ;;; also delete the function from Component-Lambdas (it won't be there before
590 ;;; local call analysis, but no matter.)  If the lambda was never referenced,
591 ;;; we give a note.
592 ;;;
593 ;;; If the lambda is an XEP, then we null out the Entry-Function in its
594 ;;; Entry-Function so that people will know that it is not an entry point
595 ;;; anymore.
596 (defun delete-lambda (leaf)
597   (declare (type clambda leaf))
598   (let ((kind (functional-kind leaf))
599         (bind (lambda-bind leaf)))
600     (assert (not (member kind '(:deleted :optional :top-level))))
601     (setf (functional-kind leaf) :deleted)
602     (setf (lambda-bind leaf) nil)
603     (dolist (let (lambda-lets leaf))
604       (setf (lambda-bind let) nil)
605       (setf (functional-kind let) :deleted))
606
607     (if (member kind '(:let :mv-let :assignment))
608         (let ((home (lambda-home leaf)))
609           (setf (lambda-lets home) (delete leaf (lambda-lets home))))
610         (let* ((bind-block (node-block bind))
611                (component (block-component bind-block))
612                (return (lambda-return leaf)))
613           (assert (null (leaf-refs leaf)))
614           (unless (leaf-ever-used leaf)
615             (let ((*compiler-error-context* bind))
616               (compiler-note "deleting unused function~:[.~;~:*~%  ~S~]"
617                              (leaf-name leaf))))
618           (unlink-blocks (component-head component) bind-block)
619           (when return
620             (unlink-blocks (node-block return) (component-tail component)))
621           (setf (component-reanalyze component) t)
622           (let ((tails (lambda-tail-set leaf)))
623             (setf (tail-set-functions tails)
624                   (delete leaf (tail-set-functions tails)))
625             (setf (lambda-tail-set leaf) nil))
626           (setf (component-lambdas component)
627                 (delete leaf (component-lambdas component)))))
628
629     (when (eq kind :external)
630       (let ((fun (functional-entry-function leaf)))
631         (setf (functional-entry-function fun) nil)
632         (when (optional-dispatch-p fun)
633           (delete-optional-dispatch fun)))))
634
635   (values))
636
637 ;;; Deal with deleting the last reference to an Optional-Dispatch. We have
638 ;;; to be a bit more careful than with lambdas, since Delete-Ref is used both
639 ;;; before and after local call analysis. Afterward, all references to
640 ;;; still-existing optional-dispatches have been moved to the XEP, leaving it
641 ;;; with no references at all. So we look at the XEP to see whether an
642 ;;; optional-dispatch is still really being used. But before local call
643 ;;; analysis, there are no XEPs, and all references are direct.
644 ;;;
645 ;;; When we do delete the optional-dispatch, we grovel all of its
646 ;;; entry-points, making them be normal lambdas, and then deleting the ones
647 ;;; with no references. This deletes any e-p lambdas that were either never
648 ;;; referenced, or couldn't be deleted when the last deference was deleted (due
649 ;;; to their :OPTIONAL kind.)
650 ;;;
651 ;;; Note that the last optional ep may alias the main entry, so when we process
652 ;;; the main entry, its kind may have been changed to NIL or even converted to
653 ;;; a let.
654 (defun delete-optional-dispatch (leaf)
655   (declare (type optional-dispatch leaf))
656   (let ((entry (functional-entry-function leaf)))
657     (unless (and entry (leaf-refs entry))
658       (assert (or (not entry) (eq (functional-kind entry) :deleted)))
659       (setf (functional-kind leaf) :deleted)
660
661       (flet ((frob (fun)
662                (unless (eq (functional-kind fun) :deleted)
663                  (assert (eq (functional-kind fun) :optional))
664                  (setf (functional-kind fun) nil)
665                  (let ((refs (leaf-refs fun)))
666                    (cond ((null refs)
667                           (delete-lambda fun))
668                          ((null (rest refs))
669                           (or (maybe-let-convert fun)
670                               (maybe-convert-to-assignment fun)))
671                          (t
672                           (maybe-convert-to-assignment fun)))))))
673         
674         (dolist (ep (optional-dispatch-entry-points leaf))
675           (frob ep))
676         (when (optional-dispatch-more-entry leaf)
677           (frob (optional-dispatch-more-entry leaf)))
678         (let ((main (optional-dispatch-main-entry leaf)))
679           (when (eq (functional-kind main) :optional)
680             (frob main))))))
681
682   (values))
683
684 ;;; Do stuff to delete the semantic attachments of a Ref node. When this
685 ;;; leaves zero or one reference, we do a type dispatch off of the leaf to
686 ;;; determine if a special action is appropriate.
687 (defun delete-ref (ref)
688   (declare (type ref ref))
689   (let* ((leaf (ref-leaf ref))
690          (refs (delete ref (leaf-refs leaf))))
691     (setf (leaf-refs leaf) refs)
692
693     (cond ((null refs)
694            (typecase leaf
695              (lambda-var (delete-lambda-var leaf))
696              (clambda
697               (ecase (functional-kind leaf)
698                 ((nil :let :mv-let :assignment :escape :cleanup)
699                  (assert (not (functional-entry-function leaf)))
700                  (delete-lambda leaf))
701                 (:external
702                  (delete-lambda leaf))
703                 ((:deleted :optional))))
704              (optional-dispatch
705               (unless (eq (functional-kind leaf) :deleted)
706                 (delete-optional-dispatch leaf)))))
707           ((null (rest refs))
708            (typecase leaf
709              (clambda (or (maybe-let-convert leaf)
710                           (maybe-convert-to-assignment leaf)))
711              (lambda-var (reoptimize-lambda-var leaf))))
712           (t
713            (typecase leaf
714              (clambda (maybe-convert-to-assignment leaf))))))
715
716   (values))
717
718 ;;; This function is called by people who delete nodes; it provides a way to
719 ;;; indicate that the value of a continuation is no longer used. We null out
720 ;;; the Continuation-Dest, set Flush-P in the blocks containing uses of Cont
721 ;;; and set Component-Reoptimize. If the Prev of the use is deleted, then we
722 ;;; blow off reoptimization.
723 ;;;
724 ;;; If the continuation is :Deleted, then we don't do anything, since all
725 ;;; semantics have already been flushed. :Deleted-Block-Start start
726 ;;; continuations are treated just like :Block-Start; it is possible that the
727 ;;; continuation may be given a new dest (e.g. by SUBSTITUTE-CONTINUATION), so
728 ;;; we don't want to delete it.
729 (defun flush-dest (cont)
730   (declare (type continuation cont))
731
732   (unless (eq (continuation-kind cont) :deleted)
733     (assert (continuation-dest cont))
734     (setf (continuation-dest cont) nil)
735     (do-uses (use cont)
736       (let ((prev (node-prev use)))
737         (unless (eq (continuation-kind prev) :deleted)
738           (let ((block (continuation-block prev)))
739             (setf (component-reoptimize (block-component block)) t)
740             (setf (block-attributep (block-flags block) flush-p type-asserted)
741                   t))))))
742
743   (setf (continuation-%type-check cont) nil)
744
745   (values))
746
747 ;;; Do a graph walk backward from Block, marking all predecessor blocks with
748 ;;; the DELETE-P flag.
749 (defun mark-for-deletion (block)
750   (declare (type cblock block))
751   (unless (block-delete-p block)
752     (setf (block-delete-p block) t)
753     (setf (component-reanalyze (block-component block)) t)
754     (dolist (pred (block-pred block))
755       (mark-for-deletion pred)))
756   (values))
757
758 ;;;    Delete Cont, eliminating both control and value semantics. We set
759 ;;; FLUSH-P and COMPONENT-REOPTIMIZE similarly to in FLUSH-DEST. Here we must
760 ;;; get the component from the use block, since the continuation may be a
761 ;;; :DELETED-BLOCK-START.
762 ;;;
763 ;;;    If Cont has DEST, then it must be the case that the DEST is unreachable,
764 ;;; since we can't compute the value desired. In this case, we call
765 ;;; MARK-FOR-DELETION to cause the DEST block and its predecessors to tell
766 ;;; people to ignore them, and to cause them to be deleted eventually.
767 (defun delete-continuation (cont)
768   (declare (type continuation cont))
769   (assert (not (eq (continuation-kind cont) :deleted)))
770
771   (do-uses (use cont)
772     (let ((prev (node-prev use)))
773       (unless (eq (continuation-kind prev) :deleted)
774         (let ((block (continuation-block prev)))
775           (setf (block-attributep (block-flags block) flush-p type-asserted) t)
776           (setf (component-reoptimize (block-component block)) t)))))
777
778   (let ((dest (continuation-dest cont)))
779     (when dest
780       (let ((prev (node-prev dest)))
781         (when (and prev
782                    (not (eq (continuation-kind prev) :deleted)))
783           (let ((block (continuation-block prev)))
784             (unless (block-delete-p block)
785               (mark-for-deletion block)))))))
786
787   (setf (continuation-kind cont) :deleted)
788   (setf (continuation-dest cont) nil)
789   (setf (continuation-next cont) nil)
790   (setf (continuation-asserted-type cont) *empty-type*)
791   (setf (continuation-%derived-type cont) *empty-type*)
792   (setf (continuation-use cont) nil)
793   (setf (continuation-block cont) nil)
794   (setf (continuation-reoptimize cont) nil)
795   (setf (continuation-%type-check cont) nil)
796   (setf (continuation-info cont) nil)
797
798   (values))
799
800 ;;; This function does what is necessary to eliminate the code in it from
801 ;;; the IR1 representation. This involves unlinking it from its predecessors
802 ;;; and successors and deleting various node-specific semantic information.
803 ;;;
804 ;;; We mark the Start as has having no next and remove the last node from
805 ;;; its Cont's uses. We also flush the DEST for all continuations whose values
806 ;;; are received by nodes in the block.
807 (defun delete-block (block)
808   (declare (type cblock block))
809   (assert (block-component block) () "Block is already deleted.")
810   (note-block-deletion block)
811   (setf (block-delete-p block) t)
812
813   (let* ((last (block-last block))
814          (cont (node-cont last)))
815     (delete-continuation-use last)
816     (if (eq (continuation-kind cont) :unused)
817         (delete-continuation cont)
818         (reoptimize-continuation cont)))
819
820   (dolist (b (block-pred block))
821     (unlink-blocks b block))
822   (dolist (b (block-succ block))
823     (unlink-blocks block b))
824
825   (do-nodes (node cont block)
826     (typecase node
827       (ref (delete-ref node))
828       (cif
829        (flush-dest (if-test node)))
830       ;; The next two cases serve to maintain the invariant that a LET always
831       ;; has a well-formed COMBINATION, REF and BIND. We delete the lambda
832       ;; whenever we delete any of these, but we must be careful that this LET
833       ;; has not already been partially deleted.
834       (basic-combination
835        (when (and (eq (basic-combination-kind node) :local)
836                   ;; Guards COMBINATION-LAMBDA agains the REF being deleted.
837                   (continuation-use (basic-combination-fun node)))
838          (let ((fun (combination-lambda node)))
839            ;; If our REF was the 2'nd to last ref, and has been deleted, then
840            ;; Fun may be a LET for some other combination.
841            (when (and (member (functional-kind fun) '(:let :mv-let))
842                       (eq (let-combination fun) node))
843              (delete-lambda fun))))
844        (flush-dest (basic-combination-fun node))
845        (dolist (arg (basic-combination-args node))
846          (when arg (flush-dest arg))))
847       (bind
848        (let ((lambda (bind-lambda node)))
849          (unless (eq (functional-kind lambda) :deleted)
850            (assert (member (functional-kind lambda)
851                            '(:let :mv-let :assignment)))
852            (delete-lambda lambda))))
853       (exit
854        (let ((value (exit-value node))
855              (entry (exit-entry node)))
856          (when value
857            (flush-dest value))
858          (when entry
859            (setf (entry-exits entry)
860                  (delete node (entry-exits entry))))))
861       (creturn
862        (flush-dest (return-result node))
863        (delete-return node))
864       (cset
865        (flush-dest (set-value node))
866        (let ((var (set-var node)))
867          (setf (basic-var-sets var)
868                (delete node (basic-var-sets var))))))
869
870     (delete-continuation (node-prev node)))
871
872   (remove-from-dfo block)
873   (values))
874
875 ;;; Do stuff to indicate that the return node Node is being deleted. We set
876 ;;; the RETURN to NIL.
877 (defun delete-return (node)
878   (declare (type creturn node))
879   (let ((fun (return-lambda node)))
880     (assert (lambda-return fun))
881     (setf (lambda-return fun) nil))
882   (values))
883
884 ;;; If any of the Vars in fun were never referenced and was not declared
885 ;;; IGNORE, then complain.
886 (defun note-unreferenced-vars (fun)
887   (declare (type clambda fun))
888   (dolist (var (lambda-vars fun))
889     (unless (or (leaf-ever-used var)
890                 (lambda-var-ignorep var))
891       (let ((*compiler-error-context* (lambda-bind fun)))
892         (unless (policy *compiler-error-context* (= brevity 3))
893           ;; ANSI section "3.2.5 Exceptional Situations in the Compiler"
894           ;; requires this to be a STYLE-WARNING.
895           (compiler-style-warning "The variable ~S is defined but never used."
896                                   (leaf-name var)))
897         (setf (leaf-ever-used var) t))))
898   (values))
899
900 (defvar *deletion-ignored-objects* '(t nil))
901
902 ;;; Return true if we can find Obj in Form, NIL otherwise. We bound our
903 ;;; recursion so that we don't get lost in circular structures. We ignore the
904 ;;; car of forms if they are a symbol (to prevent confusing function
905 ;;; referencess with variables), and we also ignore anything inside ' or #'.
906 (defun present-in-form (obj form depth)
907   (declare (type (integer 0 20) depth))
908   (cond ((= depth 20) nil)
909         ((eq obj form) t)
910         ((atom form) nil)
911         (t
912          (let ((first (car form))
913                (depth (1+ depth)))
914            (if (member first '(quote function))
915                nil
916                (or (and (not (symbolp first))
917                         (present-in-form obj first depth))
918                    (do ((l (cdr form) (cdr l))
919                         (n 0 (1+ n)))
920                        ((or (atom l) (> n 100))
921                         nil)
922                      (declare (fixnum n))
923                      (when (present-in-form obj (car l) depth)
924                        (return t)))))))))
925
926 ;;; This function is called on a block immediately before we delete it. We
927 ;;; check to see whether any of the code about to die appeared in the original
928 ;;; source, and emit a note if so.
929 ;;;
930 ;;; If the block was in a lambda is now deleted, then we ignore the whole
931 ;;; block, since this case is picked off in DELETE-LAMBDA. We also ignore
932 ;;; the deletion of CRETURN nodes, since it is somewhat reasonable for a
933 ;;; function to not return, and there is a different note for that case anyway.
934 ;;;
935 ;;; If the actual source is an atom, then we use a bunch of heuristics to
936 ;;; guess whether this reference really appeared in the original source:
937 ;;; -- If a symbol, it must be interned and not a keyword.
938 ;;; -- It must not be an easily introduced constant (T or NIL, a fixnum or a
939 ;;;    character.)
940 ;;; -- The atom must be "present" in the original source form, and present in
941 ;;;    all intervening actual source forms.
942 (defun note-block-deletion (block)
943   (let ((home (block-home-lambda block)))
944     (unless (eq (functional-kind home) :deleted)
945       (do-nodes (node cont block)
946         (let* ((path (node-source-path node))
947                (first (first path)))
948           (when (or (eq first 'original-source-start)
949                     (and (atom first)
950                          (or (not (symbolp first))
951                              (let ((pkg (symbol-package first)))
952                                (and pkg
953                                     (not (eq pkg (symbol-package :end))))))
954                          (not (member first *deletion-ignored-objects*))
955                          (not (typep first '(or fixnum character)))
956                          (every #'(lambda (x)
957                                     (present-in-form first x 0))
958                                 (source-path-forms path))
959                          (present-in-form first (find-original-source path)
960                                           0)))
961             (unless (return-p node)
962               (let ((*compiler-error-context* node))
963                 (compiler-note "deleting unreachable code")))
964             (return))))))
965   (values))
966
967 ;;; Delete a node from a block, deleting the block if there are no nodes
968 ;;; left. We remove the node from the uses of its CONT, but we don't deal with
969 ;;; cleaning up any type-specific semantic attachments. If the CONT is :UNUSED
970 ;;; after deleting this use, then we delete CONT. (Note :UNUSED is not the
971 ;;; same as no uses. A continuation will only become :UNUSED if it was
972 ;;; :INSIDE-BLOCK before.)
973 ;;;
974 ;;; If the node is the last node, there must be exactly one successor. We
975 ;;; link all of our precedessors to the successor and unlink the block. In
976 ;;; this case, we return T, otherwise NIL. If no nodes are left, and the block
977 ;;; is a successor of itself, then we replace the only node with a degenerate
978 ;;; exit node. This provides a way to represent the bodyless infinite loop,
979 ;;; given the prohibition on empty blocks in IR1.
980 (defun unlink-node (node)
981   (declare (type node node))
982   (let* ((cont (node-cont node))
983          (next (continuation-next cont))
984          (prev (node-prev node))
985          (block (continuation-block prev))
986          (prev-kind (continuation-kind prev))
987          (last (block-last block)))
988
989     (unless (eq (continuation-kind cont) :deleted)
990       (delete-continuation-use node)
991       (when (eq (continuation-kind cont) :unused)
992         (assert (not (continuation-dest cont)))
993         (delete-continuation cont)))
994
995     (setf (block-type-asserted block) t)
996     (setf (block-test-modified block) t)
997
998     (cond ((or (eq prev-kind :inside-block)
999                (and (eq prev-kind :block-start)
1000                     (not (eq node last))))
1001            (cond ((eq node last)
1002                   (setf (block-last block) (continuation-use prev))
1003                   (setf (continuation-next prev) nil))
1004                  (t
1005                   (setf (continuation-next prev) next)
1006                   (setf (node-prev next) prev)))
1007            (setf (node-prev node) nil)
1008            nil)
1009           (t
1010            (assert (eq prev-kind :block-start))
1011            (assert (eq node last))
1012            (let* ((succ (block-succ block))
1013                   (next (first succ)))
1014              (assert (and succ (null (cdr succ))))
1015              (cond
1016               ((member block succ)
1017                (with-ir1-environment node
1018                  (let ((exit (make-exit))
1019                        (dummy (make-continuation)))
1020                    (setf (continuation-next prev) nil)
1021                    (prev-link exit prev)
1022                    (add-continuation-use exit dummy)
1023                    (setf (block-last block) exit)))
1024                (setf (node-prev node) nil)
1025                nil)
1026               (t
1027                (assert (eq (block-start-cleanup block)
1028                            (block-end-cleanup block)))
1029                (unlink-blocks block next)
1030                (dolist (pred (block-pred block))
1031                  (change-block-successor pred block next))
1032                (remove-from-dfo block)
1033                (cond ((continuation-dest prev)
1034                       (setf (continuation-next prev) nil)
1035                       (setf (continuation-kind prev) :deleted-block-start))
1036                      (t
1037                       (delete-continuation prev)))
1038                (setf (node-prev node) nil)
1039                t)))))))
1040
1041 ;;; Return true if NODE has been deleted, false if it is still a valid part
1042 ;;; of IR1.
1043 (defun node-deleted (node)
1044   (declare (type node node))
1045   (let ((prev (node-prev node)))
1046     (not (and prev
1047               (not (eq (continuation-kind prev) :deleted))
1048               (let ((block (continuation-block prev)))
1049                 (and (block-component block)
1050                      (not (block-delete-p block))))))))
1051
1052 ;;; Delete all the blocks and functions in Component. We scan first marking
1053 ;;; the blocks as delete-p to prevent weird stuff from being triggered by
1054 ;;; deletion.
1055 (defun delete-component (component)
1056   (declare (type component component))
1057   (assert (null (component-new-functions component)))
1058   (setf (component-kind component) :deleted)
1059   (do-blocks (block component)
1060     (setf (block-delete-p block) t))
1061   (dolist (fun (component-lambdas component))
1062     (setf (functional-kind fun) nil)
1063     (setf (functional-entry-function fun) nil)
1064     (setf (leaf-refs fun) nil)
1065     (delete-functional fun))
1066   (do-blocks (block component)
1067     (delete-block block))
1068   (values))
1069
1070 ;;; Convert code of the form
1071 ;;;   (FOO ... (FUN ...) ...)
1072 ;;; to
1073 ;;;   (FOO ...    ...    ...).
1074 ;;; In other words, replace the function combination FUN by its
1075 ;;; arguments. If there are any problems with doing this, use GIVE-UP
1076 ;;; to blow out of whatever transform called this. Note, as the number
1077 ;;; of arguments changes, the transform must be prepared to return a
1078 ;;; lambda with a new lambda-list with the correct number of
1079 ;;; arguments.
1080 (defun extract-function-args (cont fun num-args)
1081   #!+sb-doc
1082   "If CONT is a call to FUN with NUM-ARGS args, change those arguments
1083    to feed directly to the continuation-dest of CONT, which must be
1084    a combination."
1085   (declare (type continuation cont)
1086            (type symbol fun)
1087            (type index num-args))
1088   (let ((outside (continuation-dest cont))
1089         (inside (continuation-use cont)))
1090     (assert (combination-p outside))
1091     (unless (combination-p inside)
1092       (give-up-ir1-transform))
1093     (let ((inside-fun (combination-fun inside)))
1094       (unless (eq (continuation-function-name inside-fun) fun)
1095         (give-up-ir1-transform))
1096       (let ((inside-args (combination-args inside)))
1097         (unless (= (length inside-args) num-args)
1098           (give-up-ir1-transform))
1099         (let* ((outside-args (combination-args outside))
1100                (arg-position (position cont outside-args))
1101                (before-args (subseq outside-args 0 arg-position))
1102                (after-args (subseq outside-args (1+ arg-position))))
1103           (dolist (arg inside-args)
1104             (setf (continuation-dest arg) outside))
1105           (setf (combination-args inside) nil)
1106           (setf (combination-args outside)
1107                 (append before-args inside-args after-args))
1108           (change-ref-leaf (continuation-use inside-fun)
1109                            (find-free-function 'list "???"))
1110           (setf (combination-kind inside) :full)
1111           (setf (node-derived-type inside) *wild-type*)
1112           (flush-dest cont)
1113           (setf (continuation-asserted-type cont) *wild-type*)
1114           (values))))))
1115 \f
1116 ;;;; leaf hackery
1117
1118 ;;; Change the Leaf that a Ref refers to.
1119 (defun change-ref-leaf (ref leaf)
1120   (declare (type ref ref) (type leaf leaf))
1121   (unless (eq (ref-leaf ref) leaf)
1122     (push ref (leaf-refs leaf))
1123     (delete-ref ref)
1124     (setf (ref-leaf ref) leaf)
1125     (let ((ltype (leaf-type leaf)))
1126       (if (function-type-p ltype)
1127           (setf (node-derived-type ref) ltype)
1128           (derive-node-type ref ltype)))
1129     (reoptimize-continuation (node-cont ref)))
1130   (values))
1131
1132 ;;; Change all Refs for Old-Leaf to New-Leaf.
1133 (defun substitute-leaf (new-leaf old-leaf)
1134   (declare (type leaf new-leaf old-leaf))
1135   (dolist (ref (leaf-refs old-leaf))
1136     (change-ref-leaf ref new-leaf))
1137   (values))
1138
1139 ;;; Like SUBSITIUTE-LEAF, only there is a predicate on the Ref to tell
1140 ;;; whether to substitute.
1141 (defun substitute-leaf-if (test new-leaf old-leaf)
1142   (declare (type leaf new-leaf old-leaf) (type function test))
1143   (dolist (ref (leaf-refs old-leaf))
1144     (when (funcall test ref)
1145       (change-ref-leaf ref new-leaf)))
1146   (values))
1147
1148 ;;; Return a LEAF which represents the specified constant object. If the
1149 ;;; object is not in *CONSTANTS*, then we create a new constant LEAF and
1150 ;;; enter it.
1151 #!-sb-fluid (declaim (maybe-inline find-constant))
1152 (defun find-constant (object)
1153   (if (typep object '(or symbol number character instance))
1154     (or (gethash object *constants*)
1155         (setf (gethash object *constants*)
1156               (make-constant :value object
1157                              :name nil
1158                              :type (ctype-of object)
1159                              :where-from :defined)))
1160     (make-constant :value object
1161                    :name nil
1162                    :type (ctype-of object)
1163                    :where-from :defined)))
1164 \f
1165 ;;; If there is a non-local exit noted in Entry's environment that exits to
1166 ;;; Cont in that entry, then return it, otherwise return NIL.
1167 (defun find-nlx-info (entry cont)
1168   (declare (type entry entry) (type continuation cont))
1169   (let ((entry-cleanup (entry-cleanup entry)))
1170     (dolist (nlx (environment-nlx-info (node-environment entry)) nil)
1171       (when (and (eq (nlx-info-continuation nlx) cont)
1172                  (eq (nlx-info-cleanup nlx) entry-cleanup))
1173         (return nlx)))))
1174 \f
1175 ;;;; functional hackery
1176
1177 ;;; If Functional is a Lambda, just return it; if it is an
1178 ;;; optional-dispatch, return the main-entry.
1179 (declaim (ftype (function (functional) clambda) main-entry))
1180 (defun main-entry (functional)
1181   (etypecase functional
1182     (clambda functional)
1183     (optional-dispatch
1184      (optional-dispatch-main-entry functional))))
1185
1186 ;;; Returns true if Functional is a thing that can be treated like
1187 ;;; MV-Bind when it appears in an MV-Call. All fixed arguments must be
1188 ;;; optional with null default and no supplied-p. There must be a rest
1189 ;;; arg with no references.
1190 (declaim (ftype (function (functional) boolean) looks-like-an-mv-bind))
1191 (defun looks-like-an-mv-bind (functional)
1192   (and (optional-dispatch-p functional)
1193        (do ((arg (optional-dispatch-arglist functional) (cdr arg)))
1194            ((null arg) nil)
1195          (let ((info (lambda-var-arg-info (car arg))))
1196            (unless info (return nil))
1197            (case (arg-info-kind info)
1198              (:optional
1199               (when (or (arg-info-supplied-p info) (arg-info-default info))
1200                 (return nil)))
1201              (:rest
1202               (return (and (null (cdr arg)) (null (leaf-refs (car arg))))))
1203              (t
1204               (return nil)))))))
1205
1206 ;;; Return true if function is an XEP. This is true of normal XEPs
1207 ;;; (:External kind) and top-level lambdas (:Top-Level kind.)
1208 #!-sb-fluid (declaim (inline external-entry-point-p))
1209 (defun external-entry-point-p (fun)
1210   (declare (type functional fun))
1211   (not (null (member (functional-kind fun) '(:external :top-level)))))
1212
1213 ;;; If Cont's only use is a non-notinline global function reference, then
1214 ;;; return the referenced symbol, otherwise NIL. If Notinline-OK is true, then
1215 ;;; we don't care if the leaf is notinline.
1216 (defun continuation-function-name (cont &optional notinline-ok)
1217   (declare (type continuation cont))
1218   (let ((use (continuation-use cont)))
1219     (if (ref-p use)
1220         (let ((leaf (ref-leaf use)))
1221           (if (and (global-var-p leaf)
1222                    (eq (global-var-kind leaf) :global-function)
1223                    (or (not (defined-function-p leaf))
1224                        (not (eq (defined-function-inlinep leaf) :notinline))
1225                        notinline-ok))
1226               (leaf-name leaf)
1227               nil))
1228         nil)))
1229
1230 ;;; Return the COMBINATION node that is the call to the let Fun.
1231 (defun let-combination (fun)
1232   (declare (type clambda fun))
1233   (assert (member (functional-kind fun) '(:let :mv-let)))
1234   (continuation-dest (node-cont (first (leaf-refs fun)))))
1235
1236 ;;; Return the initial value continuation for a let variable or NIL if none.
1237 (defun let-var-initial-value (var)
1238   (declare (type lambda-var var))
1239   (let ((fun (lambda-var-home var)))
1240     (elt (combination-args (let-combination fun))
1241          (position-or-lose var (lambda-vars fun)))))
1242
1243 ;;; Return the LAMBDA that is called by the local Call.
1244 #!-sb-fluid (declaim (inline combination-lambda))
1245 (defun combination-lambda (call)
1246   (declare (type basic-combination call))
1247   (assert (eq (basic-combination-kind call) :local))
1248   (ref-leaf (continuation-use (basic-combination-fun call))))
1249
1250 (defvar *inline-expansion-limit* 200
1251   #!+sb-doc
1252   "An upper limit on the number of inline function calls that will be expanded
1253    in any given code object (single function or block compilation.)")
1254
1255 ;;; Check whether Node's component has exceeded its inline expansion
1256 ;;; limit, and warn if so, returning NIL.
1257 (defun inline-expansion-ok (node)
1258   (let ((expanded (incf (component-inline-expansions
1259                          (block-component
1260                           (node-block node))))))
1261     (cond ((> expanded *inline-expansion-limit*) nil)
1262           ((= expanded *inline-expansion-limit*)
1263            (let ((*compiler-error-context* node))
1264              (compiler-note "*INLINE-EXPANSION-LIMIT* (~D) was exceeded, ~
1265                              probably trying to~%  ~
1266                              inline a recursive function."
1267                             *inline-expansion-limit*))
1268            nil)
1269           (t t))))
1270 \f
1271 ;;;; compiler error context determination
1272
1273 (declaim (special *current-path*))
1274
1275 ;;; We bind print level and length when printing out messages so that we don't
1276 ;;; dump huge amounts of garbage.
1277 (declaim (type (or unsigned-byte null)
1278                *compiler-error-print-level*
1279                *compiler-error-print-length*
1280                *compiler-error-print-lines*))
1281 (defvar *compiler-error-print-level* 3
1282   #!+sb-doc
1283   "The value for *PRINT-LEVEL* when printing compiler error messages.")
1284 (defvar *compiler-error-print-length* 5
1285   #!+sb-doc
1286   "The value for *PRINT-LENGTH* when printing compiler error messages.")
1287 (defvar *compiler-error-print-lines* 5
1288   #!+sb-doc
1289   "The value for *PRINT-LINES* when printing compiler error messages.")
1290
1291 (defvar *enclosing-source-cutoff* 1
1292   #!+sb-doc
1293   "The maximum number of enclosing non-original source forms (i.e. from
1294   macroexpansion) that we print in full. For additional enclosing forms, we
1295   print only the CAR.")
1296 (declaim (type unsigned-byte *enclosing-source-cutoff*))
1297
1298 ;;; We separate the determination of compiler error contexts from the actual
1299 ;;; signalling of those errors by objectifying the error context. This allows
1300 ;;; postponement of the determination of how (and if) to signal the error.
1301 ;;;
1302 ;;; We take care not to reference any of the IR1 so that pending potential
1303 ;;; error messages won't prevent the IR1 from being GC'd. To this end, we
1304 ;;; convert source forms to strings so that source forms that contain IR1
1305 ;;; references (e.g. %DEFUN) don't hold onto the IR.
1306 (defstruct (compiler-error-context
1307             #-no-ansi-print-object
1308             (:print-object (lambda (x stream)
1309                              (print-unreadable-object (x stream :type t)))))
1310   ;; A list of the stringified CARs of the enclosing non-original source forms
1311   ;; exceeding the *enclosing-source-cutoff*.
1312   (enclosing-source nil :type list)
1313   ;; A list of stringified enclosing non-original source forms.
1314   (source nil :type list)
1315   ;; The stringified form in the original source that expanded into Source.
1316   (original-source (required-argument) :type simple-string)
1317   ;; A list of prefixes of "interesting" forms that enclose original-source.
1318   (context nil :type list)
1319   ;; The FILE-INFO-NAME for the relevant FILE-INFO.
1320   (file-name (required-argument)
1321              :type (or pathname (member :lisp :stream)))
1322   ;; The file position at which the top-level form starts, if applicable.
1323   (file-position nil :type (or index null))
1324   ;; The original source part of the source path.
1325   (original-source-path nil :type list))
1326
1327 ;;; If true, this is the node which is used as context in compiler warning
1328 ;;; messages.
1329 (declaim (type (or null compiler-error-context node) *compiler-error-context*))
1330 (defvar *compiler-error-context* nil)
1331
1332 ;;; a hashtable mapping macro names to source context parsers. Each parser
1333 ;;; function returns the source-context list for that form.
1334 (defvar *source-context-methods* (make-hash-table))
1335
1336 ;;; documentation originally from cmu-user.tex:
1337 ;;;   This macro defines how to extract an abbreviated source context from
1338 ;;;   the \var{name}d form when it appears in the compiler input.
1339 ;;;   \var{lambda-list} is a \code{defmacro} style lambda-list used to
1340 ;;;   parse the arguments. The \var{body} should return a list of
1341 ;;;   subforms that can be printed on about one line. There are
1342 ;;;   predefined methods for \code{defstruct}, \code{defmethod}, etc. If
1343 ;;;   no method is defined, then the first two subforms are returned.
1344 ;;;   Note that this facility implicitly determines the string name
1345 ;;;   associated with anonymous functions.
1346 ;;; So even though SBCL itself only uses this macro within this file, it's a
1347 ;;; reasonable thing to put in SB-EXT in case some dedicated user wants to do
1348 ;;; some heavy tweaking to make SBCL give more informative output about his
1349 ;;; code.
1350 (defmacro def-source-context (name lambda-list &body body)
1351   #!+sb-doc
1352   "DEF-SOURCE-CONTEXT Name Lambda-List Form*
1353    This macro defines how to extract an abbreviated source context from the
1354    Named form when it appears in the compiler input. Lambda-List is a DEFMACRO
1355    style lambda-list used to parse the arguments. The Body should return a
1356    list of subforms suitable for a \"~{~S ~}\" format string."
1357   (let ((n-whole (gensym)))
1358     `(setf (gethash ',name *source-context-methods*)
1359            #'(lambda (,n-whole)
1360                (destructuring-bind ,lambda-list ,n-whole ,@body)))))
1361
1362 (def-source-context defstruct (name-or-options &rest slots)
1363   (declare (ignore slots))
1364   `(defstruct ,(if (consp name-or-options)
1365                    (car name-or-options)
1366                    name-or-options)))
1367
1368 (def-source-context function (thing)
1369   (if (and (consp thing) (eq (first thing) 'lambda) (consp (rest thing)))
1370       `(lambda ,(second thing))
1371       `(function ,thing)))
1372
1373 ;;; Return the first two elements of FORM if FORM is a list. Take the
1374 ;;; CAR of the second form if appropriate.
1375 (defun source-form-context (form)
1376   (cond ((atom form) nil)
1377         ((>= (length form) 2)
1378          (funcall (gethash (first form) *source-context-methods*
1379                            #'(lambda (x)
1380                                (declare (ignore x))
1381                                (list (first form) (second form))))
1382                   (rest form)))
1383         (t
1384          form)))
1385
1386 ;;; Given a source path, return the original source form and a description
1387 ;;; of the interesting aspects of the context in which it appeared. The
1388 ;;; context is a list of lists, one sublist per context form. The sublist is a
1389 ;;; list of some of the initial subforms of the context form.
1390 ;;;
1391 ;;; For now, we use the first two subforms of each interesting form. A form is
1392 ;;; interesting if the first element is a symbol beginning with "DEF" and it is
1393 ;;; not the source form. If there is no DEF-mumble, then we use the outermost
1394 ;;; containing form. If the second subform is a list, then in some cases we
1395 ;;; return the car of that form rather than the whole form (i.e. don't show
1396 ;;; defstruct options, etc.)
1397 (defun find-original-source (path)
1398   (declare (list path))
1399   (let* ((rpath (reverse (source-path-original-source path)))
1400          (tlf (first rpath))
1401          (root (find-source-root tlf *source-info*)))
1402     (collect ((context))
1403       (let ((form root)
1404             (current (rest rpath)))
1405         (loop
1406           (when (atom form)
1407             (assert (null current))
1408             (return))
1409           (let ((head (first form)))
1410             (when (symbolp head)
1411               (let ((name (symbol-name head)))
1412                 (when (and (>= (length name) 3) (string= name "DEF" :end1 3))
1413                   (context (source-form-context form))))))
1414           (when (null current) (return))
1415           (setq form (nth (pop current) form)))
1416         
1417         (cond ((context)
1418                (values form (context)))
1419               ((and path root)
1420                (let ((c (source-form-context root)))
1421                  (values form (if c (list c) nil))))
1422               (t
1423                (values '(unable to locate source)
1424                        '((some strange place)))))))))
1425
1426 ;;; Convert a source form to a string, formatted suitably for use in
1427 ;;; compiler warnings.
1428 (defun stringify-form (form &optional (pretty t))
1429   (let ((*print-level* *compiler-error-print-level*)
1430         (*print-length* *compiler-error-print-length*)
1431         (*print-lines* *compiler-error-print-lines*)
1432         (*print-pretty* pretty))
1433     (if pretty
1434         (format nil "  ~S~%" form)
1435         (prin1-to-string form))))
1436
1437 ;;; Return a COMPILER-ERROR-CONTEXT structure describing the current error
1438 ;;; context, or NIL if we can't figure anything out. ARGS is a list of things
1439 ;;; that are going to be printed out in the error message, and can thus be
1440 ;;; blown off when they appear in the source context.
1441 (defun find-error-context (args)
1442   (let ((context *compiler-error-context*))
1443     (if (compiler-error-context-p context)
1444         context
1445         (let ((path (or *current-path*
1446                         (if context
1447                             (node-source-path context)
1448                             nil))))
1449           (when (and *source-info* path)
1450             (multiple-value-bind (form src-context) (find-original-source path)
1451               (collect ((full nil cons)
1452                         (short nil cons))
1453                 (let ((forms (source-path-forms path))
1454                       (n 0))
1455                   (dolist (src (if (member (first forms) args)
1456                                    (rest forms)
1457                                    forms))
1458                     (if (>= n *enclosing-source-cutoff*)
1459                         (short (stringify-form (if (consp src)
1460                                                    (car src)
1461                                                    src)
1462                                                nil))
1463                         (full (stringify-form src)))
1464                     (incf n)))
1465
1466                 (let* ((tlf (source-path-tlf-number path))
1467                        (file (find-file-info tlf *source-info*)))
1468                   (make-compiler-error-context
1469                    :enclosing-source (short)
1470                    :source (full)
1471                    :original-source (stringify-form form)
1472                    :context src-context
1473                    :file-name (file-info-name file)
1474                    :file-position
1475                    (multiple-value-bind (ignore pos)
1476                        (find-source-root tlf *source-info*)
1477                      (declare (ignore ignore))
1478                      pos)
1479                    :original-source-path
1480                    (source-path-original-source path))))))))))
1481 \f
1482 ;;;; printing error messages
1483
1484 ;;; We save the context information that we printed out most recently so that
1485 ;;; we don't print it out redundantly.
1486
1487 ;;; The last COMPILER-ERROR-CONTEXT that we printed.
1488 (defvar *last-error-context* nil)
1489 (declaim (type (or compiler-error-context null) *last-error-context*))
1490
1491 ;;; The format string and args for the last error we printed.
1492 (defvar *last-format-string* nil)
1493 (defvar *last-format-args* nil)
1494 (declaim (type (or string null) *last-format-string*))
1495 (declaim (type list *last-format-args*))
1496
1497 ;;; The number of times that the last error message has been emitted, so that
1498 ;;; we can compress duplicate error messages.
1499 (defvar *last-message-count* 0)
1500 (declaim (type index *last-message-count*))
1501
1502 ;;; If the last message was given more than once, then print out an
1503 ;;; indication of how many times it was repeated. We reset the message count
1504 ;;; when we are done.
1505 (defun note-message-repeats (&optional (terpri t))
1506   (cond ((= *last-message-count* 1)
1507          (when terpri (terpri *error-output*)))
1508         ((> *last-message-count* 1)
1509          (format *error-output* "[Last message occurs ~D times.]~2%"
1510                  *last-message-count*)))
1511   (setq *last-message-count* 0))
1512
1513 ;;; Print out the message, with appropriate context if we can find it. If
1514 ;;; If the context is different from the context of the last message we
1515 ;;; printed, then we print the context. If the original source is different
1516 ;;; from the source we are working on, then we print the current source in
1517 ;;; addition to the original source.
1518 ;;;
1519 ;;; We suppress printing of messages identical to the previous, but record
1520 ;;; the number of times that the message is repeated.
1521 (defun print-compiler-message (format-string format-args)
1522
1523   (declare (type simple-string format-string))
1524   (declare (type list format-args))
1525   
1526   (let ((stream *error-output*)
1527         (context (find-error-context format-args)))
1528     (cond
1529      (context
1530       (let ((file (compiler-error-context-file-name context))
1531             (in (compiler-error-context-context context))
1532             (form (compiler-error-context-original-source context))
1533             (enclosing (compiler-error-context-enclosing-source context))
1534             (source (compiler-error-context-source context))
1535             (last *last-error-context*))
1536
1537         (unless (and last
1538                      (equal file (compiler-error-context-file-name last)))
1539           (when (pathnamep file)
1540             (note-message-repeats)
1541             (setq last nil)
1542             (format stream "~2&file: ~A~%" (namestring file))))
1543
1544         (unless (and last
1545                      (equal in (compiler-error-context-context last)))
1546           (note-message-repeats)
1547           (setq last nil)
1548           (format stream "~2&in:~{~<~%   ~4:;~{ ~S~}~>~^ =>~}~%" in))
1549
1550         (unless (and last
1551                      (string= form
1552                               (compiler-error-context-original-source last)))
1553           (note-message-repeats)
1554           (setq last nil)
1555           (write-string form stream))
1556
1557         (unless (and last
1558                      (equal enclosing
1559                             (compiler-error-context-enclosing-source last)))
1560           (when enclosing
1561             (note-message-repeats)
1562             (setq last nil)
1563             (format stream "--> ~{~<~%--> ~1:;~A~> ~}~%" enclosing)))
1564
1565         (unless (and last
1566                      (equal source (compiler-error-context-source last)))
1567           (setq *last-format-string* nil)
1568           (when source
1569             (note-message-repeats)
1570             (dolist (src source)
1571               (write-line "==>" stream)
1572               (write-string src stream))))))
1573      (t
1574       (note-message-repeats)
1575       (setq *last-format-string* nil)
1576       (format stream "~2&")))
1577
1578     (setq *last-error-context* context)
1579
1580     (unless (and (equal format-string *last-format-string*)
1581                  (tree-equal format-args *last-format-args*))
1582       (note-message-repeats nil)
1583       (setq *last-format-string* format-string)
1584       (setq *last-format-args* format-args)
1585       (let ((*print-level*  *compiler-error-print-level*)
1586             (*print-length* *compiler-error-print-length*)
1587             (*print-lines*  *compiler-error-print-lines*))
1588         (format stream "~&~?~&" format-string format-args))))
1589
1590   (incf *last-message-count*)
1591   (values))
1592
1593 (defun print-compiler-condition (condition)
1594   (declare (type condition condition))
1595   (let (;; These different classes of conditions have different effects
1596         ;; on the return codes of COMPILE-FILE, so it's nice for users to be
1597         ;; able to pick them out by lexical search through the output.
1598         (what (etypecase condition
1599                 (style-warning 'style-warning)
1600                 (warning 'warning)
1601                 (error 'error))))
1602     (multiple-value-bind (format-string format-args)
1603         (if (typep condition 'simple-condition)
1604             (values (simple-condition-format-control condition)
1605                     (simple-condition-format-arguments condition))
1606             (values "~A"
1607                     (list (with-output-to-string (s)
1608                             (princ condition s)))))
1609       (print-compiler-message (format nil
1610                                       "caught ~S:~%  ~A"
1611                                       what
1612                                       format-string)
1613                               format-args)))
1614   (values))
1615
1616 ;;; COMPILER-NOTE is vaguely like COMPILER-ERROR and the other
1617 ;;; condition-signalling functions, but it just writes some output instead of
1618 ;;; signalling. (In CMU CL, it did signal a condition, but this didn't seem to
1619 ;;; work all that well; it was weird to have COMPILE-FILE return with
1620 ;;; WARNINGS-P set when the only problem was that the compiler couldn't figure
1621 ;;; out how to compile something as efficiently as it liked.)
1622 (defun compiler-note (format-string &rest format-args)
1623   (unless (if *compiler-error-context*
1624               (policy *compiler-error-context* (= brevity 3))
1625               (policy nil (= brevity 3)))
1626     (incf *compiler-note-count*)
1627     (print-compiler-message (format nil "note: ~A" format-string)
1628                             format-args))
1629   (values))
1630
1631 ;;; The politically correct way to print out progress messages and
1632 ;;; such like. We clear the current error context so that we know that
1633 ;;; it needs to be reprinted, and we also Force-Output so that the
1634 ;;; message gets seen right away.
1635 (declaim (ftype (function (string &rest t) (values)) compiler-mumble))
1636 (defun compiler-mumble (format-string &rest format-args)
1637   (note-message-repeats)
1638   (setq *last-error-context* nil)
1639   (apply #'format *error-output* format-string format-args)
1640   (force-output *error-output*)
1641   (values))
1642
1643 ;;; Return a string that somehow names the code in Component. We use
1644 ;;; the source path for the bind node for an arbitrary entry point to
1645 ;;; find the source context, then return that as a string.
1646 (declaim (ftype (function (component) simple-string) find-component-name))
1647 (defun find-component-name (component)
1648   (let ((ep (first (block-succ (component-head component)))))
1649     (assert ep () "no entry points?")
1650     (multiple-value-bind (form context)
1651         (find-original-source
1652          (node-source-path (continuation-next (block-start ep))))
1653       (declare (ignore form))
1654       (let ((*print-level* 2)
1655             (*print-pretty* nil))
1656         (format nil "~{~{~S~^ ~}~^ => ~}" context)))))
1657 \f
1658 ;;;; condition system interface
1659
1660 ;;; Keep track of how many times each kind of condition happens.
1661 (defvar *compiler-error-count*)
1662 (defvar *compiler-warning-count*)
1663 (defvar *compiler-style-warning-count*)
1664 (defvar *compiler-note-count*)
1665
1666 ;;; Keep track of whether any surrounding COMPILE or COMPILE-FILE call
1667 ;;; should return WARNINGS-P or FAILURE-P.
1668 (defvar *failure-p*)
1669 (defvar *warnings-p*)
1670
1671 ;;; condition handlers established by the compiler. We re-signal the
1672 ;;; condition, if it is not handled, we increment our warning counter
1673 ;;; and print the error message.
1674 (defun compiler-error-handler (condition)
1675   (signal condition)
1676   (incf *compiler-error-count*)
1677   (setf *warnings-p* t
1678         *failure-p* t)
1679   (print-compiler-condition condition)
1680   (continue condition))
1681 (defun compiler-warning-handler (condition)
1682   (signal condition)
1683   (incf *compiler-warning-count*)
1684   (setf *warnings-p* t
1685         *failure-p* t)
1686   (print-compiler-condition condition)
1687   (muffle-warning condition))
1688 (defun compiler-style-warning-handler (condition)
1689   (signal condition)
1690   (incf *compiler-style-warning-count*)
1691   (setf *warnings-p* t)
1692   (print-compiler-condition condition)
1693   (muffle-warning condition))
1694 \f
1695 ;;;; undefined warnings
1696
1697 (defvar *undefined-warning-limit* 3
1698   #!+sb-doc
1699   "If non-null, then an upper limit on the number of unknown function or type
1700   warnings that the compiler will print for any given name in a single
1701   compilation. This prevents excessive amounts of output when the real
1702   problem is a missing definition (as opposed to a typo in the use.)")
1703
1704 ;;; Make an entry in the *UNDEFINED-WARNINGS* describing a reference
1705 ;;; to Name of the specified Kind. If we have exceeded the warning
1706 ;;; limit, then just increment the count, otherwise note the current
1707 ;;; error context.
1708 ;;;
1709 ;;; Undefined types are noted by a condition handler in
1710 ;;; WITH-COMPILATION-UNIT, which can potentially be invoked outside
1711 ;;; the compiler, hence the BOUNDP check.
1712 (defun note-undefined-reference (name kind)
1713   (unless (and (boundp '*lexenv*)
1714                ;; FIXME: I'm pretty sure the BREVITY test below isn't
1715                ;; a good idea; we should have BREVITY affect compiler
1716                ;; notes, not STYLE-WARNINGs. And I'm not sure what the
1717                ;; BOUNDP '*LEXENV* test above is for; it's likely
1718                ;; a good idea, but it probably deserves an explanatory
1719                ;; comment.
1720                (policy nil (= brevity 3)))
1721     (let* ((found (dolist (warning *undefined-warnings* nil)
1722                     (when (and (equal (undefined-warning-name warning) name)
1723                                (eq (undefined-warning-kind warning) kind))
1724                       (return warning))))
1725            (res (or found
1726                     (make-undefined-warning :name name :kind kind))))
1727       (unless found (push res *undefined-warnings*))
1728       (when (or (not *undefined-warning-limit*)
1729                 (< (undefined-warning-count res) *undefined-warning-limit*))
1730         (push (find-error-context (list name))
1731               (undefined-warning-warnings res)))
1732       (incf (undefined-warning-count res))))
1733   (values))
1734 \f
1735 ;;;; careful call
1736
1737 ;;; Apply a function to some arguments, returning a list of the values
1738 ;;; resulting of the evaluation. If an error is signalled during the
1739 ;;; application, then we print a warning message and return NIL as our
1740 ;;; second value to indicate this. Node is used as the error context
1741 ;;; for any error message, and Context is a string that is spliced
1742 ;;; into the warning.
1743 (declaim (ftype (function ((or symbol function) list node string)
1744                           (values list boolean))
1745                 careful-call))
1746 (defun careful-call (function args node context)
1747   (values
1748    (multiple-value-list
1749     (handler-case (apply function args)
1750       (error (condition)
1751         (let ((*compiler-error-context* node))
1752           (compiler-warning "Lisp error during ~A:~%~A" context condition)
1753           (return-from careful-call (values nil nil))))))
1754    t))
1755 \f
1756 ;;;; utilities used at run-time for parsing keyword args in IR1
1757
1758 ;;; This function is used by the result of Parse-Deftransform to find
1759 ;;; the continuation for the value of the keyword argument Key in the
1760 ;;; list of continuations Args. It returns the continuation if the
1761 ;;; keyword is present, or NIL otherwise. The legality and
1762 ;;; constantness of the keywords should already have been checked.
1763 (declaim (ftype (function (list keyword) (or continuation null))
1764                 find-keyword-continuation))
1765 (defun find-keyword-continuation (args key)
1766   (do ((arg args (cddr arg)))
1767       ((null arg) nil)
1768     (when (eq (continuation-value (first arg)) key)
1769       (return (second arg)))))
1770
1771 ;;; This function is used by the result of Parse-Deftransform to
1772 ;;; verify that alternating continuations in Args are constant and
1773 ;;; that there is an even number of args.
1774 (declaim (ftype (function (list) boolean) check-keywords-constant))
1775 (defun check-keywords-constant (args)
1776   (do ((arg args (cddr arg)))
1777       ((null arg) t)
1778     (unless (and (rest arg)
1779                  (constant-continuation-p (first arg)))
1780       (return nil))))
1781
1782 ;;; This function is used by the result of Parse-Deftransform to
1783 ;;; verify that the list of continuations Args is a well-formed
1784 ;;; keyword arglist and that only keywords present in the list Keys
1785 ;;; are supplied.
1786 (declaim (ftype (function (list list) boolean) check-transform-keys))
1787 (defun check-transform-keys (args keys)
1788   (and (check-keywords-constant args)
1789        (do ((arg args (cddr arg)))
1790            ((null arg) t)
1791          (unless (member (continuation-value (first arg)) keys)
1792            (return nil)))))
1793 \f
1794 ;;;; miscellaneous
1795
1796 ;;; Called by the expansion of the EVENT macro.
1797 (declaim (ftype (function (event-info (or node null)) *) %event))
1798 (defun %event (info node)
1799   (incf (event-info-count info))
1800   (when (and (>= (event-info-level info) *event-note-threshold*)
1801              (if node
1802                  (policy node (= brevity 0))
1803                  (policy nil (= brevity 0))))
1804     (let ((*compiler-error-context* node))
1805       (compiler-note (event-info-description info))))
1806
1807   (let ((action (event-info-action info)))
1808     (when action (funcall action node))))