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