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