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