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