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