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