b8f657c8abddb5e406951d6f70ab080e7a305f4d
[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 top
199 ;;; level forms are picked off and handled by PROCESS-TOPLEVEL-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 ;;; Convert to the %%PRIMITIVE funny function. The first argument is
327 ;;; the template, the second is a list of the results of any
328 ;;; codegen-info args, and the remaining arguments are the runtime
329 ;;; arguments.
330 ;;;
331 ;;; We do various error checking now so that we don't bomb out with
332 ;;; a fatal error during IR2 conversion.
333 ;;;
334 ;;; KLUDGE: It's confusing having multiple names floating around for
335 ;;; nearly the same concept: PRIMITIVE, TEMPLATE, VOP. Now that CMU
336 ;;; CL's *PRIMITIVE-TRANSLATORS* stuff is gone, we could call
337 ;;; primitives VOPs, rename TEMPLATE to VOP-TEMPLATE, rename
338 ;;; BACKEND-TEMPLATE-NAMES to BACKEND-VOPS, and rename %PRIMITIVE to
339 ;;; VOP or %VOP.. -- WHN 2001-06-11
340 ;;; FIXME: Look at doing this ^, it doesn't look too hard actually.
341 (def-ir1-translator %primitive ((name &rest args) start cont)
342   (unless (symbolp name)
343     (compiler-error "internal error: Primitive name ~S is not a symbol." name))
344   (let* ((template (or (gethash name *backend-template-names*)
345                        (compiler-error
346                         "internal error: Primitive name ~A is not defined."
347                         name)))
348          (required (length (template-arg-types template)))
349          (info (template-info-arg-count template))
350          (min (+ required info))
351          (nargs (length args)))
352     (if (template-more-args-type template)
353         (when (< nargs min)
354           (compiler-error "internal error: Primitive ~A was called ~
355                            with ~R argument~:P, ~
356                            but wants at least ~R."
357                           name
358                           nargs
359                           min))
360         (unless (= nargs min)
361           (compiler-error "internal error: Primitive ~A was called ~
362                            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
401                          cont
402                          (ir1-convert-lambda thing
403                                              :debug-name (debug-namify
404                                                           "#'~S" thing))))
405         ((setf)
406          (let ((var (find-lexically-apparent-function
407                      thing "as the argument to FUNCTION")))
408            (reference-leaf start cont var)))
409         ((instance-lambda)
410          (let ((res (ir1-convert-lambda `(lambda ,@(cdr thing))
411                                         :debug-name (debug-namify "#'~S"
412                                                                   thing))))
413            (setf (getf (functional-plist res) :fin-function) t)
414            (reference-leaf start cont res)))
415         (t
416          (compiler-error "~S is not a legal function name." thing)))
417       (let ((var (find-lexically-apparent-function
418                   thing "as the argument to FUNCTION")))
419         (reference-leaf start cont var))))
420 \f
421 ;;;; FUNCALL
422
423 ;;; FUNCALL is implemented on %FUNCALL, which can only call functions
424 ;;; (not symbols). %FUNCALL is used directly in some places where the
425 ;;; call should always be open-coded even if FUNCALL is :NOTINLINE.
426 (deftransform funcall ((function &rest args) * * :when :both)
427   (let ((arg-names (make-gensym-list (length args))))
428     `(lambda (function ,@arg-names)
429        (%funcall ,(if (csubtypep (continuation-type function)
430                                  (specifier-type 'function))
431                       'function
432                       '(%coerce-callable-to-fun function))
433                  ,@arg-names))))
434
435 (def-ir1-translator %funcall ((function &rest args) start cont)
436   (let ((fun-cont (make-continuation)))
437     (ir1-convert start fun-cont function)
438     (assert-continuation-type fun-cont (specifier-type 'function))
439     (ir1-convert-combination-args fun-cont cont args)))
440
441 ;;; This source transform exists to reduce the amount of work for the
442 ;;; compiler. If the called function is a FUNCTION form, then convert
443 ;;; directly to %FUNCALL, instead of waiting around for type
444 ;;; inference.
445 (def-source-transform funcall (function &rest args)
446   (if (and (consp function) (eq (car function) 'function))
447       `(%funcall ,function ,@args)
448       (values nil t)))
449
450 (deftransform %coerce-callable-to-fun ((thing) (function) *
451                                        :when :both
452                                        :important t)
453   "optimize away possible call to FDEFINITION at runtime"
454   'thing)
455 \f
456 ;;;; LET and LET*
457 ;;;;
458 ;;;; (LET and LET* can't be implemented as macros due to the fact that
459 ;;;; any pervasive declarations also affect the evaluation of the
460 ;;;; arguments.)
461
462 ;;; Given a list of binding specifiers in the style of Let, return:
463 ;;;  1. The list of var structures for the variables bound.
464 ;;;  2. The initial value form for each variable.
465 ;;;
466 ;;; The variable names are checked for legality and globally special
467 ;;; variables are marked as such. Context is the name of the form, for
468 ;;; error reporting purposes.
469 (declaim (ftype (function (list symbol) (values list list list))
470                 extract-let-variables))
471 (defun extract-let-variables (bindings context)
472   (collect ((vars)
473             (vals)
474             (names))
475     (flet ((get-var (name)
476              (varify-lambda-arg name
477                                 (if (eq context 'let*)
478                                     nil
479                                     (names)))))
480       (dolist (spec bindings)
481         (cond ((atom spec)
482                (let ((var (get-var spec)))
483                  (vars var)
484                  (names (cons spec var))
485                  (vals nil)))
486               (t
487                (unless (proper-list-of-length-p spec 1 2)
488                  (compiler-error "The ~S binding spec ~S is malformed."
489                                  context
490                                  spec))
491                (let* ((name (first spec))
492                       (var (get-var name)))
493                  (vars var)
494                  (names name)
495                  (vals (second spec)))))))
496
497     (values (vars) (vals) (names))))
498
499 (def-ir1-translator let ((bindings &body body)
500                          start cont)
501   #!+sb-doc
502   "LET ({(Var [Value]) | Var}*) Declaration* Form*
503   During evaluation of the Forms, bind the Vars to the result of evaluating the
504   Value forms. The variables are bound in parallel after all of the Values are
505   evaluated."
506   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
507     (multiple-value-bind (vars values) (extract-let-variables bindings 'let)
508       (let* ((*lexenv* (process-decls decls vars nil cont))
509              (fun-cont (make-continuation))
510              (fun (ir1-convert-lambda-body
511                    forms vars :debug-name (debug-namify "LET ~S" bindings))))
512         (reference-leaf start fun-cont fun)
513         (ir1-convert-combination-args fun-cont cont values)))))
514
515 (def-ir1-translator let* ((bindings &body body)
516                           start cont)
517   #!+sb-doc
518   "LET* ({(Var [Value]) | Var}*) Declaration* Form*
519   Similar to LET, but the variables are bound sequentially, allowing each Value
520   form to reference any of the previous Vars."
521   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
522     (multiple-value-bind (vars values) (extract-let-variables bindings 'let*)
523       (let ((*lexenv* (process-decls decls vars nil cont)))
524         (ir1-convert-aux-bindings start cont forms vars values)))))
525
526 ;;; logic shared between IR1 translators for LOCALLY, MACROLET,
527 ;;; and SYMBOL-MACROLET
528 ;;;
529 ;;; Note that all these things need to preserve toplevel-formness,
530 ;;; but we don't need to worry about that within an IR1 translator,
531 ;;; since toplevel-formness is picked off by PROCESS-TOPLEVEL-FOO
532 ;;; forms before we hit the IR1 transform level.
533 (defun ir1-translate-locally (body start cont)
534   (declare (type list body) (type continuation start cont))
535   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
536     (let ((*lexenv* (process-decls decls nil nil cont)))
537       (ir1-convert-aux-bindings start cont forms nil nil))))
538
539 (def-ir1-translator locally ((&body body) start cont)
540   #!+sb-doc
541   "LOCALLY Declaration* Form*
542   Sequentially evaluate the Forms in a lexical environment where the
543   the Declarations have effect. If LOCALLY is a top level form, then
544   the Forms are also processed as top level forms."
545   (ir1-translate-locally body start cont))
546 \f
547 ;;;; FLET and LABELS
548
549 ;;; Given a list of local function specifications in the style of
550 ;;; FLET, return lists of the function names and of the lambdas which
551 ;;; are their definitions.
552 ;;;
553 ;;; The function names are checked for legality. CONTEXT is the name
554 ;;; of the form, for error reporting.
555 (declaim (ftype (function (list symbol) (values list list))
556                 extract-flet-variables))
557 (defun extract-flet-variables (definitions context)
558   (collect ((names)
559             (defs))
560     (dolist (def definitions)
561       (when (or (atom def) (< (length def) 2))
562         (compiler-error "The ~S definition spec ~S is malformed." context def))
563
564       (let ((name (first def)))
565         (check-fun-name name)
566         (names name)
567         (multiple-value-bind (forms decls) (sb!sys:parse-body (cddr def))
568           (defs `(lambda ,(second def)
569                    ,@decls
570                    (block ,(fun-name-block-name name)
571                      . ,forms))))))
572     (values (names) (defs))))
573
574 (def-ir1-translator flet ((definitions &body body)
575                           start cont)
576   #!+sb-doc
577   "FLET ({(Name Lambda-List Declaration* Form*)}*) Declaration* Body-Form*
578   Evaluate the Body-Forms with some local function definitions. The bindings
579   do not enclose the definitions; any use of Name in the Forms will refer to
580   the lexically apparent function definition in the enclosing environment."
581   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
582     (multiple-value-bind (names defs)
583         (extract-flet-variables definitions 'flet)
584       (let* ((fvars (mapcar (lambda (n d)
585                               (ir1-convert-lambda d
586                                                   :source-name n
587                                                   :debug-name (debug-namify
588                                                                "FLET ~S" n)))
589                             names defs))
590              (*lexenv* (make-lexenv
591                         :default (process-decls decls nil fvars cont)
592                         :functions (pairlis names fvars))))
593         (ir1-convert-progn-body start cont forms)))))
594
595 (def-ir1-translator labels ((definitions &body body) start cont)
596   #!+sb-doc
597   "LABELS ({(Name Lambda-List Declaration* Form*)}*) Declaration* Body-Form*
598   Evaluate the Body-Forms with some local function definitions. The bindings
599   enclose the new definitions, so the defined functions can call themselves or
600   each other."
601   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
602     (multiple-value-bind (names defs)
603         (extract-flet-variables definitions 'labels)
604       (let* (;; dummy LABELS functions, to be used as placeholders
605              ;; during construction of real LABELS functions
606              (placeholder-funs (mapcar (lambda (name)
607                                          (make-functional
608                                           :%source-name name
609                                           :%debug-name (debug-namify
610                                                         "LABELS placeholder ~S"
611                                                         name)))
612                                        names))
613              ;; (like PAIRLIS but guaranteed to preserve ordering:)
614              (placeholder-fenv (mapcar #'cons names placeholder-funs))
615              ;; the real LABELS functions, compiled in a LEXENV which
616              ;; includes the dummy LABELS functions
617              (real-funs
618               (let ((*lexenv* (make-lexenv
619                                :functions placeholder-fenv)))
620                 (mapcar (lambda (name def)
621                           (ir1-convert-lambda def
622                                               :source-name name
623                                               :debug-name (debug-namify
624                                                            "LABELS ~S" name)))
625                         names defs))))
626
627         ;; Modify all the references to the dummy function leaves so
628         ;; that they point to the real function leaves.
629         (loop for real-fun in real-funs and
630               placeholder-cons in placeholder-fenv do
631               (substitute-leaf real-fun (cdr placeholder-cons))
632               (setf (cdr placeholder-cons) real-fun))
633
634         ;; Voila.
635         (let ((*lexenv* (make-lexenv
636                          :default (process-decls decls nil real-funs cont)
637                          ;; Use a proper FENV here (not the
638                          ;; placeholder used earlier) so that if the
639                          ;; lexical environment is used for inline
640                          ;; expansion we'll get the right functions.
641                          :functions (pairlis names real-funs))))
642           (ir1-convert-progn-body start cont forms))))))
643 \f
644 ;;;; the THE special operator, and friends
645
646 ;;; Do stuff to recognize a THE or VALUES declaration. CONT is the
647 ;;; continuation that the assertion applies to, TYPE is the type
648 ;;; specifier and LEXENV is the current lexical environment. NAME is
649 ;;; the name of the declaration we are doing, for use in error
650 ;;; messages.
651 ;;;
652 ;;; This is somewhat involved, since a type assertion may only be made
653 ;;; on a continuation, not on a node. We can't just set the
654 ;;; continuation asserted type and let it go at that, since there may
655 ;;; be parallel THE's for the same continuation, i.e.
656 ;;;     (if ...
657 ;;;      (the foo ...)
658 ;;;      (the bar ...))
659 ;;;
660 ;;; In this case, our representation can do no better than the union
661 ;;; of these assertions. And if there is a branch with no assertion,
662 ;;; we have nothing at all. We really need to recognize scoping, since
663 ;;; we need to be able to discern between parallel assertions (which
664 ;;; we union) and nested ones (which we intersect).
665 ;;;
666 ;;; We represent the scoping by throwing our innermost (intersected)
667 ;;; assertion on CONT into the TYPE-RESTRICTIONS. As we go down, we
668 ;;; intersect our assertions together. If CONT has no uses yet, we
669 ;;; have not yet bottomed out on the first COND branch; in this case
670 ;;; we optimistically assume that this type will be the one we end up
671 ;;; with, and set the ASSERTED-TYPE to it. We can never get better
672 ;;; than the type that we have the first time we bottom out. Later
673 ;;; THE's (or the absence thereof) can only weaken this result.
674 ;;;
675 ;;; We make this work by getting USE-CONTINUATION to do the unioning
676 ;;; across COND branches. We can't do it here, since we don't know how
677 ;;; many branches there are going to be.
678 (defun do-the-stuff (type cont lexenv name)
679   (declare (type continuation cont) (type lexenv lexenv))
680   (let* ((ctype (values-specifier-type type))
681          (old-type (or (lexenv-find cont type-restrictions)
682                        *wild-type*))
683          (intersects (values-types-equal-or-intersect old-type ctype))
684          (int (values-type-intersection old-type ctype))
685          (new (if intersects int old-type)))
686     (when (null (find-uses cont))
687       (setf (continuation-asserted-type cont) new))
688     (when (and (not intersects)
689                (not (policy *lexenv*
690                             (= inhibit-warnings 3)))) ;FIXME: really OK to suppress?
691       (compiler-warning
692        "The type ~S in ~S declaration conflicts with an enclosing assertion:~%   ~S"
693        (type-specifier ctype)
694        name
695        (type-specifier old-type)))
696     (make-lexenv :type-restrictions `((,cont . ,new))
697                  :default lexenv)))
698
699 ;;; Assert that FORM evaluates to the specified type (which may be a
700 ;;; VALUES type).
701 ;;;
702 ;;; FIXME: In a version of CMU CL that I used at Cadabra ca. 20000101,
703 ;;; this didn't seem to expand into an assertion, at least for ALIEN
704 ;;; values. Check that SBCL doesn't have this problem.
705 (def-ir1-translator the ((type value) start cont)
706   (let ((*lexenv* (do-the-stuff type cont *lexenv* 'the)))
707     (ir1-convert start cont value)))
708
709 ;;; This is like the THE special form, except that it believes
710 ;;; whatever you tell it. It will never generate a type check, but
711 ;;; will cause a warning if the compiler can prove the assertion is
712 ;;; wrong.
713 ;;;
714 ;;; Since the CONTINUATION-DERIVED-TYPE is computed as the union of
715 ;;; its uses's types, setting it won't work. Instead we must intersect
716 ;;; the type with the uses's DERIVED-TYPE.
717 (def-ir1-translator truly-the ((type value) start cont)
718   #!+sb-doc
719   (declare (inline member))
720   (let ((type (values-specifier-type type))
721         (old (find-uses cont)))
722     (ir1-convert start cont value)
723     (do-uses (use cont)
724       (unless (member use old :test #'eq)
725         (derive-node-type use type)))))
726 \f
727 ;;;; SETQ
728
729 ;;; If there is a definition in LEXENV-VARIABLES, just set that,
730 ;;; otherwise look at the global information. If the name is for a
731 ;;; constant, then error out.
732 (def-ir1-translator setq ((&whole source &rest things) start cont)
733   (let ((len (length things)))
734     (when (oddp len)
735       (compiler-error "odd number of args to SETQ: ~S" source))
736     (if (= len 2)
737         (let* ((name (first things))
738                (leaf (or (lexenv-find name variables)
739                          (find-free-variable name))))
740           (etypecase leaf
741             (leaf
742              (when (constant-p leaf)
743                (compiler-error "~S is a constant and thus can't be set." name))
744              (when (and (lambda-var-p leaf)
745                         (lambda-var-ignorep leaf))
746                ;; ANSI's definition of "Declaration IGNORE, IGNORABLE"
747                ;; requires that this be a STYLE-WARNING, not a full warning.
748                (compiler-style-warning
749                 "~S is being set even though it was declared to be ignored."
750                 name))
751              (set-variable start cont leaf (second things)))
752             (cons
753              (aver (eq (car leaf) 'MACRO))
754              (ir1-convert start cont `(setf ,(cdr leaf) ,(second things))))
755             (heap-alien-info
756              (ir1-convert start cont
757                           `(%set-heap-alien ',leaf ,(second things))))))
758         (collect ((sets))
759           (do ((thing things (cddr thing)))
760               ((endp thing)
761                (ir1-convert-progn-body start cont (sets)))
762             (sets `(setq ,(first thing) ,(second thing))))))))
763
764 ;;; This is kind of like REFERENCE-LEAF, but we generate a SET node.
765 ;;; This should only need to be called in SETQ.
766 (defun set-variable (start cont var value)
767   (declare (type continuation start cont) (type basic-var var))
768   (let ((dest (make-continuation)))
769     (setf (continuation-asserted-type dest) (leaf-type var))
770     (ir1-convert start dest value)
771     (let ((res (make-set :var var :value dest)))
772       (setf (continuation-dest dest) res)
773       (setf (leaf-ever-used var) t)
774       (push res (basic-var-sets var))
775       (prev-link res dest)
776       (use-continuation res cont))))
777 \f
778 ;;;; CATCH, THROW and UNWIND-PROTECT
779
780 ;;; We turn THROW into a multiple-value-call of a magical function,
781 ;;; since as as far as IR1 is concerned, it has no interesting
782 ;;; properties other than receiving multiple-values.
783 (def-ir1-translator throw ((tag result) start cont)
784   #!+sb-doc
785   "Throw Tag Form
786   Do a non-local exit, return the values of Form from the CATCH whose tag
787   evaluates to the same thing as Tag."
788   (ir1-convert start cont
789                `(multiple-value-call #'%throw ,tag ,result)))
790
791 ;;; This is a special special form used to instantiate a cleanup as
792 ;;; the current cleanup within the body. KIND is a the kind of cleanup
793 ;;; to make, and MESS-UP is a form that does the mess-up action. We
794 ;;; make the MESS-UP be the USE of the MESS-UP form's continuation,
795 ;;; and introduce the cleanup into the lexical environment. We
796 ;;; back-patch the ENTRY-CLEANUP for the current cleanup to be the new
797 ;;; cleanup, since this inner cleanup is the interesting one.
798 (def-ir1-translator %within-cleanup ((kind mess-up &body body) start cont)
799   (let ((dummy (make-continuation))
800         (dummy2 (make-continuation)))
801     (ir1-convert start dummy mess-up)
802     (let* ((mess-node (continuation-use dummy))
803            (cleanup (make-cleanup :kind kind
804                                   :mess-up mess-node))
805            (old-cup (lexenv-cleanup *lexenv*))
806            (*lexenv* (make-lexenv :cleanup cleanup)))
807       (setf (entry-cleanup (cleanup-mess-up old-cup)) cleanup)
808       (ir1-convert dummy dummy2 '(%cleanup-point))
809       (ir1-convert-progn-body dummy2 cont body))))
810
811 ;;; This is a special special form that makes an "escape function"
812 ;;; which returns unknown values from named block. We convert the
813 ;;; function, set its kind to :ESCAPE, and then reference it. The
814 ;;; :ESCAPE kind indicates that this function's purpose is to
815 ;;; represent a non-local control transfer, and that it might not
816 ;;; actually have to be compiled.
817 ;;;
818 ;;; Note that environment analysis replaces references to escape
819 ;;; functions with references to the corresponding NLX-INFO structure.
820 (def-ir1-translator %escape-function ((tag) start cont)
821   (let ((fun (ir1-convert-lambda
822               `(lambda ()
823                  (return-from ,tag (%unknown-values)))
824               :debug-name (debug-namify "escape function for ~S" tag))))
825     (setf (functional-kind fun) :escape)
826     (reference-leaf start cont fun)))
827
828 ;;; Yet another special special form. This one looks up a local
829 ;;; function and smashes it to a :CLEANUP function, as well as
830 ;;; referencing it.
831 (def-ir1-translator %cleanup-function ((name) start cont)
832   (let ((fun (lexenv-find name functions)))
833     (aver (lambda-p fun))
834     (setf (functional-kind fun) :cleanup)
835     (reference-leaf start cont fun)))
836
837 ;;; We represent the possibility of the control transfer by making an
838 ;;; "escape function" that does a lexical exit, and instantiate the
839 ;;; cleanup using %WITHIN-CLEANUP.
840 (def-ir1-translator catch ((tag &body body) start cont)
841   #!+sb-doc
842   "Catch Tag Form*
843   Evaluates Tag and instantiates it as a catcher while the body forms are
844   evaluated in an implicit PROGN. If a THROW is done to Tag within the dynamic
845   scope of the body, then control will be transferred to the end of the body
846   and the thrown values will be returned."
847   (ir1-convert
848    start cont
849    (let ((exit-block (gensym "EXIT-BLOCK-")))
850      `(block ,exit-block
851         (%within-cleanup
852             :catch
853             (%catch (%escape-function ,exit-block) ,tag)
854           ,@body)))))
855
856 ;;; UNWIND-PROTECT is similar to CATCH, but more hairy. We make the
857 ;;; cleanup forms into a local function so that they can be referenced
858 ;;; both in the case where we are unwound and in any local exits. We
859 ;;; use %CLEANUP-FUNCTION on this to indicate that reference by
860 ;;; %UNWIND-PROTECT ISN'T "real", and thus doesn't cause creation of
861 ;;; an XEP.
862 (def-ir1-translator unwind-protect ((protected &body cleanup) start cont)
863   #!+sb-doc
864   "Unwind-Protect Protected Cleanup*
865   Evaluate the form Protected, returning its values. The cleanup forms are
866   evaluated whenever the dynamic scope of the Protected form is exited (either
867   due to normal completion or a non-local exit such as THROW)."
868   (ir1-convert
869    start cont
870    (let ((cleanup-fun (gensym "CLEANUP-FUN-"))
871          (drop-thru-tag (gensym "DROP-THRU-TAG-"))
872          (exit-tag (gensym "EXIT-TAG-"))
873          (next (gensym "NEXT"))
874          (start (gensym "START"))
875          (count (gensym "COUNT")))
876      `(flet ((,cleanup-fun () ,@cleanup nil))
877         ;; FIXME: If we ever get DYNAMIC-EXTENT working, then
878         ;; ,CLEANUP-FUN should probably be declared DYNAMIC-EXTENT,
879         ;; and something can be done to make %ESCAPE-FUNCTION have
880         ;; dynamic extent too.
881         (block ,drop-thru-tag
882           (multiple-value-bind (,next ,start ,count)
883               (block ,exit-tag
884                 (%within-cleanup
885                     :unwind-protect
886                     (%unwind-protect (%escape-function ,exit-tag)
887                                      (%cleanup-function ,cleanup-fun))
888                   (return-from ,drop-thru-tag ,protected)))
889             (,cleanup-fun)
890             (%continue-unwind ,next ,start ,count)))))))
891 \f
892 ;;;; multiple-value stuff
893
894 ;;; If there are arguments, MULTIPLE-VALUE-CALL turns into an
895 ;;; MV-COMBINATION.
896 ;;;
897 ;;; If there are no arguments, then we convert to a normal
898 ;;; combination, ensuring that a MV-COMBINATION always has at least
899 ;;; one argument. This can be regarded as an optimization, but it is
900 ;;; more important for simplifying compilation of MV-COMBINATIONS.
901 (def-ir1-translator multiple-value-call ((fun &rest args) start cont)
902   #!+sb-doc
903   "MULTIPLE-VALUE-CALL Function Values-Form*
904   Call Function, passing all the values of each Values-Form as arguments,
905   values from the first Values-Form making up the first argument, etc."
906   (let* ((fun-cont (make-continuation))
907          (node (if args
908                    (make-mv-combination fun-cont)
909                    (make-combination fun-cont))))
910     (ir1-convert start fun-cont
911                  (if (and (consp fun) (eq (car fun) 'function))
912                      fun
913                      `(%coerce-callable-to-fun ,fun)))
914     (setf (continuation-dest fun-cont) node)
915     (assert-continuation-type fun-cont
916                               (specifier-type '(or function symbol)))
917     (collect ((arg-conts))
918       (let ((this-start fun-cont))
919         (dolist (arg args)
920           (let ((this-cont (make-continuation node)))
921             (ir1-convert this-start this-cont arg)
922             (setq this-start this-cont)
923             (arg-conts this-cont)))
924         (prev-link node this-start)
925         (use-continuation node cont)
926         (setf (basic-combination-args node) (arg-conts))))))
927
928 ;;; MULTIPLE-VALUE-PROG1 is represented implicitly in IR1 by having a
929 ;;; the result code use result continuation (CONT), but transfer
930 ;;; control to the evaluation of the body. In other words, the result
931 ;;; continuation isn't IMMEDIATELY-USED-P by the nodes that compute
932 ;;; the result.
933 ;;;
934 ;;; In order to get the control flow right, we convert the result with
935 ;;; a dummy result continuation, then convert all the uses of the
936 ;;; dummy to be uses of CONT. If a use is an EXIT, then we also
937 ;;; substitute CONT for the dummy in the corresponding ENTRY node so
938 ;;; that they are consistent. Note that this doesn't amount to
939 ;;; changing the exit target, since the control destination of an exit
940 ;;; is determined by the block successor; we are just indicating the
941 ;;; continuation that the result is delivered to.
942 ;;;
943 ;;; We then convert the body, using another dummy continuation in its
944 ;;; own block as the result. After we are done converting the body, we
945 ;;; move all predecessors of the dummy end block to CONT's block.
946 ;;;
947 ;;; Note that we both exploit and maintain the invariant that the CONT
948 ;;; to an IR1 convert method either has no block or starts the block
949 ;;; that control should transfer to after completion for the form.
950 ;;; Nested MV-PROG1's work because during conversion of the result
951 ;;; form, we use dummy continuation whose block is the true control
952 ;;; destination.
953 (def-ir1-translator multiple-value-prog1 ((result &rest forms) start cont)
954   #!+sb-doc
955   "MULTIPLE-VALUE-PROG1 Values-Form Form*
956   Evaluate Values-Form and then the Forms, but return all the values of
957   Values-Form."
958   (continuation-starts-block cont)
959   (let* ((dummy-result (make-continuation))
960          (dummy-start (make-continuation))
961          (cont-block (continuation-block cont)))
962     (continuation-starts-block dummy-start)
963     (ir1-convert start dummy-start result)
964
965     (substitute-continuation-uses cont dummy-start)
966
967     (continuation-starts-block dummy-result)
968     (ir1-convert-progn-body dummy-start dummy-result forms)
969     (let ((end-block (continuation-block dummy-result)))
970       (dolist (pred (block-pred end-block))
971         (unlink-blocks pred end-block)
972         (link-blocks pred cont-block))
973       (aver (not (continuation-dest dummy-result)))
974       (delete-continuation dummy-result)
975       (remove-from-dfo end-block))))
976 \f
977 ;;;; interface to defining macros
978
979 ;;;; FIXME:
980 ;;;;   classic CMU CL comment:
981 ;;;;     DEFMACRO and DEFUN expand into calls to %DEFxxx functions
982 ;;;;     so that we get a chance to see what is going on. We define
983 ;;;;     IR1 translators for these functions which look at the
984 ;;;;     definition and then generate a call to the %%DEFxxx function.
985 ;;;; Alas, this implementation doesn't do the right thing for
986 ;;;; non-toplevel uses of these forms, so this should probably
987 ;;;; be changed to use EVAL-WHEN instead.
988
989 ;;; Return a new source path with any stuff intervening between the
990 ;;; current path and the first form beginning with NAME stripped off.
991 ;;; This is used to hide the guts of DEFmumble macros to prevent
992 ;;; annoying error messages.
993 (defun revert-source-path (name)
994   (do ((path *current-path* (cdr path)))
995       ((null path) *current-path*)
996     (let ((first (first path)))
997       (when (or (eq first name)
998                 (eq first 'original-source-start))
999         (return path)))))
1000
1001 ;;; Warn about incompatible or illegal definitions and add the macro
1002 ;;; to the compiler environment.
1003 ;;;
1004 ;;; Someday we could check for macro arguments being incompatibly
1005 ;;; redefined. Doing this right will involve finding the old macro
1006 ;;; lambda-list and comparing it with the new one.
1007 (def-ir1-translator %defmacro ((qname qdef lambda-list doc) start cont
1008                                :kind :function)
1009   (let (;; QNAME is typically a quoted name. I think the idea is to
1010         ;; let %DEFMACRO work as an ordinary function when
1011         ;; interpreting. Whatever the reason the quote is there, we
1012         ;; don't want it any more. -- WHN 19990603
1013         (name (eval qname))
1014         ;; QDEF should be a sharp-quoted definition. We don't want to
1015         ;; make a function of it just yet, so we just drop the
1016         ;; sharp-quote.
1017         (def (progn
1018                (aver (eq 'function (first qdef)))
1019                (aver (proper-list-of-length-p qdef 2))
1020                (second qdef))))
1021
1022     (/show "doing IR1 translator for %DEFMACRO" name)
1023
1024     (unless (symbolp name)
1025       (compiler-error "The macro name ~S is not a symbol." name))
1026
1027     (ecase (info :function :kind name)
1028       ((nil))
1029       (:function
1030        (remhash name *free-functions*)
1031        (undefine-fun-name name)
1032        (compiler-warning
1033         "~S is being redefined as a macro when it was ~
1034          previously ~(~A~) to be a function."
1035         name
1036         (info :function :where-from name)))
1037       (:macro)
1038       (:special-form
1039        (compiler-error "The special form ~S can't be redefined as a macro."
1040                        name)))
1041
1042     (setf (info :function :kind name) :macro
1043           (info :function :where-from name) :defined
1044           (info :function :macro-function name) (coerce def 'function))
1045
1046     (let* ((*current-path* (revert-source-path 'defmacro))
1047            (fun (ir1-convert-lambda def 
1048                                     :debug-name (debug-namify "DEFMACRO ~S"
1049                                                               name))))
1050       (setf (functional-arg-documentation fun) (eval lambda-list))
1051
1052       (ir1-convert start cont `(%%defmacro ',name ,fun ,doc)))
1053
1054     (when sb!xc:*compile-print*
1055       ;; FIXME: It would be nice to convert this, and the other places
1056       ;; which create compiler diagnostic output prefixed by
1057       ;; semicolons, to use some common utility which automatically
1058       ;; prefixes all its output with semicolons. (The addition of
1059       ;; semicolon prefixes was introduced ca. sbcl-0.6.8.10 as the
1060       ;; "MNA compiler message patch", and implemented by modifying a
1061       ;; bunch of output statements on a case-by-case basis, which
1062       ;; seems unnecessarily error-prone and unclear, scattering
1063       ;; implicit information about output style throughout the
1064       ;; system.) Starting by rewriting COMPILER-MUMBLE to add
1065       ;; semicolon prefixes would be a good start, and perhaps also:
1066       ;;   * Add semicolon prefixes for "FOO assembled" messages emitted 
1067       ;;     when e.g. src/assembly/x86/assem-rtns.lisp is processed.
1068       ;;   * At least some debugger output messages deserve semicolon
1069       ;;     prefixes too:
1070       ;;     ** restarts table
1071       ;;     ** "Within the debugger, you can type HELP for help."
1072       (compiler-mumble "~&; converted ~S~%" name))))
1073
1074 (def-ir1-translator %define-compiler-macro ((name def lambda-list doc)
1075                                             start cont
1076                                             :kind :function)
1077   (let ((name (eval name))
1078         (def (second def))) ; We don't want to make a function just yet...
1079
1080     (when (eq (info :function :kind name) :special-form)
1081       (compiler-error "attempt to define a compiler-macro for special form ~S"
1082                       name))
1083
1084     (setf (info :function :compiler-macro-function name)
1085           (coerce def 'function))
1086
1087     (let* ((*current-path* (revert-source-path 'define-compiler-macro))
1088            (fun (ir1-convert-lambda def 
1089                                     :debug-name (debug-namify
1090                                                  "DEFINE-COMPILER-MACRO ~S"
1091                                                  name))))
1092       (setf (functional-arg-documentation fun) (eval lambda-list))
1093
1094       (ir1-convert start cont `(%%define-compiler-macro ',name ,fun ,doc)))
1095
1096     (when sb!xc:*compile-print*
1097       (compiler-mumble "~&; converted ~S~%" name))))