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