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