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