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