more funky &REST smartness
[sbcl.git] / src / compiler / ir1-translators.lisp
1 ;;;; the usual place for DEF-IR1-TRANSLATOR forms (and their
2 ;;;; close personal friends)
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 ;;;; special forms for control
16
17 (def-ir1-translator progn ((&rest forms) start next result)
18   #!+sb-doc
19   "PROGN form*
20
21 Evaluates each FORM in order, returning the values of the last form. With no
22 forms, returns NIL."
23   (ir1-convert-progn-body start next result forms))
24
25 (def-ir1-translator if ((test then &optional else) start next result)
26   #!+sb-doc
27   "IF predicate then [else]
28
29 If PREDICATE evaluates to true, evaluate THEN and return its values,
30 otherwise evaluate ELSE and return its values. ELSE defaults to NIL."
31   (let* ((pred-ctran (make-ctran))
32          (pred-lvar (make-lvar))
33          (then-ctran (make-ctran))
34          (then-block (ctran-starts-block then-ctran))
35          (else-ctran (make-ctran))
36          (else-block (ctran-starts-block else-ctran))
37          (maybe-instrument *instrument-if-for-code-coverage*)
38          (*instrument-if-for-code-coverage* t)
39          (node (make-if :test pred-lvar
40                         :consequent then-block
41                         :alternative else-block)))
42     ;; IR1-CONVERT-MAYBE-PREDICATE requires DEST to be CIF, so the
43     ;; order of the following two forms is important
44     (setf (lvar-dest pred-lvar) node)
45     (multiple-value-bind (context count) (possible-rest-arg-context test)
46       (if context
47           (ir1-convert start pred-ctran pred-lvar `(%rest-true ,test ,context ,count))
48           (ir1-convert start pred-ctran pred-lvar test)))
49     (link-node-to-previous-ctran node pred-ctran)
50
51     (let ((start-block (ctran-block pred-ctran)))
52       (setf (block-last start-block) node)
53       (ctran-starts-block next)
54
55       (link-blocks start-block then-block)
56       (link-blocks start-block else-block))
57
58     (let ((path (best-sub-source-path test)))
59       (ir1-convert (if (and path maybe-instrument)
60                        (let ((*current-path* path))
61                          (instrument-coverage then-ctran :then test))
62                        then-ctran)
63                    next result then)
64       (ir1-convert (if (and path maybe-instrument)
65                        (let ((*current-path* path))
66                          (instrument-coverage else-ctran :else test))
67                        else-ctran)
68                    next result else))))
69
70 ;;; To get even remotely sensible results for branch coverage
71 ;;; tracking, we need good source paths. If the macroexpansions
72 ;;; interfere enough the TEST of the conditional doesn't actually have
73 ;;; an original source location (e.g. (UNLESS FOO ...) -> (IF (NOT
74 ;;; FOO) ...). Look through the form, and try to find some subform
75 ;;; that has one.
76 (defun best-sub-source-path (form)
77   (if (policy *lexenv* (= store-coverage-data 0))
78       nil
79       (labels ((sub (form)
80                  (or (get-source-path form)
81                      (when (consp form)
82                        (unless (eq 'quote (car form))
83                          (somesub form)))))
84                (somesub (forms)
85                  (when (consp forms)
86                    (or (sub (car forms))
87                        (somesub (cdr forms))))))
88         (sub form))))
89 \f
90 ;;;; BLOCK and TAGBODY
91
92 ;;;; We make an ENTRY node to mark the start and a :ENTRY cleanup to
93 ;;;; mark its extent. When doing GO or RETURN-FROM, we emit an EXIT
94 ;;;; node.
95
96 ;;; Make a :ENTRY cleanup and emit an ENTRY node, then convert the
97 ;;; body in the modified environment. We make NEXT start a block now,
98 ;;; since if it was done later, the block would be in the wrong
99 ;;; environment.
100 (def-ir1-translator block ((name &rest forms) start next result)
101   #!+sb-doc
102   "BLOCK name form*
103
104 Evaluate the FORMS as a PROGN. Within the lexical scope of the body,
105 RETURN-FROM can be used to exit the form."
106   (unless (symbolp name)
107     (compiler-error "The block name ~S is not a symbol." name))
108   (start-block start)
109   (ctran-starts-block next)
110   (let* ((dummy (make-ctran))
111          (entry (make-entry))
112          (cleanup (make-cleanup :kind :block
113                                 :mess-up entry)))
114     (push entry (lambda-entries (lexenv-lambda *lexenv*)))
115     (setf (entry-cleanup entry) cleanup)
116     (link-node-to-previous-ctran entry start)
117     (use-ctran entry dummy)
118
119     (let* ((env-entry (list entry next result))
120            (*lexenv* (make-lexenv :blocks (list (cons name env-entry))
121                                   :cleanup cleanup)))
122       (ir1-convert-progn-body dummy next result forms))))
123
124 (def-ir1-translator return-from ((name &optional value) start next result)
125   #!+sb-doc
126   "RETURN-FROM block-name value-form
127
128 Evaluate the VALUE-FORM, returning its values from the lexically enclosing
129 block BLOCK-NAME. This is constrained to be used only within the dynamic
130 extent of the block."
131   ;; old comment:
132   ;;   We make NEXT start a block just so that it will have a block
133   ;;   assigned. People assume that when they pass a ctran into
134   ;;   IR1-CONVERT as NEXT, it will have a block when it is done.
135   ;; KLUDGE: Note that this block is basically fictitious. In the code
136   ;;   (BLOCK B (RETURN-FROM B) (SETQ X 3))
137   ;; it's the block which answers the question "which block is
138   ;; the (SETQ X 3) in?" when the right answer is that (SETQ X 3) is
139   ;; dead code and so doesn't really have a block at all. The existence
140   ;; of this block, and that way that it doesn't explicitly say
141   ;; "I'm actually nowhere at all" makes some logic (e.g.
142   ;; BLOCK-HOME-LAMBDA-OR-NULL) more obscure, and it might be better
143   ;; to get rid of it, perhaps using a special placeholder value
144   ;; to indicate the orphanedness of the code.
145   (declare (ignore result))
146   (ctran-starts-block next)
147   (let* ((found (or (lexenv-find name blocks)
148                     (compiler-error "return for unknown block: ~S" name)))
149          (exit-ctran (second found))
150          (value-ctran (make-ctran))
151          (value-lvar (make-lvar))
152          (entry (first found))
153          (exit (make-exit :entry entry
154                           :value value-lvar)))
155     (when (ctran-deleted-p exit-ctran)
156       (throw 'locall-already-let-converted exit-ctran))
157     (push exit (entry-exits entry))
158     (setf (lvar-dest value-lvar) exit)
159     (ir1-convert start value-ctran value-lvar value)
160     (link-node-to-previous-ctran exit value-ctran)
161     (let ((home-lambda (ctran-home-lambda-or-null start)))
162       (when home-lambda
163         (sset-adjoin entry (lambda-calls-or-closes home-lambda))))
164     (use-continuation exit exit-ctran (third found))))
165
166 ;;; Return a list of the segments of a TAGBODY. Each segment looks
167 ;;; like (<tag> <form>* (go <next tag>)). That is, we break up the
168 ;;; tagbody into segments of non-tag statements, and explicitly
169 ;;; represent the drop-through with a GO. The first segment has a
170 ;;; dummy NIL tag, since it represents code before the first tag. Note
171 ;;; however that NIL may appear as the tag of an inner segment. The
172 ;;; last segment (which may also be the first segment) ends in NIL
173 ;;; rather than a GO.
174 (defun parse-tagbody (body)
175   (declare (list body))
176   (collect ((tags)
177             (segments))
178     (let ((current body))
179       (loop
180        (let ((next-segment (member-if #'atom current)))
181          (unless next-segment
182            (segments `(,@current nil))
183            (return))
184          (let ((tag (car next-segment)))
185            (when (member tag (tags))
186              (compiler-error
187               "The tag ~S appears more than once in a tagbody."
188               tag))
189            (unless (or (symbolp tag) (integerp tag))
190              (compiler-error "~S is not a legal go tag." tag))
191            (tags tag)
192            (segments `(,@(ldiff current next-segment) (go ,tag))))
193          (setq current (rest next-segment))))
194       (mapcar #'cons (cons nil (tags)) (segments)))))
195
196 ;;; Set up the cleanup, emitting the entry node. Then make a block for
197 ;;; each tag, building up the tag list for LEXENV-TAGS as we go.
198 ;;; Finally, convert each segment with the precomputed Start and Cont
199 ;;; values.
200 (def-ir1-translator tagbody ((&rest statements) start next result)
201   #!+sb-doc
202   "TAGBODY {tag | statement}*
203
204 Define tags for use with GO. The STATEMENTS are evaluated in order, skipping
205 TAGS, and NIL is returned. If a statement contains a GO to a defined TAG
206 within the lexical scope of the form, then control is transferred to the next
207 statement following that tag. A TAG must be an integer or a symbol. A
208 STATEMENT must be a list. Other objects are illegal within the body."
209   (start-block start)
210   (ctran-starts-block next)
211   (let* ((dummy (make-ctran))
212          (entry (make-entry))
213          (segments (parse-tagbody statements))
214          (cleanup (make-cleanup :kind :tagbody
215                                 :mess-up entry)))
216     (push entry (lambda-entries (lexenv-lambda *lexenv*)))
217     (setf (entry-cleanup entry) cleanup)
218     (link-node-to-previous-ctran entry start)
219     (use-ctran entry dummy)
220
221     (collect ((tags)
222               (starts)
223               (ctrans))
224       (starts dummy)
225       (dolist (segment (rest segments))
226         (let* ((tag-ctran (make-ctran))
227                (tag (list (car segment) entry tag-ctran)))
228           (ctrans tag-ctran)
229           (starts tag-ctran)
230           (ctran-starts-block tag-ctran)
231           (tags tag)))
232       (ctrans next)
233
234       (let ((*lexenv* (make-lexenv :cleanup cleanup :tags (tags))))
235         (mapc (lambda (segment start end)
236                 (ir1-convert-progn-body start end
237                                         (when (eq end next) result)
238                                         (rest segment)))
239               segments (starts) (ctrans))))))
240
241 ;;; Emit an EXIT node without any value.
242 (def-ir1-translator go ((tag) start next result)
243   #!+sb-doc
244   "GO tag
245
246 Transfer control to the named TAG in the lexically enclosing TAGBODY. This is
247 constrained to be used only within the dynamic extent of the TAGBODY."
248   (ctran-starts-block next)
249   (let* ((found (or (lexenv-find tag tags :test #'eql)
250                     (compiler-error "attempt to GO to nonexistent tag: ~S"
251                                     tag)))
252          (entry (first found))
253          (exit (make-exit :entry entry)))
254     (push exit (entry-exits entry))
255     (link-node-to-previous-ctran exit start)
256     (let ((home-lambda (ctran-home-lambda-or-null start)))
257       (when home-lambda
258         (sset-adjoin entry (lambda-calls-or-closes home-lambda))))
259     (use-ctran exit (second found))))
260 \f
261 ;;;; translators for compiler-magic special forms
262
263 ;;; This handles EVAL-WHEN in non-top-level forms. (EVAL-WHENs in top
264 ;;; level forms are picked off and handled by PROCESS-TOPLEVEL-FORM,
265 ;;; so that they're never seen at this level.)
266 ;;;
267 ;;; ANSI "3.2.3.1 Processing of Top Level Forms" says that processing
268 ;;; of non-top-level EVAL-WHENs is very simple:
269 ;;;   EVAL-WHEN forms cause compile-time evaluation only at top level.
270 ;;;   Both :COMPILE-TOPLEVEL and :LOAD-TOPLEVEL situation specifications
271 ;;;   are ignored for non-top-level forms. For non-top-level forms, an
272 ;;;   eval-when specifying the :EXECUTE situation is treated as an
273 ;;;   implicit PROGN including the forms in the body of the EVAL-WHEN
274 ;;;   form; otherwise, the forms in the body are ignored.
275 (def-ir1-translator eval-when ((situations &rest forms) start next result)
276   #!+sb-doc
277   "EVAL-WHEN (situation*) form*
278
279 Evaluate the FORMS in the specified SITUATIONS (any of :COMPILE-TOPLEVEL,
280 :LOAD-TOPLEVEL, or :EXECUTE, or (deprecated) COMPILE, LOAD, or EVAL)."
281   (multiple-value-bind (ct lt e) (parse-eval-when-situations situations)
282     (declare (ignore ct lt))
283     (ir1-convert-progn-body start next result (and e forms)))
284   (values))
285
286 ;;; common logic for MACROLET and SYMBOL-MACROLET
287 ;;;
288 ;;; Call DEFINITIONIZE-FUN on each element of DEFINITIONS to find its
289 ;;; in-lexenv representation, stuff the results into *LEXENV*, and
290 ;;; call FUN (with no arguments).
291 (defun %funcall-in-foomacrolet-lexenv (definitionize-fun
292                                        definitionize-keyword
293                                        definitions
294                                        fun)
295   (declare (type function definitionize-fun fun))
296   (declare (type (member :vars :funs) definitionize-keyword))
297   (declare (type list definitions))
298   (unless (= (length definitions)
299              (length (remove-duplicates definitions :key #'first)))
300     (compiler-style-warn "duplicate definitions in ~S" definitions))
301   (let* ((processed-definitions (mapcar definitionize-fun definitions))
302          (*lexenv* (make-lexenv definitionize-keyword processed-definitions)))
303     ;; I wonder how much of an compiler performance penalty this
304     ;; non-constant keyword is.
305     (funcall fun definitionize-keyword processed-definitions)))
306
307 ;;; Tweak LEXENV to include the DEFINITIONS from a MACROLET, then
308 ;;; call FUN (with no arguments).
309 ;;;
310 ;;; This is split off from the IR1 convert method so that it can be
311 ;;; shared by the special-case top level MACROLET processing code, and
312 ;;; further split so that the special-case MACROLET processing code in
313 ;;; EVAL can likewise make use of it.
314 (defun macrolet-definitionize-fun (context lexenv)
315   (flet ((fail (control &rest args)
316            (ecase context
317              (:compile (apply #'compiler-error control args))
318              (:eval (error 'simple-program-error
319                            :format-control control
320                            :format-arguments args)))))
321     (lambda (definition)
322       (unless (list-of-length-at-least-p definition 2)
323         (fail "The list ~S is too short to be a legal local macro definition."
324               definition))
325       (destructuring-bind (name arglist &body body) definition
326         (unless (symbolp name)
327           (fail "The local macro name ~S is not a symbol." name))
328         (when (fboundp name)
329           (program-assert-symbol-home-package-unlocked
330            context name "binding ~A as a local macro"))
331         (unless (listp arglist)
332           (fail "The local macro argument list ~S is not a list."
333                 arglist))
334         (with-unique-names (whole environment)
335           (multiple-value-bind (body local-decls)
336               (parse-defmacro arglist whole body name 'macrolet
337                               :environment environment)
338             `(,name macro .
339                     ,(compile-in-lexenv
340                       nil
341                       `(lambda (,whole ,environment)
342                          ,@local-decls
343                          ,body)
344                       lexenv))))))))
345
346 (defun funcall-in-macrolet-lexenv (definitions fun context)
347   (%funcall-in-foomacrolet-lexenv
348    (macrolet-definitionize-fun context (make-restricted-lexenv *lexenv*))
349    :funs
350    definitions
351    fun))
352
353 (def-ir1-translator macrolet ((definitions &rest body) start next result)
354   #!+sb-doc
355   "MACROLET ({(name lambda-list form*)}*) body-form*
356
357 Evaluate the BODY-FORMS in an environment with the specified local macros
358 defined. NAME is the local macro name, LAMBDA-LIST is a DEFMACRO style
359 destructuring lambda list, and the FORMS evaluate to the expansion."
360   (funcall-in-macrolet-lexenv
361    definitions
362    (lambda (&key funs)
363      (declare (ignore funs))
364      (ir1-translate-locally body start next result))
365    :compile))
366
367 (defun symbol-macrolet-definitionize-fun (context)
368   (flet ((fail (control &rest args)
369            (ecase context
370              (:compile (apply #'compiler-error control args))
371              (:eval (error 'simple-program-error
372                            :format-control control
373                            :format-arguments args)))))
374     (lambda (definition)
375       (unless (proper-list-of-length-p definition 2)
376         (fail "malformed symbol/expansion pair: ~S" definition))
377       (destructuring-bind (name expansion) definition
378         (unless (symbolp name)
379           (fail "The local symbol macro name ~S is not a symbol." name))
380         (when (or (boundp name) (eq (info :variable :kind name) :macro))
381           (program-assert-symbol-home-package-unlocked
382            context name "binding ~A as a local symbol-macro"))
383         (let ((kind (info :variable :kind name)))
384           (when (member kind '(:special :constant :global))
385             (fail "Attempt to bind a ~(~A~) variable with SYMBOL-MACROLET: ~S"
386                   kind name)))
387         ;; A magical cons that MACROEXPAND-1 understands.
388         `(,name . (macro . ,expansion))))))
389
390 (defun funcall-in-symbol-macrolet-lexenv (definitions fun context)
391   (%funcall-in-foomacrolet-lexenv
392    (symbol-macrolet-definitionize-fun context)
393    :vars
394    definitions
395    fun))
396
397 (def-ir1-translator symbol-macrolet
398     ((macrobindings &body body) start next result)
399   #!+sb-doc
400   "SYMBOL-MACROLET ({(name expansion)}*) decl* form*
401
402 Define the NAMES as symbol macros with the given EXPANSIONS. Within the
403 body, references to a NAME will effectively be replaced with the EXPANSION."
404   (funcall-in-symbol-macrolet-lexenv
405    macrobindings
406    (lambda (&key vars)
407      (ir1-translate-locally body start next result :vars vars))
408    :compile))
409 \f
410 ;;;; %PRIMITIVE
411 ;;;;
412 ;;;; Uses of %PRIMITIVE are either expanded into Lisp code or turned
413 ;;;; into a funny function.
414
415 ;;; Carefully evaluate a list of forms, returning a list of the results.
416 (defun eval-info-args (args)
417   (declare (list args))
418   (handler-case (mapcar #'eval args)
419     (error (condition)
420       (compiler-error "Lisp error during evaluation of info args:~%~A"
421                       condition))))
422
423 ;;; Convert to the %%PRIMITIVE funny function. The first argument is
424 ;;; the template, the second is a list of the results of any
425 ;;; codegen-info args, and the remaining arguments are the runtime
426 ;;; arguments.
427 ;;;
428 ;;; We do various error checking now so that we don't bomb out with
429 ;;; a fatal error during IR2 conversion.
430 ;;;
431 ;;; KLUDGE: It's confusing having multiple names floating around for
432 ;;; nearly the same concept: PRIMITIVE, TEMPLATE, VOP. Now that CMU
433 ;;; CL's *PRIMITIVE-TRANSLATORS* stuff is gone, we could call
434 ;;; primitives VOPs, rename TEMPLATE to VOP-TEMPLATE, rename
435 ;;; BACKEND-TEMPLATE-NAMES to BACKEND-VOPS, and rename %PRIMITIVE to
436 ;;; VOP or %VOP.. -- WHN 2001-06-11
437 ;;; FIXME: Look at doing this ^, it doesn't look too hard actually.
438 (def-ir1-translator %primitive ((name &rest args) start next result)
439   (declare (type symbol name))
440   (let* ((template (or (gethash name *backend-template-names*)
441                        (bug "undefined primitive ~A" name)))
442          (required (length (template-arg-types template)))
443          (info (template-info-arg-count template))
444          (min (+ required info))
445          (nargs (length args)))
446     (if (template-more-args-type template)
447         (when (< nargs min)
448           (bug "Primitive ~A was called with ~R argument~:P, ~
449                 but wants at least ~R."
450                name
451                nargs
452                min))
453         (unless (= nargs min)
454           (bug "Primitive ~A was called with ~R argument~:P, ~
455                 but wants exactly ~R."
456                name
457                nargs
458                min)))
459
460     (when (template-conditional-p template)
461       (bug "%PRIMITIVE was used with a conditional template."))
462
463     (when (template-more-results-type template)
464       (bug "%PRIMITIVE was used with an unknown values template."))
465
466     (ir1-convert start next result
467                  `(%%primitive ',template
468                                ',(eval-info-args
469                                   (subseq args required min))
470                                ,@(subseq args 0 required)
471                                ,@(subseq args min)))))
472 \f
473 ;;;; QUOTE
474
475 (def-ir1-translator quote ((thing) start next result)
476   #!+sb-doc
477   "QUOTE value
478
479 Return VALUE without evaluating it."
480   (reference-constant start next result thing))
481 \f
482 (defun name-context ()
483   ;; Name of the outermost non-NIL BLOCK, or the source namestring
484   ;; of the source file.
485   (let ((context
486           (or (car (find-if (lambda (b)
487                               (let ((name (pop b)))
488                                 (and name
489                                      ;; KLUDGE: High debug adds this block on
490                                      ;; some platforms.
491                                      #!-unwind-to-frame-and-call-vop
492                                      (neq 'return-value-tag name)
493                                      ;; KLUDGE: CATCH produces blocks whose
494                                      ;; cleanup is :CATCH.
495                                      (neq :catch (cleanup-kind (entry-cleanup (pop b)))))))
496                             (lexenv-blocks *lexenv*) :from-end t))
497               *source-namestring*
498               (let ((p (or *compile-file-truename* *load-truename*)))
499                 (when p (namestring p))))))
500     (when context
501       (list :in context))))
502
503 ;;;; FUNCTION and NAMED-LAMBDA
504 (defun name-lambdalike (thing)
505   (case (car thing)
506     ((named-lambda)
507      (or (second thing)
508          `(lambda ,(third thing) ,(name-context))))
509     ((lambda)
510      `(lambda ,(second thing) ,@(name-context)))
511     ((lambda-with-lexenv)
512      ;; FIXME: Get the original DEFUN name here.
513      `(lambda ,(fifth thing)))
514     (otherwise
515      (compiler-error "Not a valid lambda expression:~%  ~S"
516                      thing))))
517
518 (defun fun-name-leaf (thing)
519   (if (consp thing)
520       (cond
521         ((member (car thing)
522                  '(lambda named-lambda lambda-with-lexenv))
523          (values (ir1-convert-lambdalike
524                   thing
525                   :debug-name (name-lambdalike thing))
526                  t))
527         ((legal-fun-name-p thing)
528          (values (find-lexically-apparent-fun
529                   thing "as the argument to FUNCTION")
530                  nil))
531         (t
532          (compiler-error "~S is not a legal function name." thing)))
533       (values (find-lexically-apparent-fun
534                thing "as the argument to FUNCTION")
535               nil)))
536
537 (def-ir1-translator %%allocate-closures ((&rest leaves) start next result)
538   (aver (eq result 'nil))
539   (let ((lambdas leaves))
540     (ir1-convert start next result `(%allocate-closures ',lambdas))
541     (let ((allocator (node-dest (ctran-next start))))
542       (dolist (lambda lambdas)
543         (setf (functional-allocator lambda) allocator)))))
544
545 (defmacro with-fun-name-leaf ((leaf thing start &key global-function) &body body)
546   `(multiple-value-bind (,leaf allocate-p)
547        (if ,global-function
548            (find-global-fun ,thing t)
549            (fun-name-leaf ,thing))
550      (if allocate-p
551          (let ((.new-start. (make-ctran)))
552            (ir1-convert ,start .new-start. nil `(%%allocate-closures ,leaf))
553            (let ((,start .new-start.))
554              ,@body))
555          (locally
556              ,@body))))
557
558 (def-ir1-translator function ((thing) start next result)
559   #!+sb-doc
560   "FUNCTION name
561
562 Return the lexically apparent definition of the function NAME. NAME may also
563 be a lambda expression."
564   (with-fun-name-leaf (leaf thing start)
565     (reference-leaf start next result leaf)))
566
567 ;;; Like FUNCTION, but ignores local definitions and inline
568 ;;; expansions, and doesn't nag about undefined functions.
569 ;;; Used for optimizing things like (FUNCALL 'FOO).
570 (def-ir1-translator global-function ((thing) start next result)
571   (with-fun-name-leaf (leaf thing start :global-function t)
572     (reference-leaf start next result leaf)))
573
574 (defun constant-global-fun-name (thing)
575   (let ((constantp (sb!xc:constantp thing)))
576     (when constantp
577       (let ((name (constant-form-value thing)))
578         (when (legal-fun-name-p name)
579           name)))))
580
581 (defun lvar-constant-global-fun-name (lvar)
582   (when (constant-lvar-p lvar)
583     (let ((name (lvar-value lvar)))
584       (when (legal-fun-name-p name)
585         name))))
586
587 (defun ensure-source-fun-form (source &optional give-up)
588   (let ((op (when (consp source) (car source))))
589     (cond ((eq op '%coerce-callable-to-fun)
590            (ensure-source-fun-form (second source)))
591           ((member op '(function global-function lambda named-lambda))
592            (values source nil))
593           (t
594            (let ((cname (constant-global-fun-name source)))
595              (if cname
596                  (values `(global-function ,cname) nil)
597                  (values `(%coerce-callable-to-fun ,source) give-up)))))))
598
599 (defun ensure-lvar-fun-form (lvar lvar-name &optional give-up)
600   (aver (and lvar-name (symbolp lvar-name)))
601   (if (csubtypep (lvar-type lvar) (specifier-type 'function))
602       lvar-name
603       (let ((cname (lvar-constant-global-fun-name lvar)))
604         (cond (cname
605                `(global-function ,cname))
606               (give-up
607                (give-up-ir1-transform give-up))
608               (t
609                `(%coerce-callable-to-fun ,lvar-name))))))
610 \f
611 ;;;; FUNCALL
612
613 ;;; FUNCALL is implemented on %FUNCALL, which can only call functions
614 ;;; (not symbols). %FUNCALL is used directly in some places where the
615 ;;; call should always be open-coded even if FUNCALL is :NOTINLINE.
616 (deftransform funcall ((function &rest args) * *)
617   (let ((arg-names (make-gensym-list (length args))))
618     `(lambda (function ,@arg-names)
619        (declare (ignorable function))
620        `(%funcall ,(ensure-lvar-fun-form function 'function) ,@arg-names))))
621
622 (def-ir1-translator %funcall ((function &rest args) start next result)
623   ;; MACROEXPAND so that (LAMBDA ...) forms arriving here don't get an
624   ;; extra cast inserted for them.
625   (let* ((function (%macroexpand function *lexenv*))
626          (op (when (consp function) (car function))))
627     (cond ((eq op 'function)
628            (compiler-destructuring-bind (thing) (cdr function)
629                function
630              (with-fun-name-leaf (leaf thing start)
631                (ir1-convert start next result `(,leaf ,@args)))))
632           ((eq op 'global-function)
633            (compiler-destructuring-bind (thing) (cdr function)
634                global-function
635              (with-fun-name-leaf (leaf thing start :global-function t)
636                (ir1-convert start next result `(,leaf ,@args)))))
637           (t
638            (let ((ctran (make-ctran))
639                  (fun-lvar (make-lvar)))
640              (ir1-convert start ctran fun-lvar `(the function ,function))
641              (ir1-convert-combination-args fun-lvar ctran next result args))))))
642
643 ;;; This source transform exists to reduce the amount of work for the
644 ;;; compiler. If the called function is a FUNCTION form, then convert
645 ;;; directly to %FUNCALL, instead of waiting around for type
646 ;;; inference.
647 (define-source-transform funcall (function &rest args)
648   `(%funcall ,(ensure-source-fun-form function) ,@args))
649
650 (deftransform %coerce-callable-to-fun ((thing) * *)
651   (ensure-lvar-fun-form thing 'thing "optimize away possible call to FDEFINITION at runtime"))
652
653 (define-source-transform %coerce-callable-to-fun (thing)
654   (ensure-source-fun-form thing t))
655 \f
656 ;;;; LET and LET*
657 ;;;;
658 ;;;; (LET and LET* can't be implemented as macros due to the fact that
659 ;;;; any pervasive declarations also affect the evaluation of the
660 ;;;; arguments.)
661
662 ;;; Given a list of binding specifiers in the style of LET, return:
663 ;;;  1. The list of var structures for the variables bound.
664 ;;;  2. The initial value form for each variable.
665 ;;;
666 ;;; The variable names are checked for legality and globally special
667 ;;; variables are marked as such. Context is the name of the form, for
668 ;;; error reporting purposes.
669 (declaim (ftype (function (list symbol) (values list list))
670                 extract-let-vars))
671 (defun extract-let-vars (bindings context)
672   (collect ((vars)
673             (vals)
674             (names))
675     (flet ((get-var (name)
676              (varify-lambda-arg name
677                                 (if (eq context 'let*)
678                                     nil
679                                     (names))
680                                 context)))
681       (dolist (spec bindings)
682         (cond ((atom spec)
683                (let ((var (get-var spec)))
684                  (vars var)
685                  (names spec)
686                  (vals nil)))
687               (t
688                (unless (proper-list-of-length-p spec 1 2)
689                  (compiler-error "The ~S binding spec ~S is malformed."
690                                  context
691                                  spec))
692                (let* ((name (first spec))
693                       (var (get-var name)))
694                  (vars var)
695                  (names name)
696                  (vals (second spec)))))))
697     (dolist (name (names))
698       (when (eq (info :variable :kind name) :macro)
699         (program-assert-symbol-home-package-unlocked
700          :compile name "lexically binding symbol-macro ~A")))
701     (values (vars) (vals))))
702
703 (def-ir1-translator let ((bindings &body body) start next result)
704   #!+sb-doc
705   "LET ({(var [value]) | var}*) declaration* form*
706
707 During evaluation of the FORMS, bind the VARS to the result of evaluating the
708 VALUE forms. The variables are bound in parallel after all of the VALUES forms
709 have been evaluated."
710   (cond ((null bindings)
711          (ir1-translate-locally body start next result))
712         ((listp bindings)
713          (multiple-value-bind (forms decls)
714              (parse-body body :doc-string-allowed nil)
715            (multiple-value-bind (vars values) (extract-let-vars bindings 'let)
716              (binding* ((ctran (make-ctran))
717                         (fun-lvar (make-lvar))
718                         ((next result)
719                          (processing-decls (decls vars nil next result
720                                                   post-binding-lexenv)
721                            (let ((fun (ir1-convert-lambda-body
722                                        forms
723                                        vars
724                                        :post-binding-lexenv post-binding-lexenv
725                                        :debug-name (debug-name 'let bindings))))
726                              (reference-leaf start ctran fun-lvar fun))
727                            (values next result))))
728                (ir1-convert-combination-args fun-lvar ctran next result values)))))
729         (t
730          (compiler-error "Malformed LET bindings: ~S." bindings))))
731
732 (def-ir1-translator let* ((bindings &body body)
733                           start next result)
734   #!+sb-doc
735   "LET* ({(var [value]) | var}*) declaration* form*
736
737 Similar to LET, but the variables are bound sequentially, allowing each VALUE
738 form to reference any of the previous VARS."
739   (if (listp bindings)
740       (multiple-value-bind (forms decls)
741           (parse-body body :doc-string-allowed nil)
742         (multiple-value-bind (vars values) (extract-let-vars bindings 'let*)
743           (processing-decls (decls vars nil next result post-binding-lexenv)
744             (ir1-convert-aux-bindings start
745                                       next
746                                       result
747                                       forms
748                                       vars
749                                       values
750                                       post-binding-lexenv))))
751       (compiler-error "Malformed LET* bindings: ~S." bindings)))
752
753 ;;; logic shared between IR1 translators for LOCALLY, MACROLET,
754 ;;; and SYMBOL-MACROLET
755 ;;;
756 ;;; Note that all these things need to preserve toplevel-formness,
757 ;;; but we don't need to worry about that within an IR1 translator,
758 ;;; since toplevel-formness is picked off by PROCESS-TOPLEVEL-FOO
759 ;;; forms before we hit the IR1 transform level.
760 (defun ir1-translate-locally (body start next result &key vars funs)
761   (declare (type ctran start next) (type (or lvar null) result)
762            (type list body))
763   (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
764     (processing-decls (decls vars funs next result)
765       (ir1-convert-progn-body start next result forms))))
766
767 (def-ir1-translator locally ((&body body) start next result)
768   #!+sb-doc
769   "LOCALLY declaration* form*
770
771 Sequentially evaluate the FORMS in a lexical environment where the
772 DECLARATIONS have effect. If LOCALLY is a top level form, then the FORMS are
773 also processed as top level forms."
774   (ir1-translate-locally body start next result))
775 \f
776 ;;;; FLET and LABELS
777
778 ;;; Given a list of local function specifications in the style of
779 ;;; FLET, return lists of the function names and of the lambdas which
780 ;;; are their definitions.
781 ;;;
782 ;;; The function names are checked for legality. CONTEXT is the name
783 ;;; of the form, for error reporting.
784 (declaim (ftype (function (list symbol) (values list list)) extract-flet-vars))
785 (defun extract-flet-vars (definitions context)
786   (collect ((names)
787             (defs))
788     (dolist (def definitions)
789       (when (or (atom def) (< (length def) 2))
790         (compiler-error "The ~S definition spec ~S is malformed." context def))
791
792       (let ((name (first def)))
793         (check-fun-name name)
794         (when (fboundp name)
795           (program-assert-symbol-home-package-unlocked
796            :compile name "binding ~A as a local function"))
797         (names name)
798         (multiple-value-bind (forms decls doc) (parse-body (cddr def))
799           (defs `(lambda ,(second def)
800                    ,@(when doc (list doc))
801                    ,@decls
802                    (block ,(fun-name-block-name name)
803                      . ,forms))))))
804     (values (names) (defs))))
805
806 (defun ir1-convert-fbindings (start next result funs body)
807   (let ((ctran (make-ctran))
808         (dx-p (find-if #'leaf-dynamic-extent funs)))
809     (when dx-p
810       (ctran-starts-block ctran)
811       (ctran-starts-block next))
812     (ir1-convert start ctran nil `(%%allocate-closures ,@funs))
813     (cond (dx-p
814            (let* ((dummy (make-ctran))
815                   (entry (make-entry))
816                   (cleanup (make-cleanup :kind :dynamic-extent
817                                          :mess-up entry
818                                          :info (list (node-dest
819                                                       (ctran-next start))))))
820              (push entry (lambda-entries (lexenv-lambda *lexenv*)))
821              (setf (entry-cleanup entry) cleanup)
822              (link-node-to-previous-ctran entry ctran)
823              (use-ctran entry dummy)
824
825              (let ((*lexenv* (make-lexenv :cleanup cleanup)))
826                (ir1-convert-progn-body dummy next result body))))
827           (t (ir1-convert-progn-body ctran next result body)))))
828
829 (def-ir1-translator flet ((definitions &body body)
830                           start next result)
831   #!+sb-doc
832   "FLET ({(name lambda-list declaration* form*)}*) declaration* body-form*
833
834 Evaluate the BODY-FORMS with local function definitions. The bindings do
835 not enclose the definitions; any use of NAME in the FORMS will refer to the
836 lexically apparent function definition in the enclosing environment."
837   (multiple-value-bind (forms decls)
838       (parse-body body :doc-string-allowed nil)
839     (multiple-value-bind (names defs)
840         (extract-flet-vars definitions 'flet)
841       (let ((fvars (mapcar (lambda (n d)
842                              (ir1-convert-lambda
843                               d :source-name n
844                                 :maybe-add-debug-catch t
845                                 :debug-name
846                                 (debug-name 'flet n t)))
847                            names defs)))
848         (processing-decls (decls nil fvars next result)
849           (let ((*lexenv* (make-lexenv :funs (pairlis names fvars))))
850             (ir1-convert-fbindings start next result fvars forms)))))))
851
852 (def-ir1-translator labels ((definitions &body body) start next result)
853   #!+sb-doc
854   "LABELS ({(name lambda-list declaration* form*)}*) declaration* body-form*
855
856 Evaluate the BODY-FORMS with local function definitions. The bindings enclose
857 the new definitions, so the defined functions can call themselves or each
858 other."
859   (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
860     (multiple-value-bind (names defs)
861         (extract-flet-vars definitions 'labels)
862       (let* (;; dummy LABELS functions, to be used as placeholders
863              ;; during construction of real LABELS functions
864              (placeholder-funs (mapcar (lambda (name)
865                                          (make-functional
866                                           :%source-name name
867                                           :%debug-name (debug-name
868                                                         'labels-placeholder
869                                                         name)))
870                                        names))
871              ;; (like PAIRLIS but guaranteed to preserve ordering:)
872              (placeholder-fenv (mapcar #'cons names placeholder-funs))
873              ;; the real LABELS functions, compiled in a LEXENV which
874              ;; includes the dummy LABELS functions
875              (real-funs
876               (let ((*lexenv* (make-lexenv :funs placeholder-fenv)))
877                 (mapcar (lambda (name def)
878                           (ir1-convert-lambda def
879                                               :source-name name
880                                               :maybe-add-debug-catch t
881                                               :debug-name (debug-name 'labels name t)))
882                         names defs))))
883
884         ;; Modify all the references to the dummy function leaves so
885         ;; that they point to the real function leaves.
886         (loop for real-fun in real-funs and
887               placeholder-cons in placeholder-fenv do
888               (substitute-leaf real-fun (cdr placeholder-cons))
889               (setf (cdr placeholder-cons) real-fun))
890
891         ;; Voila.
892         (processing-decls (decls nil real-funs next result)
893           (let ((*lexenv* (make-lexenv
894                            ;; Use a proper FENV here (not the
895                            ;; placeholder used earlier) so that if the
896                            ;; lexical environment is used for inline
897                            ;; expansion we'll get the right functions.
898                            :funs (pairlis names real-funs))))
899             (ir1-convert-fbindings start next result real-funs forms)))))))
900
901 \f
902 ;;;; the THE special operator, and friends
903
904 ;;; A logic shared among THE and TRULY-THE.
905 (defun the-in-policy (type value policy start next result)
906   (let ((type (if (ctype-p type) type
907                    (compiler-values-specifier-type type))))
908     (cond ((or (eq type *wild-type*)
909                (eq type *universal-type*)
910                (and (leaf-p value)
911                     (values-subtypep (make-single-value-type (leaf-type value))
912                                      type))
913                (and (sb!xc:constantp value)
914                     (ctypep (constant-form-value value)
915                             (single-value-type type))))
916            (ir1-convert start next result value))
917           (t (let ((value-ctran (make-ctran))
918                    (value-lvar (make-lvar)))
919                (ir1-convert start value-ctran value-lvar value)
920                (let ((cast (make-cast value-lvar type policy)))
921                  (link-node-to-previous-ctran cast value-ctran)
922                  (setf (lvar-dest value-lvar) cast)
923                  (use-continuation cast next result)))))))
924
925 ;;; Assert that FORM evaluates to the specified type (which may be a
926 ;;; VALUES type). TYPE may be a type specifier or (as a hack) a CTYPE.
927 (def-ir1-translator the ((value-type form) start next result)
928   #!+sb-doc
929   "Specifies that the values returned by FORM conform to the VALUE-TYPE.
930
931 CLHS specifies that the consequences are undefined if any result is
932 not of the declared type, but SBCL treats declarations as assertions
933 as long as SAFETY is at least 2, in which case incorrect type
934 information will result in a runtime type-error instead of leading to
935 eg. heap corruption. This is however expressly non-portable: use
936 CHECK-TYPE instead of THE to catch type-errors at runtime. THE is best
937 considered an optimization tool to inform the compiler about types it
938 is unable to derive from other declared types."
939   (the-in-policy value-type form (lexenv-policy *lexenv*) start next result))
940
941 ;;; This is like the THE special form, except that it believes
942 ;;; whatever you tell it. It will never generate a type check, but
943 ;;; will cause a warning if the compiler can prove the assertion is
944 ;;; wrong.
945 ;;;
946 ;;; For the benefit of code-walkers we also add a macro-expansion. (Using INFO
947 ;;; directly to get around safeguards for adding a macro-expansion for special
948 ;;; operator.) Because :FUNCTION :KIND remains :SPECIAL-FORM, the compiler
949 ;;; never uses the macro -- but manually calling its MACRO-FUNCTION or
950 ;;; MACROEXPANDing TRULY-THE forms does.
951 (def-ir1-translator truly-the ((value-type form) start next result)
952   #!+sb-doc
953   "Specifies that the values returned by FORM conform to the
954 VALUE-TYPE, and causes the compiler to trust this information
955 unconditionally.
956
957 Consequences are undefined if any result is not of the declared type
958 -- typical symptoms including memory corruptions. Use with great
959 care."
960   (the-in-policy value-type form '((type-check . 0)) start next result))
961
962 #-sb-xc-host
963 (setf (info :function :macro-function 'truly-the)
964       (lambda (whole env)
965         (declare (ignore env))
966         `(the ,@(cdr whole))))
967 \f
968 ;;;; SETQ
969
970 ;;; If there is a definition in LEXENV-VARS, just set that, otherwise
971 ;;; look at the global information. If the name is for a constant,
972 ;;; then error out.
973 (def-ir1-translator setq ((&whole source &rest things) start next result)
974   (let ((len (length things)))
975     (when (oddp len)
976       (compiler-error "odd number of args to SETQ: ~S" source))
977     (if (= len 2)
978         (let* ((name (first things))
979                (value-form (second things))
980                (leaf (or (lexenv-find name vars) (find-free-var name))))
981           (etypecase leaf
982             (leaf
983              (when (constant-p leaf)
984                (compiler-error "~S is a constant and thus can't be set." name))
985              (when (lambda-var-p leaf)
986                (let ((home-lambda (ctran-home-lambda-or-null start)))
987                  (when home-lambda
988                    (sset-adjoin leaf (lambda-calls-or-closes home-lambda))))
989                (when (lambda-var-ignorep leaf)
990                  ;; ANSI's definition of "Declaration IGNORE, IGNORABLE"
991                  ;; requires that this be a STYLE-WARNING, not a full warning.
992                  (compiler-style-warn
993                   "~S is being set even though it was declared to be ignored."
994                   name)))
995              (if (and (global-var-p leaf) (eq :unknown (global-var-kind leaf)))
996                  ;; For undefined variables go through SET, so that we can catch
997                  ;; constant modifications.
998                  (ir1-convert start next result `(set ',name ,value-form))
999                  (setq-var start next result leaf value-form)))
1000             (cons
1001              (aver (eq (car leaf) 'macro))
1002              ;; FIXME: [Free] type declaration. -- APD, 2002-01-26
1003              (ir1-convert start next result
1004                           `(setf ,(cdr leaf) ,(second things))))
1005             (heap-alien-info
1006              (ir1-convert start next result
1007                           `(%set-heap-alien ',leaf ,(second things))))))
1008         (collect ((sets))
1009           (do ((thing things (cddr thing)))
1010               ((endp thing)
1011                (ir1-convert-progn-body start next result (sets)))
1012             (sets `(setq ,(first thing) ,(second thing))))))))
1013
1014 ;;; This is kind of like REFERENCE-LEAF, but we generate a SET node.
1015 ;;; This should only need to be called in SETQ.
1016 (defun setq-var (start next result var value)
1017   (declare (type ctran start next) (type (or lvar null) result)
1018            (type basic-var var))
1019   (let ((dest-ctran (make-ctran))
1020         (dest-lvar (make-lvar))
1021         (type (or (lexenv-find var type-restrictions)
1022                   (leaf-type var))))
1023     (ir1-convert start dest-ctran dest-lvar `(the ,(type-specifier type)
1024                                                   ,value))
1025     (let ((res (make-set :var var :value dest-lvar)))
1026       (setf (lvar-dest dest-lvar) res)
1027       (setf (leaf-ever-used var) t)
1028       (push res (basic-var-sets var))
1029       (link-node-to-previous-ctran res dest-ctran)
1030       (use-continuation res next result))))
1031 \f
1032 ;;;; CATCH, THROW and UNWIND-PROTECT
1033
1034 ;;; We turn THROW into a MULTIPLE-VALUE-CALL of a magical function,
1035 ;;; since as as far as IR1 is concerned, it has no interesting
1036 ;;; properties other than receiving multiple-values.
1037 (def-ir1-translator throw ((tag result) start next result-lvar)
1038   #!+sb-doc
1039   "THROW tag form
1040
1041 Do a non-local exit, return the values of FORM from the CATCH whose tag is EQ
1042 to TAG."
1043   (ir1-convert start next result-lvar
1044                `(multiple-value-call #'%throw ,tag ,result)))
1045
1046 ;;; This is a special special form used to instantiate a cleanup as
1047 ;;; the current cleanup within the body. KIND is the kind of cleanup
1048 ;;; to make, and MESS-UP is a form that does the mess-up action. We
1049 ;;; make the MESS-UP be the USE of the MESS-UP form's continuation,
1050 ;;; and introduce the cleanup into the lexical environment. We
1051 ;;; back-patch the ENTRY-CLEANUP for the current cleanup to be the new
1052 ;;; cleanup, since this inner cleanup is the interesting one.
1053 (def-ir1-translator %within-cleanup
1054     ((kind mess-up &body body) start next result)
1055   (let ((dummy (make-ctran))
1056         (dummy2 (make-ctran)))
1057     (ir1-convert start dummy nil mess-up)
1058     (let* ((mess-node (ctran-use dummy))
1059            (cleanup (make-cleanup :kind kind
1060                                   :mess-up mess-node))
1061            (old-cup (lexenv-cleanup *lexenv*))
1062            (*lexenv* (make-lexenv :cleanup cleanup)))
1063       (setf (entry-cleanup (cleanup-mess-up old-cup)) cleanup)
1064       (ir1-convert dummy dummy2 nil '(%cleanup-point))
1065       (ir1-convert-progn-body dummy2 next result body))))
1066
1067 ;;; This is a special special form that makes an "escape function"
1068 ;;; which returns unknown values from named block. We convert the
1069 ;;; function, set its kind to :ESCAPE, and then reference it. The
1070 ;;; :ESCAPE kind indicates that this function's purpose is to
1071 ;;; represent a non-local control transfer, and that it might not
1072 ;;; actually have to be compiled.
1073 ;;;
1074 ;;; Note that environment analysis replaces references to escape
1075 ;;; functions with references to the corresponding NLX-INFO structure.
1076 (def-ir1-translator %escape-fun ((tag) start next result)
1077   (let ((fun (let ((*allow-instrumenting* nil))
1078                (ir1-convert-lambda
1079                 `(lambda ()
1080                    (return-from ,tag (%unknown-values)))
1081                 :debug-name (debug-name 'escape-fun tag))))
1082         (ctran (make-ctran)))
1083     (setf (functional-kind fun) :escape)
1084     (ir1-convert start ctran nil `(%%allocate-closures ,fun))
1085     (reference-leaf ctran next result fun)))
1086
1087 ;;; Yet another special special form. This one looks up a local
1088 ;;; function and smashes it to a :CLEANUP function, as well as
1089 ;;; referencing it.
1090 (def-ir1-translator %cleanup-fun ((name) start next result)
1091   ;; FIXME: Should this not be :TEST #'EQUAL? What happens to
1092   ;; (SETF FOO) here?
1093   (let ((fun (lexenv-find name funs)))
1094     (aver (lambda-p fun))
1095     (setf (functional-kind fun) :cleanup)
1096     (reference-leaf start next result fun)))
1097
1098 (def-ir1-translator catch ((tag &body body) start next result)
1099   #!+sb-doc
1100   "CATCH tag form*
1101
1102 Evaluate TAG and instantiate it as a catcher while the body forms are
1103 evaluated in an implicit PROGN. If a THROW is done to TAG within the dynamic
1104 scope of the body, then control will be transferred to the end of the body and
1105 the thrown values will be returned."
1106   ;; We represent the possibility of the control transfer by making an
1107   ;; "escape function" that does a lexical exit, and instantiate the
1108   ;; cleanup using %WITHIN-CLEANUP.
1109   (ir1-convert
1110    start next result
1111    (with-unique-names (exit-block)
1112      `(block ,exit-block
1113         (%within-cleanup
1114          :catch (%catch (%escape-fun ,exit-block) ,tag)
1115          ,@body)))))
1116
1117 (def-ir1-translator unwind-protect
1118     ((protected &body cleanup) start next result)
1119   #!+sb-doc
1120   "UNWIND-PROTECT protected cleanup*
1121
1122 Evaluate the form PROTECTED, returning its values. The CLEANUP forms are
1123 evaluated whenever the dynamic scope of the PROTECTED form is exited (either
1124 due to normal completion or a non-local exit such as THROW)."
1125   ;; UNWIND-PROTECT is similar to CATCH, but hairier. We make the
1126   ;; cleanup forms into a local function so that they can be referenced
1127   ;; both in the case where we are unwound and in any local exits. We
1128   ;; use %CLEANUP-FUN on this to indicate that reference by
1129   ;; %UNWIND-PROTECT isn't "real", and thus doesn't cause creation of
1130   ;; an XEP.
1131   (ir1-convert
1132    start next result
1133    (with-unique-names (cleanup-fun drop-thru-tag exit-tag next start count)
1134      `(flet ((,cleanup-fun ()
1135                ,@cleanup
1136                nil))
1137         ;; FIXME: If we ever get DYNAMIC-EXTENT working, then
1138         ;; ,CLEANUP-FUN should probably be declared DYNAMIC-EXTENT,
1139         ;; and something can be done to make %ESCAPE-FUN have
1140         ;; dynamic extent too.
1141         (declare (dynamic-extent #',cleanup-fun))
1142         (block ,drop-thru-tag
1143           (multiple-value-bind (,next ,start ,count)
1144               (block ,exit-tag
1145                 (%within-cleanup
1146                     :unwind-protect
1147                     (%unwind-protect (%escape-fun ,exit-tag)
1148                                      (%cleanup-fun ,cleanup-fun))
1149                   (return-from ,drop-thru-tag ,protected)))
1150             (declare (optimize (insert-debug-catch 0)))
1151             (,cleanup-fun)
1152             (%continue-unwind ,next ,start ,count)))))))
1153 \f
1154 ;;;; multiple-value stuff
1155
1156 (def-ir1-translator multiple-value-call ((fun &rest args) start next result)
1157   #!+sb-doc
1158   "MULTIPLE-VALUE-CALL function values-form*
1159
1160 Call FUNCTION, passing all the values of each VALUES-FORM as arguments,
1161 values from the first VALUES-FORM making up the first argument, etc."
1162   (let* ((ctran (make-ctran))
1163          (fun-lvar (make-lvar))
1164          (node (if args
1165                    ;; If there are arguments, MULTIPLE-VALUE-CALL
1166                    ;; turns into an MV-COMBINATION.
1167                    (make-mv-combination fun-lvar)
1168                    ;; If there are no arguments, then we convert to a
1169                    ;; normal combination, ensuring that a MV-COMBINATION
1170                    ;; always has at least one argument. This can be
1171                    ;; regarded as an optimization, but it is more
1172                    ;; important for simplifying compilation of
1173                    ;; MV-COMBINATIONS.
1174                    (make-combination fun-lvar))))
1175     (ir1-convert start ctran fun-lvar (ensure-source-fun-form fun))
1176     (setf (lvar-dest fun-lvar) node)
1177     (collect ((arg-lvars))
1178       (let ((this-start ctran))
1179         (dolist (arg args)
1180           (let ((this-ctran (make-ctran))
1181                 (this-lvar (make-lvar node)))
1182             (ir1-convert this-start this-ctran this-lvar arg)
1183             (setq this-start this-ctran)
1184             (arg-lvars this-lvar)))
1185         (link-node-to-previous-ctran node this-start)
1186         (use-continuation node next result)
1187         (setf (basic-combination-args node) (arg-lvars))))))
1188
1189 (def-ir1-translator multiple-value-prog1
1190     ((values-form &rest forms) start next result)
1191   #!+sb-doc
1192   "MULTIPLE-VALUE-PROG1 values-form form*
1193
1194 Evaluate VALUES-FORM and then the FORMS, but return all the values of
1195 VALUES-FORM."
1196   (let ((dummy (make-ctran)))
1197     (ctran-starts-block dummy)
1198     (ir1-convert start dummy result values-form)
1199     (ir1-convert-progn-body dummy next nil forms)))
1200 \f
1201 ;;;; interface to defining macros
1202
1203 ;;; Old CMUCL comment:
1204 ;;;
1205 ;;;   Return a new source path with any stuff intervening between the
1206 ;;;   current path and the first form beginning with NAME stripped
1207 ;;;   off.  This is used to hide the guts of DEFmumble macros to
1208 ;;;   prevent annoying error messages.
1209 ;;;
1210 ;;; Now that we have implementations of DEFmumble macros in terms of
1211 ;;; EVAL-WHEN, this function is no longer used.  However, it might be
1212 ;;; worth figuring out why it was used, and maybe doing analogous
1213 ;;; munging to the functions created in the expanders for the macros.
1214 (defun revert-source-path (name)
1215   (do ((path *current-path* (cdr path)))
1216       ((null path) *current-path*)
1217     (let ((first (first path)))
1218       (when (or (eq first name)
1219                 (eq first 'original-source-start))
1220         (return path)))))