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