0.7.1.2:
[sbcl.git] / src / compiler / ir2tran.lisp
1 ;;;; This file contains the virtual-machine-independent parts of the
2 ;;;; code which does the actual translation of nodes to VOPs.
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 ;;;; moves and type checks
16
17 ;;; Move X to Y unless they are EQ.
18 (defun emit-move (node block x y)
19   (declare (type node node) (type ir2-block block) (type tn x y))
20   (unless (eq x y)
21     (vop move node block x y))
22   (values))
23
24 ;;; If there is any CHECK-xxx template for TYPE, then return it,
25 ;;; otherwise return NIL.
26 (defun type-check-template (type)
27   (declare (type ctype type))
28   (multiple-value-bind (check-ptype exact) (primitive-type type)
29     (if exact
30         (primitive-type-check check-ptype)
31         (let ((name (hairy-type-check-template-name type)))
32           (if name
33               (template-or-lose name)
34               nil)))))
35
36 ;;; Emit code in BLOCK to check that VALUE is of the specified TYPE,
37 ;;; yielding the checked result in RESULT. VALUE and result may be of
38 ;;; any primitive type. There must be CHECK-xxx VOP for TYPE. Any
39 ;;; other type checks should have been converted to an explicit type
40 ;;; test.
41 (defun emit-type-check (node block value result type)
42   (declare (type tn value result) (type node node) (type ir2-block block)
43            (type ctype type))
44   (emit-move-template node block (type-check-template type) value result)
45   (values))
46
47 ;;; Allocate an indirect value cell. Maybe do some clever stack
48 ;;; allocation someday.
49 ;;;
50 ;;; FIXME: DO-MAKE-VALUE-CELL is a bad name, since it doesn't make
51 ;;; clear what's the distinction between it and the MAKE-VALUE-CELL
52 ;;; VOP, and since the DO- further connotes iteration, which has
53 ;;; nothing to do with this. Clearer, more systematic names, anyone?
54 (defevent make-value-cell-event "Allocate heap value cell for lexical var.")
55 (defun do-make-value-cell (node block value res)
56   (event make-value-cell-event node)
57   (vop make-value-cell node block value res))
58 \f
59 ;;;; leaf reference
60
61 ;;; Return the TN that holds the value of THING in the environment ENV.
62 (declaim (ftype (function ((or nlx-info lambda-var) physenv) tn)
63                 find-in-physenv))
64 (defun find-in-physenv (thing physenv)
65   (or (cdr (assoc thing (ir2-physenv-closure (physenv-info physenv))))
66       (etypecase thing
67         (lambda-var
68          ;; I think that a failure of this assertion means that we're
69          ;; trying to access a variable which was improperly closed
70          ;; over. The PHYSENV describes a physical environment. Every
71          ;; variable that a form refers to should either be in its
72          ;; physical environment directly, or grabbed from a
73          ;; surrounding physical environment when it was closed over.
74          ;; The ASSOC expression above finds closed-over variables, so
75          ;; if we fell through the ASSOC expression, it wasn't closed
76          ;; over. Therefore, it must be in our physical environment
77          ;; directly. If instead it is in some other physical
78          ;; environment, then it's bogus for us to reference it here
79          ;; without it being closed over. -- WHN 2001-09-29
80          (aver (eq physenv (lambda-physenv (lambda-var-home thing))))
81          (leaf-info thing))
82         (nlx-info
83          (aver (eq physenv (block-physenv (nlx-info-target thing))))
84          (ir2-nlx-info-home (nlx-info-info thing))))
85       (error "~@<internal error: ~2I~_~S ~_not found in ~_~S~:>"
86              thing physenv)))
87
88 ;;; If LEAF already has a constant TN, return that, otherwise make a
89 ;;; TN for it.
90 (defun constant-tn (leaf)
91   (declare (type constant leaf))
92   (or (leaf-info leaf)
93       (setf (leaf-info leaf)
94             (make-constant-tn leaf))))
95
96 ;;; Return a TN that represents the value of LEAF, or NIL if LEAF
97 ;;; isn't directly represented by a TN. ENV is the environment that
98 ;;; the reference is done in.
99 (defun leaf-tn (leaf env)
100   (declare (type leaf leaf) (type physenv env))
101   (typecase leaf
102     (lambda-var
103      (unless (lambda-var-indirect leaf)
104        (find-in-physenv leaf env)))
105     (constant (constant-tn leaf))
106     (t nil)))
107
108 ;;; This is used to conveniently get a handle on a constant TN during
109 ;;; IR2 conversion. It returns a constant TN representing the Lisp
110 ;;; object VALUE.
111 (defun emit-constant (value)
112   (constant-tn (find-constant value)))
113
114 ;;; Convert a REF node. The reference must not be delayed.
115 (defun ir2-convert-ref (node block)
116   (declare (type ref node) (type ir2-block block))
117   (let* ((cont (node-cont node))
118          (leaf (ref-leaf node))
119          (locs (continuation-result-tns
120                 cont (list (primitive-type (leaf-type leaf)))))
121          (res (first locs)))
122     (etypecase leaf
123       (lambda-var
124        (let ((tn (find-in-physenv leaf (node-physenv node))))
125          (if (lambda-var-indirect leaf)
126              (vop value-cell-ref node block tn res)
127              (emit-move node block tn res))))
128       (constant
129        (if (legal-immediate-constant-p leaf)
130            (emit-move node block (constant-tn leaf) res)
131            (let* ((name (leaf-source-name leaf))
132                   (name-tn (emit-constant name)))
133              (if (policy node (zerop safety))
134                  (vop fast-symbol-value node block name-tn res)
135                  (vop symbol-value node block name-tn res)))))
136       (functional
137        (ir2-convert-closure node block leaf res))
138       (global-var
139        (let ((unsafe (policy node (zerop safety)))
140              (name (leaf-source-name leaf)))
141          (ecase (global-var-kind leaf)
142            ((:special :global)
143             (aver (symbolp name))
144             (let ((name-tn (emit-constant name)))
145               (if unsafe
146                   (vop fast-symbol-value node block name-tn res)
147                   (vop symbol-value node block name-tn res))))
148            (:global-function
149             (let ((fdefn-tn (make-load-time-constant-tn :fdefinition name)))
150               (if unsafe
151                   (vop fdefn-fun node block fdefn-tn res)
152                   (vop safe-fdefn-fun node block fdefn-tn res))))))))
153     (move-continuation-result node block locs cont))
154   (values))
155
156 ;;; Emit code to load a function object implementing FUN into
157 ;;; RES. This gets interesting when the referenced function is a
158 ;;; closure: we must make the closure and move the closed-over values
159 ;;; into it.
160 ;;;
161 ;;; FUN is either a :TOPLEVEL-XEP functional or the XEP lambda for the
162 ;;; called function, since local call analysis converts all closure
163 ;;; references. If a :TOPLEVEL-XEP, we know it is not a closure.
164 ;;;
165 ;;; If a closed-over LAMBDA-VAR has no refs (is deleted), then we
166 ;;; don't initialize that slot. This can happen with closures over
167 ;;; top level variables, where optimization of the closure deleted the
168 ;;; variable. Since we committed to the closure format when we
169 ;;; pre-analyzed the top level code, we just leave an empty slot.
170 (defun ir2-convert-closure (ref ir2-block fun res)
171   (declare (type ref ref) (type ir2-block ir2-block)
172            (type functional fun) (type tn res))
173
174   (unless (leaf-info fun)
175     (setf (leaf-info fun)
176           (make-entry-info :name (functional-debug-name fun))))
177   (let ((entry (make-load-time-constant-tn :entry fun))
178         (closure (etypecase fun
179                    (clambda
180
181                     ;; This assertion was sort of an experiment. It
182                     ;; would be nice and sane and easier to understand
183                     ;; things if it were *always* true, but
184                     ;; experimentally I observe that it's only
185                     ;; *almost* always true. -- WHN 2001-01-02
186                     #+nil 
187                     (aver (eql (lambda-component fun)
188                                (block-component (ir2-block-block ir2-block))))
189
190                     ;; Check for some weirdness which came up in bug
191                     ;; 138, 2002-01-02.
192                     ;;
193                     ;; The MAKE-LOAD-TIME-CONSTANT-TN call above puts
194                     ;; an :ENTRY record into the
195                     ;; IR2-COMPONENT-CONSTANTS table. The
196                     ;; dump-a-COMPONENT code
197                     ;;   * treats every HANDLEless :ENTRY record into a
198                     ;;     patch, and
199                     ;;   * expects every patch to correspond to an
200                     ;;     IR2-COMPONENT-ENTRIES record.
201                     ;; The IR2-COMPONENT-ENTRIES records are set by
202                     ;; ENTRY-ANALYZE walking over COMPONENT-LAMBDAS.
203                     ;; Bug 138b arose because there was a HANDLEless
204                     ;; :ENTRY record which didn't correspond to an
205                     ;; IR2-COMPONENT-ENTRIES record. That problem is
206                     ;; hard to debug when it's caught at dump time, so
207                     ;; this assertion tries to catch it here.
208                     (aver (member fun
209                                   (component-lambdas (lambda-component fun))))
210
211                     ;; another bug-138-related issue: COMPONENT-NEW-FUNS
212                     ;; is an IR1 temporary, and now that we're doing IR2
213                     ;; it should've been completely flushed (but wasn't).
214                     (aver (null (component-new-funs (lambda-component fun))))
215
216                     (physenv-closure (get-lambda-physenv fun)))
217                    (functional
218                     (aver (eq (functional-kind fun) :toplevel-xep))
219                     nil))))
220
221     (cond (closure
222            (let ((this-env (node-physenv ref)))
223              (vop make-closure ref ir2-block entry (length closure) res)
224              (loop for what in closure and n from 0 do
225                (unless (and (lambda-var-p what)
226                             (null (leaf-refs what)))
227                  (vop closure-init ref ir2-block
228                       res
229                       (find-in-physenv what this-env)
230                       n)))))
231           (t
232            (emit-move ref ir2-block entry res))))
233   (values))
234
235 ;;; Convert a SET node. If the node's CONT is annotated, then we also
236 ;;; deliver the value to that continuation. If the var is a lexical
237 ;;; variable with no refs, then we don't actually set anything, since
238 ;;; the variable has been deleted.
239 (defun ir2-convert-set (node block)
240   (declare (type cset node) (type ir2-block block))
241   (let* ((cont (node-cont node))
242          (leaf (set-var node))
243          (val (continuation-tn node block (set-value node)))
244          (locs (if (continuation-info cont)
245                    (continuation-result-tns
246                     cont (list (primitive-type (leaf-type leaf))))
247                    nil)))
248     (etypecase leaf
249       (lambda-var
250        (when (leaf-refs leaf)
251          (let ((tn (find-in-physenv leaf (node-physenv node))))
252            (if (lambda-var-indirect leaf)
253                (vop value-cell-set node block tn val)
254                (emit-move node block val tn)))))
255       (global-var
256        (ecase (global-var-kind leaf)
257          ((:special :global)
258           (aver (symbolp (leaf-source-name leaf)))
259           (vop set node block (emit-constant (leaf-source-name leaf)) val)))))
260     (when locs
261       (emit-move node block val (first locs))
262       (move-continuation-result node block locs cont)))
263   (values))
264 \f
265 ;;;; utilities for receiving fixed values
266
267 ;;; Return a TN that can be referenced to get the value of CONT. CONT
268 ;;; must be LTN-Annotated either as a delayed leaf ref or as a fixed,
269 ;;; single-value continuation. If a type check is called for, do it.
270 ;;;
271 ;;; The primitive-type of the result will always be the same as the
272 ;;; IR2-CONTINUATION-PRIMITIVE-TYPE, ensuring that VOPs are always
273 ;;; called with TNs that satisfy the operand primitive-type
274 ;;; restriction. We may have to make a temporary of the desired type
275 ;;; and move the actual continuation TN into it. This happens when we
276 ;;; delete a type check in unsafe code or when we locally know
277 ;;; something about the type of an argument variable.
278 (defun continuation-tn (node block cont)
279   (declare (type node node) (type ir2-block block) (type continuation cont))
280   (let* ((2cont (continuation-info cont))
281          (cont-tn
282           (ecase (ir2-continuation-kind 2cont)
283             (:delayed
284              (let ((ref (continuation-use cont)))
285                (leaf-tn (ref-leaf ref) (node-physenv ref))))
286             (:fixed
287              (aver (= (length (ir2-continuation-locs 2cont)) 1))
288              (first (ir2-continuation-locs 2cont)))))
289          (ptype (ir2-continuation-primitive-type 2cont)))
290
291     (cond ((and (eq (continuation-type-check cont) t)
292                 (multiple-value-bind (check types)
293                     (continuation-check-types cont)
294                   (aver (eq check :simple))
295                   ;; If the proven type is a subtype of the possibly
296                   ;; weakened type check then it's always true and is
297                   ;; flushed.
298                   (unless (values-subtypep (continuation-proven-type cont)
299                                            (first types))
300                     (let ((temp (make-normal-tn ptype)))
301                       (emit-type-check node block cont-tn temp
302                                        (first types))
303                       temp)))))
304           ((eq (tn-primitive-type cont-tn) ptype) cont-tn)
305           (t
306            (let ((temp (make-normal-tn ptype)))
307              (emit-move node block cont-tn temp)
308              temp)))))
309
310 ;;; This is similar to CONTINUATION-TN, but hacks multiple values. We
311 ;;; return continuations holding the values of CONT with PTYPES as
312 ;;; their primitive types. CONT must be annotated for the same number
313 ;;; of fixed values are there are PTYPES.
314 ;;;
315 ;;; If the continuation has a type check, check the values into temps
316 ;;; and return the temps. When we have more values than assertions, we
317 ;;; move the extra values with no check.
318 (defun continuation-tns (node block cont ptypes)
319   (declare (type node node) (type ir2-block block)
320            (type continuation cont) (list ptypes))
321   (let* ((locs (ir2-continuation-locs (continuation-info cont)))
322          (nlocs (length locs)))
323     (aver (= nlocs (length ptypes)))
324     (if (eq (continuation-type-check cont) t)
325         (multiple-value-bind (check types) (continuation-check-types cont)
326           (aver (eq check :simple))
327           (let ((ntypes (length types)))
328             (mapcar (lambda (from to-type assertion)
329                       (let ((temp (make-normal-tn to-type)))
330                         (if assertion
331                             (emit-type-check node block from temp assertion)
332                             (emit-move node block from temp))
333                         temp))
334                     locs ptypes
335                     (if (< ntypes nlocs)
336                         (append types (make-list (- nlocs ntypes)
337                                                  :initial-element nil))
338                         types))))
339         (mapcar (lambda (from to-type)
340                   (if (eq (tn-primitive-type from) to-type)
341                       from
342                       (let ((temp (make-normal-tn to-type)))
343                         (emit-move node block from temp)
344                         temp)))
345                 locs
346                 ptypes))))
347 \f
348 ;;;; utilities for delivering values to continuations
349
350 ;;; Return a list of TNs with the specifier TYPES that can be used as
351 ;;; result TNs to evaluate an expression into the continuation CONT.
352 ;;; This is used together with MOVE-CONTINUATION-RESULT to deliver
353 ;;; fixed values to a continuation.
354 ;;;
355 ;;; If the continuation isn't annotated (meaning the values are
356 ;;; discarded) or is unknown-values, the then we make temporaries for
357 ;;; each supplied value, providing a place to compute the result in
358 ;;; until we decide what to do with it (if anything.)
359 ;;;
360 ;;; If the continuation is fixed-values, and wants the same number of
361 ;;; values as the user wants to deliver, then we just return the
362 ;;; IR2-CONTINUATION-LOCS. Otherwise we make a new list padded as
363 ;;; necessary by discarded TNs. We always return a TN of the specified
364 ;;; type, using the continuation locs only when they are of the
365 ;;; correct type.
366 (defun continuation-result-tns (cont types)
367   (declare (type continuation cont) (type list types))
368   (let ((2cont (continuation-info cont)))
369     (if (not 2cont)
370         (mapcar #'make-normal-tn types)
371         (ecase (ir2-continuation-kind 2cont)
372           (:fixed
373            (let* ((locs (ir2-continuation-locs 2cont))
374                   (nlocs (length locs))
375                   (ntypes (length types)))
376              (if (and (= nlocs ntypes)
377                       (do ((loc locs (cdr loc))
378                            (type types (cdr type)))
379                           ((null loc) t)
380                         (unless (eq (tn-primitive-type (car loc)) (car type))
381                           (return nil))))
382                  locs
383                  (mapcar (lambda (loc type)
384                            (if (eq (tn-primitive-type loc) type)
385                                loc
386                                (make-normal-tn type)))
387                          (if (< nlocs ntypes)
388                              (append locs
389                                      (mapcar #'make-normal-tn
390                                              (subseq types nlocs)))
391                              locs)
392                          types))))
393           (:unknown
394            (mapcar #'make-normal-tn types))))))
395
396 ;;; Make the first N standard value TNs, returning them in a list.
397 (defun make-standard-value-tns (n)
398   (declare (type unsigned-byte n))
399   (collect ((res))
400     (dotimes (i n)
401       (res (standard-arg-location i)))
402     (res)))
403
404 ;;; Return a list of TNs wired to the standard value passing
405 ;;; conventions that can be used to receive values according to the
406 ;;; unknown-values convention. This is used with together
407 ;;; MOVE-CONTINUATION-RESULT for delivering unknown values to a fixed
408 ;;; values continuation.
409 ;;;
410 ;;; If the continuation isn't annotated, then we treat as 0-values,
411 ;;; returning an empty list of temporaries.
412 ;;;
413 ;;; If the continuation is annotated, then it must be :FIXED.
414 (defun standard-result-tns (cont)
415   (declare (type continuation cont))
416   (let ((2cont (continuation-info cont)))
417     (if 2cont
418         (ecase (ir2-continuation-kind 2cont)
419           (:fixed
420            (make-standard-value-tns (length (ir2-continuation-locs 2cont)))))
421         ())))
422
423 ;;; Just move each SRC TN into the corresponding DEST TN, defaulting
424 ;;; any unsupplied source values to NIL. We let EMIT-MOVE worry about
425 ;;; doing the appropriate coercions.
426 (defun move-results-coerced (node block src dest)
427   (declare (type node node) (type ir2-block block) (list src dest))
428   (let ((nsrc (length src))
429         (ndest (length dest)))
430     (mapc (lambda (from to)
431             (unless (eq from to)
432               (emit-move node block from to)))
433           (if (> ndest nsrc)
434               (append src (make-list (- ndest nsrc)
435                                      :initial-element (emit-constant nil)))
436               src)
437           dest))
438   (values))
439
440 ;;; If necessary, emit coercion code needed to deliver the RESULTS to
441 ;;; the specified continuation. NODE and BLOCK provide context for
442 ;;; emitting code. Although usually obtained from STANDARD-RESULT-TNs
443 ;;; or CONTINUATION-RESULT-TNs, RESULTS my be a list of any type or
444 ;;; number of TNs.
445 ;;;
446 ;;; If the continuation is fixed values, then move the results into
447 ;;; the continuation locations. If the continuation is unknown values,
448 ;;; then do the moves into the standard value locations, and use
449 ;;; PUSH-VALUES to put the values on the stack.
450 (defun move-continuation-result (node block results cont)
451   (declare (type node node) (type ir2-block block)
452            (list results) (type continuation cont))
453   (let* ((2cont (continuation-info cont)))
454     (when 2cont
455       (ecase (ir2-continuation-kind 2cont)
456         (:fixed
457          (let ((locs (ir2-continuation-locs 2cont)))
458            (unless (eq locs results)
459              (move-results-coerced node block results locs))))
460         (:unknown
461          (let* ((nvals (length results))
462                 (locs (make-standard-value-tns nvals)))
463            (move-results-coerced node block results locs)
464            (vop* push-values node block
465                  ((reference-tn-list locs nil))
466                  ((reference-tn-list (ir2-continuation-locs 2cont) t))
467                  nvals))))))
468   (values))
469 \f
470 ;;;; template conversion
471
472 ;;; Build a TN-Refs list that represents access to the values of the
473 ;;; specified list of continuations ARGS for TEMPLATE. Any :CONSTANT
474 ;;; arguments are returned in the second value as a list rather than
475 ;;; being accessed as a normal argument. NODE and BLOCK provide the
476 ;;; context for emitting any necessary type-checking code.
477 (defun reference-args (node block args template)
478   (declare (type node node) (type ir2-block block) (list args)
479            (type template template))
480   (collect ((info-args))
481     (let ((last nil)
482           (first nil))
483       (do ((args args (cdr args))
484            (types (template-arg-types template) (cdr types)))
485           ((null args))
486         (let ((type (first types))
487               (arg (first args)))
488           (if (and (consp type) (eq (car type) ':constant))
489               (info-args (continuation-value arg))
490               (let ((ref (reference-tn (continuation-tn node block arg) nil)))
491                 (if last
492                     (setf (tn-ref-across last) ref)
493                     (setf first ref))
494                 (setq last ref)))))
495
496       (values (the (or tn-ref null) first) (info-args)))))
497
498 ;;; Convert a conditional template. We try to exploit any
499 ;;; drop-through, but emit an unconditional branch afterward if we
500 ;;; fail. NOT-P is true if the sense of the TEMPLATE's test should be
501 ;;; negated.
502 (defun ir2-convert-conditional (node block template args info-args if not-p)
503   (declare (type node node) (type ir2-block block)
504            (type template template) (type (or tn-ref null) args)
505            (list info-args) (type cif if) (type boolean not-p))
506   (aver (= (template-info-arg-count template) (+ (length info-args) 2)))
507   (let ((consequent (if-consequent if))
508         (alternative (if-alternative if)))
509     (cond ((drop-thru-p if consequent)
510            (emit-template node block template args nil
511                           (list* (block-label alternative) (not not-p)
512                                  info-args)))
513           (t
514            (emit-template node block template args nil
515                           (list* (block-label consequent) not-p info-args))
516            (unless (drop-thru-p if alternative)
517              (vop branch node block (block-label alternative)))))))
518
519 ;;; Convert an IF that isn't the DEST of a conditional template.
520 (defun ir2-convert-if (node block)
521   (declare (type ir2-block block) (type cif node))
522   (let* ((test (if-test node))
523          (test-ref (reference-tn (continuation-tn node block test) nil))
524          (nil-ref (reference-tn (emit-constant nil) nil)))
525     (setf (tn-ref-across test-ref) nil-ref)
526     (ir2-convert-conditional node block (template-or-lose 'if-eq)
527                              test-ref () node t)))
528
529 ;;; Return a list of primitive-types that we can pass to
530 ;;; CONTINUATION-RESULT-TNS describing the result types we want for a
531 ;;; template call. We duplicate here the determination of output type
532 ;;; that was done in initially selecting the template, so we know that
533 ;;; the types we find are allowed by the template output type
534 ;;; restrictions.
535 (defun find-template-result-types (call cont template rtypes)
536   (declare (type combination call) (type continuation cont)
537            (type template template) (list rtypes))
538   (let* ((dtype (node-derived-type call))
539          (type (if (and (or (eq (template-ltn-policy template) :safe)
540                             (policy call (= safety 0)))
541                         (continuation-type-check cont))
542                    (values-type-intersection
543                     dtype
544                     (continuation-asserted-type cont))
545                    dtype))
546          (types (mapcar #'primitive-type
547                         (if (values-type-p type)
548                             (append (values-type-required type)
549                                     (values-type-optional type))
550                             (list type)))))
551     (let ((nvals (length rtypes))
552           (ntypes (length types)))
553       (cond ((< ntypes nvals)
554              (append types
555                      (make-list (- nvals ntypes)
556                                 :initial-element *backend-t-primitive-type*)))
557             ((> ntypes nvals)
558              (subseq types 0 nvals))
559             (t
560              types)))))
561
562 ;;; Return a list of TNs usable in a CALL to TEMPLATE delivering
563 ;;; values to CONT. As an efficiency hack, we pick off the common case
564 ;;; where the continuation is fixed values and has locations that
565 ;;; satisfy the result restrictions. This can fail when there is a
566 ;;; type check or a values count mismatch.
567 (defun make-template-result-tns (call cont template rtypes)
568   (declare (type combination call) (type continuation cont)
569            (type template template) (list rtypes))
570   (let ((2cont (continuation-info cont)))
571     (if (and 2cont (eq (ir2-continuation-kind 2cont) :fixed))
572         (let ((locs (ir2-continuation-locs 2cont)))
573           (if (and (= (length rtypes) (length locs))
574                    (do ((loc locs (cdr loc))
575                         (rtype rtypes (cdr rtype)))
576                        ((null loc) t)
577                      (unless (operand-restriction-ok
578                               (car rtype)
579                               (tn-primitive-type (car loc))
580                               :t-ok nil)
581                        (return nil))))
582               locs
583               (continuation-result-tns
584                cont
585                (find-template-result-types call cont template rtypes))))
586         (continuation-result-tns
587          cont
588          (find-template-result-types call cont template rtypes)))))
589
590 ;;; Get the operands into TNs, make TN-Refs for them, and then call
591 ;;; the template emit function.
592 (defun ir2-convert-template (call block)
593   (declare (type combination call) (type ir2-block block))
594   (let* ((template (combination-info call))
595          (cont (node-cont call))
596          (rtypes (template-result-types template)))
597     (multiple-value-bind (args info-args)
598         (reference-args call block (combination-args call) template)
599       (aver (not (template-more-results-type template)))
600       (if (eq rtypes :conditional)
601           (ir2-convert-conditional call block template args info-args
602                                    (continuation-dest cont) nil)
603           (let* ((results (make-template-result-tns call cont template rtypes))
604                  (r-refs (reference-tn-list results t)))
605             (aver (= (length info-args)
606                      (template-info-arg-count template)))
607             (if info-args
608                 (emit-template call block template args r-refs info-args)
609                 (emit-template call block template args r-refs))
610             (move-continuation-result call block results cont)))))
611   (values))
612
613 ;;; We don't have to do much because operand count checking is done by
614 ;;; IR1 conversion. The only difference between this and the function
615 ;;; case of IR2-CONVERT-TEMPLATE is that there can be codegen-info
616 ;;; arguments.
617 (defoptimizer (%%primitive ir2-convert) ((template info &rest args) call block)
618   (let* ((template (continuation-value template))
619          (info (continuation-value info))
620          (cont (node-cont call))
621          (rtypes (template-result-types template))
622          (results (make-template-result-tns call cont template rtypes))
623          (r-refs (reference-tn-list results t)))
624     (multiple-value-bind (args info-args)
625         (reference-args call block (cddr (combination-args call)) template)
626       (aver (not (template-more-results-type template)))
627       (aver (not (eq rtypes :conditional)))
628       (aver (null info-args))
629
630       (if info
631           (emit-template call block template args r-refs info)
632           (emit-template call block template args r-refs))
633
634       (move-continuation-result call block results cont)))
635   (values))
636 \f
637 ;;;; local call
638
639 ;;; Convert a LET by moving the argument values into the variables.
640 ;;; Since a LET doesn't have any passing locations, we move the
641 ;;; arguments directly into the variables. We must also allocate any
642 ;;; indirect value cells, since there is no function prologue to do
643 ;;; this.
644 (defun ir2-convert-let (node block fun)
645   (declare (type combination node) (type ir2-block block) (type clambda fun))
646   (mapc (lambda (var arg)
647           (when arg
648             (let ((src (continuation-tn node block arg))
649                   (dest (leaf-info var)))
650               (if (lambda-var-indirect var)
651                   (do-make-value-cell node block src dest)
652                   (emit-move node block src dest)))))
653         (lambda-vars fun) (basic-combination-args node))
654   (values))
655
656 ;;; Emit any necessary moves into assignment temps for a local call to
657 ;;; FUN. We return two lists of TNs: TNs holding the actual argument
658 ;;; values, and (possibly EQ) TNs that are the actual destination of
659 ;;; the arguments. When necessary, we allocate temporaries for
660 ;;; arguments to preserve parallel assignment semantics. These lists
661 ;;; exclude unused arguments and include implicit environment
662 ;;; arguments, i.e. they exactly correspond to the arguments passed.
663 ;;;
664 ;;; OLD-FP is the TN currently holding the value we want to pass as
665 ;;; OLD-FP. If null, then the call is to the same environment (an
666 ;;; :ASSIGNMENT), so we only move the arguments, and leave the
667 ;;; environment alone.
668 (defun emit-psetq-moves (node block fun old-fp)
669   (declare (type combination node) (type ir2-block block) (type clambda fun)
670            (type (or tn null) old-fp))
671   (let* ((called-env (physenv-info (lambda-physenv fun)))
672          (this-1env (node-physenv node))
673          (actuals (mapcar (lambda (x)
674                             (when x
675                               (continuation-tn node block x)))
676                           (combination-args node))))
677     (collect ((temps)
678               (locs))
679       (dolist (var (lambda-vars fun))
680         (let ((actual (pop actuals))
681               (loc (leaf-info var)))
682           (when actual
683             (cond
684              ((lambda-var-indirect var)
685               (let ((temp
686                      (make-normal-tn *backend-t-primitive-type*)))
687                 (do-make-value-cell node block actual temp)
688                 (temps temp)))
689              ((member actual (locs))
690               (let ((temp (make-normal-tn (tn-primitive-type loc))))
691                 (emit-move node block actual temp)
692                 (temps temp)))
693              (t
694               (temps actual)))
695             (locs loc))))
696
697       (when old-fp
698         (dolist (thing (ir2-physenv-closure called-env))
699           (temps (find-in-physenv (car thing) this-1env))
700           (locs (cdr thing)))
701
702         (temps old-fp)
703         (locs (ir2-physenv-old-fp called-env)))
704
705       (values (temps) (locs)))))
706
707 ;;; A tail-recursive local call is done by emitting moves of stuff
708 ;;; into the appropriate passing locations. After setting up the args
709 ;;; and environment, we just move our return-pc into the called
710 ;;; function's passing location.
711 (defun ir2-convert-tail-local-call (node block fun)
712   (declare (type combination node) (type ir2-block block) (type clambda fun))
713   (let ((this-env (physenv-info (node-physenv node))))
714     (multiple-value-bind (temps locs)
715         (emit-psetq-moves node block fun (ir2-physenv-old-fp this-env))
716
717       (mapc (lambda (temp loc)
718               (emit-move node block temp loc))
719             temps locs))
720
721     (emit-move node block
722                (ir2-physenv-return-pc this-env)
723                (ir2-physenv-return-pc-pass
724                 (physenv-info
725                  (lambda-physenv fun)))))
726
727   (values))
728
729 ;;; Convert an :ASSIGNMENT call. This is just like a tail local call,
730 ;;; except that the caller and callee environment are the same, so we
731 ;;; don't need to mess with the environment locations, return PC, etc.
732 (defun ir2-convert-assignment (node block fun)
733   (declare (type combination node) (type ir2-block block) (type clambda fun))
734     (multiple-value-bind (temps locs) (emit-psetq-moves node block fun nil)
735
736       (mapc (lambda (temp loc)
737               (emit-move node block temp loc))
738             temps locs))
739   (values))
740
741 ;;; Do stuff to set up the arguments to a non-tail local call
742 ;;; (including implicit environment args.) We allocate a frame
743 ;;; (returning the FP and NFP), and also compute the TN-REFS list for
744 ;;; the values to pass and the list of passing location TNs.
745 (defun ir2-convert-local-call-args (node block fun)
746   (declare (type combination node) (type ir2-block block) (type clambda fun))
747   (let ((fp (make-stack-pointer-tn))
748         (nfp (make-number-stack-pointer-tn))
749         (old-fp (make-stack-pointer-tn)))
750     (multiple-value-bind (temps locs)
751         (emit-psetq-moves node block fun old-fp)
752       (vop current-fp node block old-fp)
753       (vop allocate-frame node block
754            (physenv-info (lambda-physenv fun))
755            fp nfp)
756       (values fp nfp temps (mapcar #'make-alias-tn locs)))))
757
758 ;;; Handle a non-TR known-values local call. We emit the call, then
759 ;;; move the results to the continuation's destination.
760 (defun ir2-convert-local-known-call (node block fun returns cont start)
761   (declare (type node node) (type ir2-block block) (type clambda fun)
762            (type return-info returns) (type continuation cont)
763            (type label start))
764   (multiple-value-bind (fp nfp temps arg-locs)
765       (ir2-convert-local-call-args node block fun)
766     (let ((locs (return-info-locations returns)))
767       (vop* known-call-local node block
768             (fp nfp (reference-tn-list temps nil))
769             ((reference-tn-list locs t))
770             arg-locs (physenv-info (lambda-physenv fun)) start)
771       (move-continuation-result node block locs cont)))
772   (values))
773
774 ;;; Handle a non-TR unknown-values local call. We do different things
775 ;;; depending on what kind of values the continuation wants.
776 ;;;
777 ;;; If CONT is :UNKNOWN, then we use the "multiple-" variant, directly
778 ;;; specifying the continuation's LOCS as the VOP results so that we
779 ;;; don't have to do anything after the call.
780 ;;;
781 ;;; Otherwise, we use STANDARD-RESULT-TNS to get wired result TNs, and
782 ;;; then call MOVE-CONTINUATION-RESULT to do any necessary type checks
783 ;;; or coercions.
784 (defun ir2-convert-local-unknown-call (node block fun cont start)
785   (declare (type node node) (type ir2-block block) (type clambda fun)
786            (type continuation cont) (type label start))
787   (multiple-value-bind (fp nfp temps arg-locs)
788       (ir2-convert-local-call-args node block fun)
789     (let ((2cont (continuation-info cont))
790           (env (physenv-info (lambda-physenv fun)))
791           (temp-refs (reference-tn-list temps nil)))
792       (if (and 2cont (eq (ir2-continuation-kind 2cont) :unknown))
793           (vop* multiple-call-local node block (fp nfp temp-refs)
794                 ((reference-tn-list (ir2-continuation-locs 2cont) t))
795                 arg-locs env start)
796           (let ((locs (standard-result-tns cont)))
797             (vop* call-local node block
798                   (fp nfp temp-refs)
799                   ((reference-tn-list locs t))
800                   arg-locs env start (length locs))
801             (move-continuation-result node block locs cont)))))
802   (values))
803
804 ;;; Dispatch to the appropriate function, depending on whether we have
805 ;;; a let, tail or normal call. If the function doesn't return, call
806 ;;; it using the unknown-value convention. We could compile it as a
807 ;;; tail call, but that might seem confusing in the debugger.
808 (defun ir2-convert-local-call (node block)
809   (declare (type combination node) (type ir2-block block))
810   (let* ((fun (ref-leaf (continuation-use (basic-combination-fun node))))
811          (kind (functional-kind fun)))
812     (cond ((eq kind :let)
813            (ir2-convert-let node block fun))
814           ((eq kind :assignment)
815            (ir2-convert-assignment node block fun))
816           ((node-tail-p node)
817            (ir2-convert-tail-local-call node block fun))
818           (t
819            (let ((start (block-label (lambda-block fun)))
820                  (returns (tail-set-info (lambda-tail-set fun)))
821                  (cont (node-cont node)))
822              (ecase (if returns
823                         (return-info-kind returns)
824                         :unknown)
825                (:unknown
826                 (ir2-convert-local-unknown-call node block fun cont start))
827                (:fixed
828                 (ir2-convert-local-known-call node block fun returns
829                                               cont start)))))))
830   (values))
831 \f
832 ;;;; full call
833
834 ;;; Given a function continuation FUN, return as values a TN holding
835 ;;; the thing that we call and true if the thing is named (false if it
836 ;;; is a function). There are two interesting non-named cases:
837 ;;;   -- Known to be a function, no check needed: return the
838 ;;;      continuation loc.
839 ;;;   -- Not known what it is.
840 (defun fun-continuation-tn (node block cont)
841   (declare (type continuation cont))
842   (let ((2cont (continuation-info cont)))
843     (if (eq (ir2-continuation-kind 2cont) :delayed)
844         (let ((name (continuation-fun-name cont t)))
845           (aver name)
846           (values (make-load-time-constant-tn :fdefinition name) t))
847         (let* ((locs (ir2-continuation-locs 2cont))
848                (loc (first locs))
849                (check (continuation-type-check cont))
850                (function-ptype (primitive-type-or-lose 'function)))
851           (aver (and (eq (ir2-continuation-kind 2cont) :fixed)
852                      (= (length locs) 1)))
853           (cond ((eq (tn-primitive-type loc) function-ptype)
854                  (aver (not (eq check t)))
855                  (values loc nil))
856                 (t
857                  (let ((temp (make-normal-tn function-ptype)))
858                    (aver (and (eq (ir2-continuation-primitive-type 2cont)
859                                   function-ptype)
860                               (eq check t)))
861                    (emit-type-check node block loc temp
862                                     (specifier-type 'function))
863                    (values temp nil))))))))
864
865 ;;; Set up the args to Node in the current frame, and return a tn-ref
866 ;;; list for the passing locations.
867 (defun move-tail-full-call-args (node block)
868   (declare (type combination node) (type ir2-block block))
869   (let ((args (basic-combination-args node))
870         (last nil)
871         (first nil))
872     (dotimes (num (length args))
873       (let ((loc (standard-arg-location num)))
874         (emit-move node block (continuation-tn node block (elt args num)) loc)
875         (let ((ref (reference-tn loc nil)))
876           (if last
877               (setf (tn-ref-across last) ref)
878               (setf first ref))
879           (setq last ref))))
880       first))
881
882 ;;; Move the arguments into the passing locations and do a (possibly
883 ;;; named) tail call.
884 (defun ir2-convert-tail-full-call (node block)
885   (declare (type combination node) (type ir2-block block))
886   (let* ((env (physenv-info (node-physenv node)))
887          (args (basic-combination-args node))
888          (nargs (length args))
889          (pass-refs (move-tail-full-call-args node block))
890          (old-fp (ir2-physenv-old-fp env))
891          (return-pc (ir2-physenv-return-pc env)))
892
893     (multiple-value-bind (fun-tn named)
894         (fun-continuation-tn node block (basic-combination-fun node))
895       (if named
896           (vop* tail-call-named node block
897                 (fun-tn old-fp return-pc pass-refs)
898                 (nil)
899                 nargs)
900           (vop* tail-call node block
901                 (fun-tn old-fp return-pc pass-refs)
902                 (nil)
903                 nargs))))
904
905   (values))
906
907 ;;; like IR2-CONVERT-LOCAL-CALL-ARGS, only different
908 (defun ir2-convert-full-call-args (node block)
909   (declare (type combination node) (type ir2-block block))
910   (let* ((args (basic-combination-args node))
911          (fp (make-stack-pointer-tn))
912          (nargs (length args)))
913     (vop allocate-full-call-frame node block nargs fp)
914     (collect ((locs))
915       (let ((last nil)
916             (first nil))
917         (dotimes (num nargs)
918           (locs (standard-arg-location num))
919           (let ((ref (reference-tn (continuation-tn node block (elt args num))
920                                    nil)))
921             (if last
922                 (setf (tn-ref-across last) ref)
923                 (setf first ref))
924             (setq last ref)))
925         
926         (values fp first (locs) nargs)))))
927
928 ;;; Do full call when a fixed number of values are desired. We make
929 ;;; STANDARD-RESULT-TNS for our continuation, then deliver the result
930 ;;; using MOVE-CONTINUATION-RESULT. We do named or normal call, as
931 ;;; appropriate.
932 (defun ir2-convert-fixed-full-call (node block)
933   (declare (type combination node) (type ir2-block block))
934   (multiple-value-bind (fp args arg-locs nargs)
935       (ir2-convert-full-call-args node block)
936     (let* ((cont (node-cont node))
937            (locs (standard-result-tns cont))
938            (loc-refs (reference-tn-list locs t))
939            (nvals (length locs)))
940       (multiple-value-bind (fun-tn named)
941           (fun-continuation-tn node block (basic-combination-fun node))
942         (if named
943             (vop* call-named node block (fp fun-tn args) (loc-refs)
944                   arg-locs nargs nvals)
945             (vop* call node block (fp fun-tn args) (loc-refs)
946                   arg-locs nargs nvals))
947         (move-continuation-result node block locs cont))))
948   (values))
949
950 ;;; Do full call when unknown values are desired.
951 (defun ir2-convert-multiple-full-call (node block)
952   (declare (type combination node) (type ir2-block block))
953   (multiple-value-bind (fp args arg-locs nargs)
954       (ir2-convert-full-call-args node block)
955     (let* ((cont (node-cont node))
956            (locs (ir2-continuation-locs (continuation-info cont)))
957            (loc-refs (reference-tn-list locs t)))
958       (multiple-value-bind (fun-tn named)
959           (fun-continuation-tn node block (basic-combination-fun node))
960         (if named
961             (vop* multiple-call-named node block (fp fun-tn args) (loc-refs)
962                   arg-locs nargs)
963             (vop* multiple-call node block (fp fun-tn args) (loc-refs)
964                   arg-locs nargs)))))
965   (values))
966
967 ;;; stuff to check in CHECK-FULL-CALL
968 ;;;
969 ;;; There are some things which are intended always to be optimized
970 ;;; away by DEFTRANSFORMs and such, and so never compiled into full
971 ;;; calls. This has been a source of bugs so many times that it seems
972 ;;; worth listing some of them here so that we can check the list
973 ;;; whenever we compile a full call.
974 ;;;
975 ;;; FIXME: It might be better to represent this property by setting a
976 ;;; flag in DEFKNOWN, instead of representing it by membership in this
977 ;;; list.
978 (defvar *always-optimized-away*
979   '(;; This should always be DEFTRANSFORMed away, but wasn't in a bug
980     ;; reported to cmucl-imp@cons.org 2000-06-20.
981     %instance-ref
982     ;; These should always turn into VOPs, but wasn't in a bug which
983     ;; appeared when LTN-POLICY stuff was being tweaked in
984     ;; sbcl-0.6.9.16. in sbcl-0.6.0
985     data-vector-set
986     data-vector-ref))
987
988 ;;; more stuff to check in CHECK-FULL-CALL
989 ;;;
990 ;;; These came in handy when troubleshooting cold boot after making
991 ;;; major changes in the package structure: various transforms and
992 ;;; VOPs and stuff got attached to the wrong symbol, so that
993 ;;; references to the right symbol were bogusly translated as full
994 ;;; calls instead of primitives, sending the system off into infinite
995 ;;; space. Having a report on all full calls generated makes it easier
996 ;;; to figure out what form caused the problem this time.
997 #!+sb-show (defvar *show-full-called-fnames-p* nil)
998 #!+sb-show (defvar *full-called-fnames* (make-hash-table :test 'equal))
999
1000 ;;; Do some checks on a full call:
1001 ;;;   * Is this a full call to something we have reason to know should
1002 ;;;     never be full called?
1003 ;;;   * Is this a full call to (SETF FOO) which might conflict with
1004 ;;;     a DEFSETF or some such thing elsewhere in the program?
1005 (defun check-full-call (node)
1006   (let* ((cont (basic-combination-fun node))
1007          (fname (continuation-fun-name cont t)))
1008     (declare (type (or symbol cons) fname))
1009
1010     #!+sb-show (unless (gethash fname *full-called-fnames*)
1011                  (setf (gethash fname *full-called-fnames*) t))
1012     #!+sb-show (when *show-full-called-fnames-p*
1013                  (/show "converting full call to named function" fname)
1014                  (/show (basic-combination-args node))
1015                  (/show (policy node speed) (policy node safety))
1016                  (/show (policy node compilation-speed))
1017                  (let ((arg-types (mapcar (lambda (maybe-continuation)
1018                                             (when maybe-continuation
1019                                               (type-specifier
1020                                                (continuation-type
1021                                                 maybe-continuation))))
1022                                           (basic-combination-args node))))
1023                    (/show arg-types)))
1024
1025     (when (memq fname *always-optimized-away*)
1026       (/show (policy node speed) (policy node safety))
1027       (/show (policy node compilation-speed))
1028       (error "internal error: full call to ~S" fname))
1029
1030     (when (consp fname)
1031       (destructuring-bind (setf stem) fname
1032         (aver (eq setf 'setf))
1033         (setf (gethash stem *setf-assumed-fboundp*) t)))))
1034
1035 ;;; If the call is in a tail recursive position and the return
1036 ;;; convention is standard, then do a tail full call. If one or fewer
1037 ;;; values are desired, then use a single-value call, otherwise use a
1038 ;;; multiple-values call.
1039 (defun ir2-convert-full-call (node block)
1040   (declare (type combination node) (type ir2-block block))
1041   (check-full-call node)
1042   (let ((2cont (continuation-info (node-cont node))))
1043     (cond ((node-tail-p node)
1044            (ir2-convert-tail-full-call node block))
1045           ((and 2cont
1046                 (eq (ir2-continuation-kind 2cont) :unknown))
1047            (ir2-convert-multiple-full-call node block))
1048           (t
1049            (ir2-convert-fixed-full-call node block))))
1050   (values))
1051 \f
1052 ;;;; entering functions
1053
1054 ;;; Do all the stuff that needs to be done on XEP entry:
1055 ;;; -- Create frame.
1056 ;;; -- Copy any more arg.
1057 ;;; -- Set up the environment, accessing any closure variables.
1058 ;;; -- Move args from the standard passing locations to their internal
1059 ;;;    locations.
1060 (defun init-xep-environment (node block fun)
1061   (declare (type bind node) (type ir2-block block) (type clambda fun))
1062   (let ((start-label (entry-info-offset (leaf-info fun)))
1063         (env (physenv-info (node-physenv node))))
1064     (let ((ef (functional-entry-fun fun)))
1065       (cond ((and (optional-dispatch-p ef) (optional-dispatch-more-entry ef))
1066              ;; Special case the xep-allocate-frame + copy-more-arg case.
1067              (vop xep-allocate-frame node block start-label t)
1068              (vop copy-more-arg node block (optional-dispatch-max-args ef)))
1069             (t
1070              ;; No more args, so normal entry.
1071              (vop xep-allocate-frame node block start-label nil)))
1072       (if (ir2-physenv-closure env)
1073           (let ((closure (make-normal-tn *backend-t-primitive-type*)))
1074             (vop setup-closure-environment node block start-label closure)
1075             (when (getf (functional-plist ef) :fin-function)
1076               (vop funcallable-instance-lexenv node block closure closure))
1077             (let ((n -1))
1078               (dolist (loc (ir2-physenv-closure env))
1079                 (vop closure-ref node block closure (incf n) (cdr loc)))))
1080           (vop setup-environment node block start-label)))
1081
1082     (unless (eq (functional-kind fun) :toplevel)
1083       (let ((vars (lambda-vars fun))
1084             (n 0))
1085         (when (leaf-refs (first vars))
1086           (emit-move node block (make-arg-count-location)
1087                      (leaf-info (first vars))))
1088         (dolist (arg (rest vars))
1089           (when (leaf-refs arg)
1090             (let ((pass (standard-arg-location n))
1091                   (home (leaf-info arg)))
1092               (if (lambda-var-indirect arg)
1093                   (do-make-value-cell node block pass home)
1094                   (emit-move node block pass home))))
1095           (incf n))))
1096
1097     (emit-move node block (make-old-fp-passing-location t)
1098                (ir2-physenv-old-fp env)))
1099
1100   (values))
1101
1102 ;;; Emit function prolog code. This is only called on bind nodes for
1103 ;;; functions that allocate environments. All semantics of let calls
1104 ;;; are handled by IR2-CONVERT-LET.
1105 ;;;
1106 ;;; If not an XEP, all we do is move the return PC from its passing
1107 ;;; location, since in a local call, the caller allocates the frame
1108 ;;; and sets up the arguments.
1109 (defun ir2-convert-bind (node block)
1110   (declare (type bind node) (type ir2-block block))
1111   (let* ((fun (bind-lambda node))
1112          (env (physenv-info (lambda-physenv fun))))
1113     (aver (member (functional-kind fun)
1114                   '(nil :external :optional :toplevel :cleanup)))
1115
1116     (when (xep-p fun)
1117       (init-xep-environment node block fun)
1118       #!+sb-dyncount
1119       (when *collect-dynamic-statistics*
1120         (vop count-me node block *dynamic-counts-tn*
1121              (block-number (ir2-block-block block)))))
1122
1123     (emit-move node
1124                block
1125                (ir2-physenv-return-pc-pass env)
1126                (ir2-physenv-return-pc env))
1127
1128     (let ((lab (gen-label)))
1129       (setf (ir2-physenv-environment-start env) lab)
1130       (vop note-environment-start node block lab)))
1131
1132   (values))
1133 \f
1134 ;;;; function return
1135
1136 ;;; Do stuff to return from a function with the specified values and
1137 ;;; convention. If the return convention is :FIXED and we aren't
1138 ;;; returning from an XEP, then we do a known return (letting
1139 ;;; representation selection insert the correct move-arg VOPs.)
1140 ;;; Otherwise, we use the unknown-values convention. If there is a
1141 ;;; fixed number of return values, then use RETURN, otherwise use
1142 ;;; RETURN-MULTIPLE.
1143 (defun ir2-convert-return (node block)
1144   (declare (type creturn node) (type ir2-block block))
1145   (let* ((cont (return-result node))
1146          (2cont (continuation-info cont))
1147          (cont-kind (ir2-continuation-kind 2cont))
1148          (fun (return-lambda node))
1149          (env (physenv-info (lambda-physenv fun)))
1150          (old-fp (ir2-physenv-old-fp env))
1151          (return-pc (ir2-physenv-return-pc env))
1152          (returns (tail-set-info (lambda-tail-set fun))))
1153     (cond
1154      ((and (eq (return-info-kind returns) :fixed)
1155            (not (xep-p fun)))
1156       (let ((locs (continuation-tns node block cont
1157                                     (return-info-types returns))))
1158         (vop* known-return node block
1159               (old-fp return-pc (reference-tn-list locs nil))
1160               (nil)
1161               (return-info-locations returns))))
1162      ((eq cont-kind :fixed)
1163       (let* ((types (mapcar #'tn-primitive-type (ir2-continuation-locs 2cont)))
1164              (cont-locs (continuation-tns node block cont types))
1165              (nvals (length cont-locs))
1166              (locs (make-standard-value-tns nvals)))
1167         (mapc (lambda (val loc)
1168                 (emit-move node block val loc))
1169               cont-locs
1170               locs)
1171         (if (= nvals 1)
1172             (vop return-single node block old-fp return-pc (car locs))
1173             (vop* return node block
1174                   (old-fp return-pc (reference-tn-list locs nil))
1175                   (nil)
1176                   nvals))))
1177      (t
1178       (aver (eq cont-kind :unknown))
1179       (vop* return-multiple node block
1180             (old-fp return-pc
1181                     (reference-tn-list (ir2-continuation-locs 2cont) nil))
1182             (nil)))))
1183
1184   (values))
1185 \f
1186 ;;;; debugger hooks
1187
1188 ;;; This is used by the debugger to find the top function on the
1189 ;;; stack. It returns the OLD-FP and RETURN-PC for the current
1190 ;;; function as multiple values.
1191 (defoptimizer (sb!kernel:%caller-frame-and-pc ir2-convert) (() node block)
1192   (let ((ir2-physenv (physenv-info (node-physenv node))))
1193     (move-continuation-result node block
1194                               (list (ir2-physenv-old-fp ir2-physenv)
1195                                     (ir2-physenv-return-pc ir2-physenv))
1196                               (node-cont node))))
1197 \f
1198 ;;;; multiple values
1199
1200 ;;; This is almost identical to IR2-Convert-Let. Since LTN annotates
1201 ;;; the continuation for the correct number of values (with the
1202 ;;; continuation user responsible for defaulting), we can just pick
1203 ;;; them up from the continuation.
1204 (defun ir2-convert-mv-bind (node block)
1205   (declare (type mv-combination node) (type ir2-block block))
1206   (let* ((cont (first (basic-combination-args node)))
1207          (fun (ref-leaf (continuation-use (basic-combination-fun node))))
1208          (vars (lambda-vars fun)))
1209     (aver (eq (functional-kind fun) :mv-let))
1210     (mapc (lambda (src var)
1211             (when (leaf-refs var)
1212               (let ((dest (leaf-info var)))
1213                 (if (lambda-var-indirect var)
1214                     (do-make-value-cell node block src dest)
1215                     (emit-move node block src dest)))))
1216           (continuation-tns node block cont
1217                             (mapcar (lambda (x)
1218                                       (primitive-type (leaf-type x)))
1219                                     vars))
1220           vars))
1221   (values))
1222
1223 ;;; Emit the appropriate fixed value, unknown value or tail variant of
1224 ;;; CALL-VARIABLE. Note that we only need to pass the values start for
1225 ;;; the first argument: all the other argument continuation TNs are
1226 ;;; ignored. This is because we require all of the values globs to be
1227 ;;; contiguous and on stack top.
1228 (defun ir2-convert-mv-call (node block)
1229   (declare (type mv-combination node) (type ir2-block block))
1230   (aver (basic-combination-args node))
1231   (let* ((start-cont (continuation-info (first (basic-combination-args node))))
1232          (start (first (ir2-continuation-locs start-cont)))
1233          (tails (and (node-tail-p node)
1234                      (lambda-tail-set (node-home-lambda node))))
1235          (cont (node-cont node))
1236          (2cont (continuation-info cont)))
1237     (multiple-value-bind (fun named)
1238         (fun-continuation-tn node block (basic-combination-fun node))
1239       (aver (and (not named)
1240                  (eq (ir2-continuation-kind start-cont) :unknown)))
1241       (cond
1242        (tails
1243         (let ((env (physenv-info (node-physenv node))))
1244           (vop tail-call-variable node block start fun
1245                (ir2-physenv-old-fp env)
1246                (ir2-physenv-return-pc env))))
1247        ((and 2cont
1248              (eq (ir2-continuation-kind 2cont) :unknown))
1249         (vop* multiple-call-variable node block (start fun nil)
1250               ((reference-tn-list (ir2-continuation-locs 2cont) t))))
1251        (t
1252         (let ((locs (standard-result-tns cont)))
1253           (vop* call-variable node block (start fun nil)
1254                 ((reference-tn-list locs t)) (length locs))
1255           (move-continuation-result node block locs cont)))))))
1256
1257 ;;; Reset the stack pointer to the start of the specified
1258 ;;; unknown-values continuation (discarding it and all values globs on
1259 ;;; top of it.)
1260 (defoptimizer (%pop-values ir2-convert) ((continuation) node block)
1261   (let ((2cont (continuation-info (continuation-value continuation))))
1262     (aver (eq (ir2-continuation-kind 2cont) :unknown))
1263     (vop reset-stack-pointer node block
1264          (first (ir2-continuation-locs 2cont)))))
1265
1266 ;;; Deliver the values TNs to CONT using MOVE-CONTINUATION-RESULT.
1267 (defoptimizer (values ir2-convert) ((&rest values) node block)
1268   (let ((tns (mapcar (lambda (x)
1269                        (continuation-tn node block x))
1270                      values)))
1271     (move-continuation-result node block tns (node-cont node))))
1272
1273 ;;; In the normal case where unknown values are desired, we use the
1274 ;;; VALUES-LIST VOP. In the relatively unimportant case of VALUES-LIST
1275 ;;; for a fixed number of values, we punt by doing a full call to the
1276 ;;; VALUES-LIST function. This gets the full call VOP to deal with
1277 ;;; defaulting any unsupplied values. It seems unworthwhile to
1278 ;;; optimize this case.
1279 (defoptimizer (values-list ir2-convert) ((list) node block)
1280   (let* ((cont (node-cont node))
1281          (2cont (continuation-info cont)))
1282     (when 2cont
1283       (ecase (ir2-continuation-kind 2cont)
1284         (:fixed (ir2-convert-full-call node block))
1285         (:unknown
1286          (let ((locs (ir2-continuation-locs 2cont)))
1287            (vop* values-list node block
1288                  ((continuation-tn node block list) nil)
1289                  ((reference-tn-list locs t)))))))))
1290
1291 (defoptimizer (%more-arg-values ir2-convert) ((context start count) node block)
1292   (let* ((cont (node-cont node))
1293          (2cont (continuation-info cont)))
1294     (when 2cont
1295       (ecase (ir2-continuation-kind 2cont)
1296         (:fixed (ir2-convert-full-call node block))
1297         (:unknown
1298          (let ((locs (ir2-continuation-locs 2cont)))
1299            (vop* %more-arg-values node block
1300                  ((continuation-tn node block context)
1301                   (continuation-tn node block start)
1302                   (continuation-tn node block count)
1303                   nil)
1304                  ((reference-tn-list locs t)))))))))
1305 \f
1306 ;;;; special binding
1307
1308 ;;; This is trivial, given our assumption of a shallow-binding
1309 ;;; implementation.
1310 (defoptimizer (%special-bind ir2-convert) ((var value) node block)
1311   (let ((name (leaf-source-name (continuation-value var))))
1312     (vop bind node block (continuation-tn node block value)
1313          (emit-constant name))))
1314 (defoptimizer (%special-unbind ir2-convert) ((var) node block)
1315   (vop unbind node block))
1316
1317 ;;; ### It's not clear that this really belongs in this file, or
1318 ;;; should really be done this way, but this is the least violation of
1319 ;;; abstraction in the current setup. We don't want to wire
1320 ;;; shallow-binding assumptions into IR1tran.
1321 (def-ir1-translator progv ((vars vals &body body) start cont)
1322   (ir1-convert
1323    start cont
1324    (once-only ((n-save-bs '(%primitive current-binding-pointer)))
1325      `(unwind-protect
1326           (progn
1327             (mapc (lambda (var val)
1328                     (%primitive bind val var))
1329                   ,vars
1330                   ,vals)
1331             ,@body)
1332         (%primitive unbind-to-here ,n-save-bs)))))
1333 \f
1334 ;;;; non-local exit
1335
1336 ;;; Convert a non-local lexical exit. First find the NLX-Info in our
1337 ;;; environment. Note that this is never called on the escape exits
1338 ;;; for CATCH and UNWIND-PROTECT, since the escape functions aren't
1339 ;;; IR2 converted.
1340 (defun ir2-convert-exit (node block)
1341   (declare (type exit node) (type ir2-block block))
1342   (let ((loc (find-in-physenv (find-nlx-info (exit-entry node)
1343                                              (node-cont node))
1344                               (node-physenv node)))
1345         (temp (make-stack-pointer-tn))
1346         (value (exit-value node)))
1347     (vop value-cell-ref node block loc temp)
1348     (if value
1349         (let ((locs (ir2-continuation-locs (continuation-info value))))
1350           (vop unwind node block temp (first locs) (second locs)))
1351         (let ((0-tn (emit-constant 0)))
1352           (vop unwind node block temp 0-tn 0-tn))))
1353
1354   (values))
1355
1356 ;;; %CLEANUP-POINT doesn't do anything except prevent the body from
1357 ;;; being entirely deleted.
1358 (defoptimizer (%cleanup-point ir2-convert) (() node block) node block)
1359
1360 ;;; This function invalidates a lexical exit on exiting from the
1361 ;;; dynamic extent. This is done by storing 0 into the indirect value
1362 ;;; cell that holds the closed unwind block.
1363 (defoptimizer (%lexical-exit-breakup ir2-convert) ((info) node block)
1364   (vop value-cell-set node block
1365        (find-in-physenv (continuation-value info) (node-physenv node))
1366        (emit-constant 0)))
1367
1368 ;;; We have to do a spurious move of no values to the result
1369 ;;; continuation so that lifetime analysis won't get confused.
1370 (defun ir2-convert-throw (node block)
1371   (declare (type mv-combination node) (type ir2-block block))
1372   (let ((args (basic-combination-args node)))
1373     (vop* throw node block
1374           ((continuation-tn node block (first args))
1375            (reference-tn-list
1376             (ir2-continuation-locs (continuation-info (second args)))
1377             nil))
1378           (nil)))
1379   (move-continuation-result node block () (node-cont node))
1380   (values))
1381
1382 ;;; Emit code to set up a non-local exit. INFO is the NLX-Info for the
1383 ;;; exit, and TAG is the continuation for the catch tag (if any.) We
1384 ;;; get at the target PC by passing in the label to the vop. The vop
1385 ;;; is responsible for building a return-PC object.
1386 (defun emit-nlx-start (node block info tag)
1387   (declare (type node node) (type ir2-block block) (type nlx-info info)
1388            (type (or continuation null) tag))
1389   (let* ((2info (nlx-info-info info))
1390          (kind (cleanup-kind (nlx-info-cleanup info)))
1391          (block-tn (physenv-live-tn
1392                     (make-normal-tn (primitive-type-or-lose 'catch-block))
1393                     (node-physenv node)))
1394          (res (make-stack-pointer-tn))
1395          (target-label (ir2-nlx-info-target 2info)))
1396
1397     (vop current-binding-pointer node block
1398          (car (ir2-nlx-info-dynamic-state 2info)))
1399     (vop* save-dynamic-state node block
1400           (nil)
1401           ((reference-tn-list (cdr (ir2-nlx-info-dynamic-state 2info)) t)))
1402     (vop current-stack-pointer node block (ir2-nlx-info-save-sp 2info))
1403
1404     (ecase kind
1405       (:catch
1406        (vop make-catch-block node block block-tn
1407             (continuation-tn node block tag) target-label res))
1408       ((:unwind-protect :block :tagbody)
1409        (vop make-unwind-block node block block-tn target-label res)))
1410
1411     (ecase kind
1412       ((:block :tagbody)
1413        (do-make-value-cell node block res (ir2-nlx-info-home 2info)))
1414       (:unwind-protect
1415        (vop set-unwind-protect node block block-tn))
1416       (:catch)))
1417
1418   (values))
1419
1420 ;;; Scan each of ENTRY's exits, setting up the exit for each lexical exit.
1421 (defun ir2-convert-entry (node block)
1422   (declare (type entry node) (type ir2-block block))
1423   (dolist (exit (entry-exits node))
1424     (let ((info (find-nlx-info node (node-cont exit))))
1425       (when (and info
1426                  (member (cleanup-kind (nlx-info-cleanup info))
1427                          '(:block :tagbody)))
1428         (emit-nlx-start node block info nil))))
1429   (values))
1430
1431 ;;; Set up the unwind block for these guys.
1432 (defoptimizer (%catch ir2-convert) ((info-cont tag) node block)
1433   (emit-nlx-start node block (continuation-value info-cont) tag))
1434 (defoptimizer (%unwind-protect ir2-convert) ((info-cont cleanup) node block)
1435   (emit-nlx-start node block (continuation-value info-cont) nil))
1436
1437 ;;; Emit the entry code for a non-local exit. We receive values and
1438 ;;; restore dynamic state.
1439 ;;;
1440 ;;; In the case of a lexical exit or CATCH, we look at the exit
1441 ;;; continuation's kind to determine which flavor of entry VOP to
1442 ;;; emit. If unknown values, emit the xxx-MULTIPLE variant to the
1443 ;;; continuation locs. If fixed values, make the appropriate number of
1444 ;;; temps in the standard values locations and use the other variant,
1445 ;;; delivering the temps to the continuation using
1446 ;;; MOVE-CONTINUATION-RESULT.
1447 ;;;
1448 ;;; In the UNWIND-PROTECT case, we deliver the first register
1449 ;;; argument, the argument count and the argument pointer to our
1450 ;;; continuation as multiple values. These values are the block exited
1451 ;;; to and the values start and count.
1452 ;;;
1453 ;;; After receiving values, we restore dynamic state. Except in the
1454 ;;; UNWIND-PROTECT case, the values receiving restores the stack
1455 ;;; pointer. In an UNWIND-PROTECT cleanup, we want to leave the stack
1456 ;;; pointer alone, since the thrown values are still out there.
1457 (defoptimizer (%nlx-entry ir2-convert) ((info-cont) node block)
1458   (let* ((info (continuation-value info-cont))
1459          (cont (nlx-info-continuation info))
1460          (2cont (continuation-info cont))
1461          (2info (nlx-info-info info))
1462          (top-loc (ir2-nlx-info-save-sp 2info))
1463          (start-loc (make-nlx-entry-arg-start-location))
1464          (count-loc (make-arg-count-location))
1465          (target (ir2-nlx-info-target 2info)))
1466
1467     (ecase (cleanup-kind (nlx-info-cleanup info))
1468       ((:catch :block :tagbody)
1469        (if (and 2cont (eq (ir2-continuation-kind 2cont) :unknown))
1470            (vop* nlx-entry-multiple node block
1471                  (top-loc start-loc count-loc nil)
1472                  ((reference-tn-list (ir2-continuation-locs 2cont) t))
1473                  target)
1474            (let ((locs (standard-result-tns cont)))
1475              (vop* nlx-entry node block
1476                    (top-loc start-loc count-loc nil)
1477                    ((reference-tn-list locs t))
1478                    target
1479                    (length locs))
1480              (move-continuation-result node block locs cont))))
1481       (:unwind-protect
1482        (let ((block-loc (standard-arg-location 0)))
1483          (vop uwp-entry node block target block-loc start-loc count-loc)
1484          (move-continuation-result
1485           node block
1486           (list block-loc start-loc count-loc)
1487           cont))))
1488
1489     #!+sb-dyncount
1490     (when *collect-dynamic-statistics*
1491       (vop count-me node block *dynamic-counts-tn*
1492            (block-number (ir2-block-block block))))
1493
1494     (vop* restore-dynamic-state node block
1495           ((reference-tn-list (cdr (ir2-nlx-info-dynamic-state 2info)) nil))
1496           (nil))
1497     (vop unbind-to-here node block
1498          (car (ir2-nlx-info-dynamic-state 2info)))))
1499 \f
1500 ;;;; n-argument functions
1501
1502 (macrolet ((def (name)
1503              `(defoptimizer (,name ir2-convert) ((&rest args) node block)
1504                 (let* ((refs (move-tail-full-call-args node block))
1505                        (cont (node-cont node))
1506                        (res (continuation-result-tns
1507                              cont
1508                              (list (primitive-type (specifier-type 'list))))))
1509                   (vop* ,name node block (refs) ((first res) nil)
1510                         (length args))
1511                   (move-continuation-result node block res cont)))))
1512   (def list)
1513   (def list*))
1514 \f
1515 ;;; Convert the code in a component into VOPs.
1516 (defun ir2-convert (component)
1517   (declare (type component component))
1518   (let (#!+sb-dyncount
1519         (*dynamic-counts-tn*
1520          (when *collect-dynamic-statistics*
1521            (let* ((blocks
1522                    (block-number (block-next (component-head component))))
1523                   (counts (make-array blocks
1524                                       :element-type '(unsigned-byte 32)
1525                                       :initial-element 0))
1526                   (info (make-dyncount-info
1527                          :for (component-name component)
1528                          :costs (make-array blocks
1529                                             :element-type '(unsigned-byte 32)
1530                                             :initial-element 0)
1531                          :counts counts)))
1532              (setf (ir2-component-dyncount-info (component-info component))
1533                    info)
1534              (emit-constant info)
1535              (emit-constant counts)))))
1536     (let ((num 0))
1537       (declare (type index num))
1538       (do-ir2-blocks (2block component)
1539         (let ((block (ir2-block-block 2block)))
1540           (when (block-start block)
1541             (setf (block-number block) num)
1542             #!+sb-dyncount
1543             (when *collect-dynamic-statistics*
1544               (let ((first-node (continuation-next (block-start block))))
1545                 (unless (or (and (bind-p first-node)
1546                                  (xep-p (bind-lambda first-node)))
1547                             (eq (continuation-fun-name
1548                                  (node-cont first-node))
1549                                 '%nlx-entry))
1550                   (vop count-me
1551                        first-node
1552                        2block
1553                        #!+sb-dyncount *dynamic-counts-tn* #!-sb-dyncount nil
1554                        num))))
1555             (ir2-convert-block block)
1556             (incf num))))))
1557   (values))
1558
1559 ;;; If necessary, emit a terminal unconditional branch to go to the
1560 ;;; successor block. If the successor is the component tail, then
1561 ;;; there isn't really any successor, but if the end is an unknown,
1562 ;;; non-tail call, then we emit an error trap just in case the
1563 ;;; function really does return.
1564 (defun finish-ir2-block (block)
1565   (declare (type cblock block))
1566   (let* ((2block (block-info block))
1567          (last (block-last block))
1568          (succ (block-succ block)))
1569     (unless (if-p last)
1570       (aver (and succ (null (rest succ))))
1571       (let ((target (first succ)))
1572         (cond ((eq target (component-tail (block-component block)))
1573                (when (and (basic-combination-p last)
1574                           (eq (basic-combination-kind last) :full))
1575                  (let* ((fun (basic-combination-fun last))
1576                         (use (continuation-use fun))
1577                         (name (and (ref-p use)
1578                                    (leaf-has-source-name-p (ref-leaf use))
1579                                    (leaf-source-name (ref-leaf use)))))
1580                    (unless (or (node-tail-p last)
1581                                (info :function :info name)
1582                                (policy last (zerop safety)))
1583                      (vop nil-fun-returned-error last 2block
1584                           (if name
1585                               (emit-constant name)
1586                               (multiple-value-bind (tn named)
1587                                   (fun-continuation-tn last 2block fun)
1588                                 (aver (not named))
1589                                 tn)))))))
1590               ((not (eq (ir2-block-next 2block) (block-info target)))
1591                (vop branch last 2block (block-label target)))))))
1592
1593   (values))
1594
1595 ;;; Convert the code in a block into VOPs.
1596 (defun ir2-convert-block (block)
1597   (declare (type cblock block))
1598   (let ((2block (block-info block)))
1599     (do-nodes (node cont block)
1600       (etypecase node
1601         (ref
1602          (let ((2cont (continuation-info cont)))
1603            (when (and 2cont
1604                       (not (eq (ir2-continuation-kind 2cont) :delayed)))
1605              (ir2-convert-ref node 2block))))
1606         (combination
1607          (let ((kind (basic-combination-kind node)))
1608            (case kind
1609              (:local
1610               (ir2-convert-local-call node 2block))
1611              (:full
1612               (ir2-convert-full-call node 2block))
1613              (t
1614               (let ((fun (fun-info-ir2-convert kind)))
1615                 (cond (fun
1616                        (funcall fun node 2block))
1617                       ((eq (basic-combination-info node) :full)
1618                        (ir2-convert-full-call node 2block))
1619                       (t
1620                        (ir2-convert-template node 2block))))))))
1621         (cif
1622          (when (continuation-info (if-test node))
1623            (ir2-convert-if node 2block)))
1624         (bind
1625          (let ((fun (bind-lambda node)))
1626            (when (eq (lambda-home fun) fun)
1627              (ir2-convert-bind node 2block))))
1628         (creturn
1629          (ir2-convert-return node 2block))
1630         (cset
1631          (ir2-convert-set node 2block))
1632         (mv-combination
1633          (cond
1634           ((eq (basic-combination-kind node) :local)
1635            (ir2-convert-mv-bind node 2block))
1636           ((eq (continuation-fun-name (basic-combination-fun node))
1637                '%throw)
1638            (ir2-convert-throw node 2block))
1639           (t
1640            (ir2-convert-mv-call node 2block))))
1641         (exit
1642          (when (exit-entry node)
1643            (ir2-convert-exit node 2block)))
1644         (entry
1645          (ir2-convert-entry node 2block)))))
1646
1647   (finish-ir2-block block)
1648
1649   (values))