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