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