x86-64 disentwingling of fixnums and words.
[sbcl.git] / src / compiler / x86-64 / call.lisp
1 ;;;; function call for the x86 VM
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!VM")
13 \f
14 ;;;; interfaces to IR2 conversion
15
16 ;;; Return a wired TN describing the N'th full call argument passing
17 ;;; location.
18 (!def-vm-support-routine standard-arg-location (n)
19   (declare (type unsigned-byte n))
20   (if (< n register-arg-count)
21       (make-wired-tn *backend-t-primitive-type* descriptor-reg-sc-number
22                      (nth n *register-arg-offsets*))
23       (make-wired-tn *backend-t-primitive-type* control-stack-sc-number n)))
24
25 ;;; Make a passing location TN for a local call return PC.
26 ;;;
27 ;;; Always wire the return PC location to the stack in its standard
28 ;;; location.
29 (!def-vm-support-routine make-return-pc-passing-location (standard)
30   (declare (ignore standard))
31   (make-wired-tn (primitive-type-or-lose 'system-area-pointer)
32                  sap-stack-sc-number return-pc-save-offset))
33
34 ;;; This is similar to MAKE-RETURN-PC-PASSING-LOCATION, but makes a
35 ;;; location to pass OLD-FP in.
36 ;;;
37 ;;; This is wired in both the standard and the local-call conventions,
38 ;;; because we want to be able to assume it's always there. Besides,
39 ;;; the x86 doesn't have enough registers to really make it profitable
40 ;;; to pass it in a register.
41 (!def-vm-support-routine make-old-fp-passing-location (standard)
42   (declare (ignore standard))
43   (make-wired-tn *fixnum-primitive-type* control-stack-sc-number
44                  ocfp-save-offset))
45
46 ;;; Make the TNs used to hold OLD-FP and RETURN-PC within the current
47 ;;; function. We treat these specially so that the debugger can find
48 ;;; them at a known location.
49 ;;;
50 ;;; Without using a save-tn - which does not make much sense if it is
51 ;;; wired to the stack?
52 (!def-vm-support-routine make-old-fp-save-location (physenv)
53   (physenv-debug-live-tn (make-wired-tn *fixnum-primitive-type*
54                                         control-stack-sc-number
55                                         ocfp-save-offset)
56                          physenv))
57 (!def-vm-support-routine make-return-pc-save-location (physenv)
58   (physenv-debug-live-tn
59    (make-wired-tn (primitive-type-or-lose 'system-area-pointer)
60                   sap-stack-sc-number return-pc-save-offset)
61    physenv))
62
63 ;;; Make a TN for the standard argument count passing location. We only
64 ;;; need to make the standard location, since a count is never passed when we
65 ;;; are using non-standard conventions.
66 (!def-vm-support-routine make-arg-count-location ()
67   (make-wired-tn *fixnum-primitive-type* any-reg-sc-number rcx-offset))
68
69 ;;; Make a TN to hold the number-stack frame pointer. This is allocated
70 ;;; once per component, and is component-live.
71 (!def-vm-support-routine make-nfp-tn ()
72   (make-restricted-tn *fixnum-primitive-type* ignore-me-sc-number))
73
74 (!def-vm-support-routine make-stack-pointer-tn ()
75   (make-normal-tn *fixnum-primitive-type*))
76
77 (!def-vm-support-routine make-number-stack-pointer-tn ()
78   (make-restricted-tn *fixnum-primitive-type* ignore-me-sc-number))
79
80 ;;; Return a list of TNs that can be used to represent an unknown-values
81 ;;; continuation within a function.
82 (!def-vm-support-routine make-unknown-values-locations ()
83   (list (make-stack-pointer-tn)
84         (make-normal-tn *fixnum-primitive-type*)))
85
86 ;;; This function is called by the ENTRY-ANALYZE phase, allowing
87 ;;; VM-dependent initialization of the IR2-COMPONENT structure. We
88 ;;; push placeholder entries in the CONSTANTS to leave room for
89 ;;; additional noise in the code object header.
90 (!def-vm-support-routine select-component-format (component)
91   (declare (type component component))
92   ;; The 1+ here is because for the x86 the first constant is a
93   ;; pointer to a list of fixups, or NIL if the code object has none.
94   ;; (If I understand correctly, the fixups are needed at GC copy
95   ;; time because the X86 code isn't relocatable.)
96   ;;
97   ;; KLUDGE: It'd be cleaner to have the fixups entry be a named
98   ;; element of the CODE (aka component) primitive object. However,
99   ;; it's currently a large, tricky, error-prone chore to change
100   ;; the layout of any primitive object, so for the foreseeable future
101   ;; we'll just live with this ugliness. -- WHN 2002-01-02
102   (dotimes (i (1+ code-constants-offset))
103     (vector-push-extend nil
104                         (ir2-component-constants (component-info component))))
105   (values))
106 \f
107 ;;;; frame hackery
108
109 ;;; This is used for setting up the Old-FP in local call.
110 (define-vop (current-fp)
111   (:results (val :scs (any-reg control-stack)))
112   (:generator 1
113     (move val rbp-tn)))
114
115 ;;; We don't have a separate NFP, so we don't need to do anything here.
116 (define-vop (compute-old-nfp)
117   (:results (val))
118   (:ignore val)
119   (:generator 1
120     nil))
121
122 ;;; Accessing a slot from an earlier stack frame is definite hackery.
123 (define-vop (ancestor-frame-ref)
124   (:args (frame-pointer :scs (descriptor-reg))
125          (variable-home-tn :load-if nil))
126   (:results (value :scs (descriptor-reg any-reg)))
127   (:policy :fast-safe)
128   (:generator 4
129     (aver (sc-is variable-home-tn control-stack))
130     (loadw value frame-pointer
131            (frame-word-offset (tn-offset variable-home-tn)))))
132 (define-vop (ancestor-frame-set)
133   (:args (frame-pointer :scs (descriptor-reg))
134          (value :scs (descriptor-reg any-reg)))
135   (:results (variable-home-tn :load-if nil))
136   (:policy :fast-safe)
137   (:generator 4
138     (aver (sc-is variable-home-tn control-stack))
139     (storew value frame-pointer
140             (frame-word-offset (tn-offset variable-home-tn)))))
141
142 (macrolet ((define-frame-op
143                (suffix sc stack-sc instruction
144                 &optional (ea
145                            `(make-ea :qword
146                                      :base frame-pointer
147                                      :disp (frame-byte-offset
148                                             (tn-offset variable-home-tn)))))
149                (let ((reffer (symbolicate 'ancestor-frame-ref '/ suffix))
150                      (setter (symbolicate 'ancestor-frame-set '/ suffix)))
151                  `(progn
152                     (define-vop (,reffer ancestor-frame-ref)
153                       (:results (value :scs (,sc)))
154                       (:generator 4
155                         (aver (sc-is variable-home-tn ,stack-sc))
156                         (inst ,instruction value
157                               ,ea)))
158                     (define-vop (,setter ancestor-frame-set)
159                       (:args (frame-pointer :scs (descriptor-reg))
160                              (value :scs (,sc)))
161                       (:generator 4
162                         (aver (sc-is variable-home-tn ,stack-sc))
163                         (inst ,instruction ,ea value)))))))
164   (define-frame-op double-float double-reg double-stack movsd)
165   (define-frame-op single-float single-reg single-stack movss)
166   (define-frame-op complex-double-float complex-double-reg complex-double-stack
167     movupd (ea-for-cdf-data-stack variable-home-tn frame-pointer))
168   (define-frame-op complex-single-float complex-single-reg complex-single-stack
169     movq   (ea-for-csf-data-stack variable-home-tn frame-pointer))
170   (define-frame-op signed-byte-64 signed-reg signed-stack mov)
171   (define-frame-op unsigned-byte-64 unsigned-reg unsigned-stack mov)
172   (define-frame-op system-area-pointer sap-reg sap-stack mov))
173
174 (defun primitive-type-indirect-cell-type (ptype)
175   (declare (type primitive-type ptype))
176   (macrolet ((foo (&body data)
177                  `(case (primitive-type-name ptype)
178                     ,@(loop for (name stack-sc ref set) in data
179                             collect
180                             `(,name
181                                (load-time-value
182                                 (list (primitive-type-or-lose ',name)
183                                       (sc-or-lose ',stack-sc)
184                                       (lambda (node block fp value res)
185                                         (sb!c::vop ,ref node block
186                                                    fp value res))
187                                       (lambda (node block fp new-val value)
188                                         (sb!c::vop ,set node block
189                                                    fp new-val value)))))))))
190     (foo (double-float double-stack
191                        ancestor-frame-ref/double-float
192                        ancestor-frame-set/double-float)
193          (single-float single-stack
194                        ancestor-frame-ref/single-float
195                        ancestor-frame-set/single-float)
196          (complex-double-float complex-double-stack
197                                ancestor-frame-ref/complex-double-float
198                                ancestor-frame-set/complex-double-float)
199          (complex-single-float complex-single-stack
200                                ancestor-frame-ref/complex-single-float
201                                ancestor-frame-set/complex-single-float)
202          (signed-byte-64 signed-stack
203                          ancestor-frame-ref/signed-byte-64
204                          ancestor-frame-set/signed-byte-64)
205          (unsigned-byte-64 unsigned-stack
206                            ancestor-frame-ref/unsigned-byte-64
207                            ancestor-frame-set/unsigned-byte-64)
208          (unsigned-byte-63 unsigned-stack
209                            ancestor-frame-ref/unsigned-byte-64
210                            ancestor-frame-set/unsigned-byte-64)
211          (system-area-pointer sap-stack
212                               ancestor-frame-ref/system-area-pointer
213                               ancestor-frame-set/system-area-pointer))))
214
215 (define-vop (xep-allocate-frame)
216   (:info start-lab copy-more-arg-follows)
217   (:vop-var vop)
218   (:generator 1
219     (emit-alignment n-lowtag-bits)
220     (trace-table-entry trace-table-fun-prologue)
221     (emit-label start-lab)
222     ;; Skip space for the function header.
223     (inst simple-fun-header-word)
224     (dotimes (i (* n-word-bytes (1- simple-fun-code-offset)))
225       (inst byte 0))
226
227     ;; The start of the actual code.
228     ;; Save the return-pc.
229     (popw rbp-tn (frame-word-offset return-pc-save-offset))
230
231     ;; If copy-more-arg follows it will allocate the correct stack
232     ;; size. The stack is not allocated first here as this may expose
233     ;; args on the stack if they take up more space than the frame!
234     (unless copy-more-arg-follows
235       ;; The args fit within the frame so just allocate the frame.
236       (inst lea rsp-tn
237             (make-ea :qword :base rbp-tn
238                      :disp (- (* n-word-bytes
239                                  (- (max 3 (sb-allocated-size 'stack))
240                                     sp->fp-offset))))))
241
242     (trace-table-entry trace-table-normal)))
243
244 ;;; This is emitted directly before either a known-call-local, call-local,
245 ;;; or a multiple-call-local. All it does is allocate stack space for the
246 ;;; callee (who has the same size stack as us).
247 (define-vop (allocate-frame)
248   (:results (res :scs (any-reg))
249             (nfp))
250   (:info callee)
251   (:ignore nfp callee)
252   (:generator 2
253     (inst lea res (make-ea :qword :base rsp-tn
254                            :disp (- (* sp->fp-offset n-word-bytes))))
255     (inst sub rsp-tn (* n-word-bytes (sb-allocated-size 'stack)))))
256
257 ;;; Allocate a partial frame for passing stack arguments in a full
258 ;;; call. NARGS is the number of arguments passed. We allocate at
259 ;;; least 3 slots, because the XEP noise is going to want to use them
260 ;;; before it can extend the stack.
261 (define-vop (allocate-full-call-frame)
262   (:info nargs)
263   (:results (res :scs (any-reg)))
264   (:generator 2
265     (inst lea res (make-ea :qword :base rsp-tn
266                            :disp (- (* sp->fp-offset n-word-bytes))))
267     (inst sub rsp-tn (* (max nargs 3) n-word-bytes))))
268 \f
269 ;;; Emit code needed at the return-point from an unknown-values call
270 ;;; for a fixed number of values. Values is the head of the TN-REF
271 ;;; list for the locations that the values are to be received into.
272 ;;; Nvals is the number of values that are to be received (should
273 ;;; equal the length of Values).
274 ;;;
275 ;;; If 0 or 1 values are expected, then we just emit an instruction to
276 ;;; reset the SP (which will only be executed when other than 1 value
277 ;;; is returned.)
278 ;;;
279 ;;; In the general case we have to do three things:
280 ;;;  -- Default unsupplied register values. This need only be done
281 ;;;     when a single value is returned, since register values are
282 ;;;     defaulted by the called in the non-single case.
283 ;;;  -- Default unsupplied stack values. This needs to be done whenever
284 ;;;     there are stack values.
285 ;;;  -- Reset SP. This must be done whenever other than 1 value is
286 ;;;     returned, regardless of the number of values desired.
287 (defun default-unknown-values (vop values nvals node)
288   (declare (type (or tn-ref null) values)
289            (type unsigned-byte nvals))
290   (let ((type (sb!c::basic-combination-derived-type node)))
291     (cond
292       ((<= nvals 1)
293        (note-this-location vop :single-value-return)
294        (cond
295          ((<= (sb!kernel:values-type-max-value-count type)
296               register-arg-count)
297           (when (and (named-type-p type)
298                      (eq nil (named-type-name type)))
299             ;; The function never returns, it may happen that the code
300             ;; ends right here leavig the :SINGLE-VALUE-RETURN note
301             ;; dangling. Let's emit a NOP.
302             (inst nop)))
303          ((not (sb!kernel:values-type-may-be-single-value-p type))
304           (inst mov rsp-tn rbx-tn))
305          (t
306           (inst cmov :c rsp-tn rbx-tn))))
307       ((<= nvals register-arg-count)
308        (note-this-location vop :unknown-return)
309        (when (sb!kernel:values-type-may-be-single-value-p type)
310          (let ((regs-defaulted (gen-label)))
311            (inst jmp :c regs-defaulted)
312            ;; Default the unsupplied registers.
313            (let* ((2nd-tn-ref (tn-ref-across values))
314                   (2nd-tn (tn-ref-tn 2nd-tn-ref)))
315              (inst mov 2nd-tn nil-value)
316              (when (> nvals 2)
317                (loop
318                 for tn-ref = (tn-ref-across 2nd-tn-ref)
319                 then (tn-ref-across tn-ref)
320                 for count from 2 below register-arg-count
321                 do (inst mov (tn-ref-tn tn-ref) 2nd-tn))))
322            (inst mov rbx-tn rsp-tn)
323            (emit-label regs-defaulted)))
324        (when (< register-arg-count
325                 (sb!kernel:values-type-max-value-count type))
326          (inst mov rsp-tn rbx-tn)))
327       ((<= nvals 7)
328        ;; The number of bytes depends on the relative jump instructions.
329        ;; Best case is 31+(n-3)*14, worst case is 35+(n-3)*18. For
330        ;; NVALS=6 that is 73/89 bytes, and for NVALS=7 that is 87/107
331        ;; bytes which is likely better than using the blt below.
332        (let ((regs-defaulted (gen-label))
333              (defaulting-done (gen-label))
334              (default-stack-slots (gen-label)))
335          (note-this-location vop :unknown-return)
336          ;; Branch off to the MV case.
337          (inst jmp :c regs-defaulted)
338          ;; Do the single value case.
339          ;; Default the register args
340          (inst mov rax-tn nil-value)
341          (do ((i 1 (1+ i))
342               (val (tn-ref-across values) (tn-ref-across val)))
343              ((= i (min nvals register-arg-count)))
344            (inst mov (tn-ref-tn val) rax-tn))
345          ;; Fake other registers so it looks like we returned with all the
346          ;; registers filled in.
347          (move rbx-tn rsp-tn)
348          (inst jmp default-stack-slots)
349          (emit-label regs-defaulted)
350          (inst mov rax-tn nil-value)
351          (collect ((defaults))
352            (do ((i register-arg-count (1+ i))
353                 (val (do ((i 0 (1+ i))
354                           (val values (tn-ref-across val)))
355                          ((= i register-arg-count) val))
356                      (tn-ref-across val)))
357                ((null val))
358              (let ((default-lab (gen-label))
359                    (tn (tn-ref-tn val))
360                    (first-stack-arg-p (= i register-arg-count)))
361                (defaults (cons default-lab
362                                (cons tn first-stack-arg-p)))
363                (inst cmp rcx-tn (fixnumize i))
364                (inst jmp :be default-lab)
365                (when first-stack-arg-p
366                  ;; There are stack args so the frame of the callee is
367                  ;; still there, save RDX in its first slot temporalily.
368                  (storew rdx-tn rbx-tn (frame-word-offset sp->fp-offset)))
369                (loadw rdx-tn rbx-tn (frame-word-offset (+ sp->fp-offset i)))
370                (inst mov tn rdx-tn)))
371            (emit-label defaulting-done)
372            (loadw rdx-tn rbx-tn (frame-word-offset sp->fp-offset))
373            (move rsp-tn rbx-tn)
374            (let ((defaults (defaults)))
375              (when defaults
376                (assemble (*elsewhere*)
377                  (trace-table-entry trace-table-fun-prologue)
378                  (emit-label default-stack-slots)
379                  (dolist (default defaults)
380                    (emit-label (car default))
381                    (when (cddr default)
382                      ;; We are setting the first stack argument to NIL.
383                      ;; The callee's stack frame is dead, save RDX by
384                      ;; pushing it to the stack, it will end up at same
385                      ;; place as in the (STOREW RDX-TN RBX-TN -1) case
386                      ;; above.
387                      (inst push rdx-tn))
388                    (inst mov (second default) rax-tn))
389                  (inst jmp defaulting-done)
390                  (trace-table-entry trace-table-normal)))))))
391       (t
392        (let ((regs-defaulted (gen-label))
393              (restore-edi (gen-label))
394              (no-stack-args (gen-label))
395              (default-stack-vals (gen-label))
396              (count-okay (gen-label)))
397          (note-this-location vop :unknown-return)
398          ;; Branch off to the MV case.
399          (inst jmp :c regs-defaulted)
400          ;; Default the register args, and set up the stack as if we
401          ;; entered the MV return point.
402          (inst mov rbx-tn rsp-tn)
403          (inst mov rdi-tn nil-value)
404          (inst mov rsi-tn rdi-tn)
405          ;; Compute a pointer to where to put the [defaulted] stack values.
406          (emit-label no-stack-args)
407          (inst push rdx-tn)
408          (inst push rdi-tn)
409          (inst lea rdi-tn
410                (make-ea :qword :base rbp-tn
411                         :disp (frame-byte-offset register-arg-count)))
412          ;; Load RAX with NIL so we can quickly store it, and set up
413          ;; stuff for the loop.
414          (inst mov rax-tn nil-value)
415          (inst std)
416          (inst mov rcx-tn (- nvals register-arg-count))
417          ;; Jump into the default loop.
418          (inst jmp default-stack-vals)
419          ;; The regs are defaulted. We need to copy any stack arguments,
420          ;; and then default the remaining stack arguments.
421          (emit-label regs-defaulted)
422          ;; Compute the number of stack arguments, and if it's zero or
423          ;; less, don't copy any stack arguments.
424          (inst sub rcx-tn (fixnumize register-arg-count))
425          (inst jmp :le no-stack-args)
426          ;; Save EDI.
427          (storew rdi-tn rbx-tn (frame-word-offset (+ sp->fp-offset 1)))
428          ;; Throw away any unwanted args.
429          (inst cmp rcx-tn (fixnumize (- nvals register-arg-count)))
430          (inst jmp :be count-okay)
431          (inst mov rcx-tn (fixnumize (- nvals register-arg-count)))
432          (emit-label count-okay)
433          ;; Save the number of stack values.
434          (inst mov rax-tn rcx-tn)
435          ;; Compute a pointer to where the stack args go.
436          (inst lea rdi-tn
437                (make-ea :qword :base rbp-tn
438                         :disp (frame-byte-offset register-arg-count)))
439          ;; Save ESI, and compute a pointer to where the args come from.
440          (storew rsi-tn rbx-tn (frame-word-offset (+ sp->fp-offset 2)))
441          (inst lea rsi-tn
442                (make-ea :qword :base rbx-tn
443                         :disp (frame-byte-offset
444                                (+ sp->fp-offset register-arg-count))))
445          ;; Do the copy.
446          (inst shr rcx-tn n-fixnum-tag-bits)   ; make word count
447          (inst std)
448          (inst rep)
449          (inst movs :qword)
450          ;; Restore RSI.
451          (loadw rsi-tn rbx-tn (frame-word-offset (+ sp->fp-offset 2)))
452          ;; Now we have to default the remaining args. Find out how many.
453          (inst sub rax-tn (fixnumize (- nvals register-arg-count)))
454          (inst neg rax-tn)
455          ;; If none, then just blow out of here.
456          (inst jmp :le restore-edi)
457          (inst mov rcx-tn rax-tn)
458          (inst shr rcx-tn n-fixnum-tag-bits)   ; word count
459          ;; Load RAX with NIL for fast storing.
460          (inst mov rax-tn nil-value)
461          ;; Do the store.
462          (emit-label default-stack-vals)
463          (inst rep)
464          (inst stos rax-tn)
465          ;; Restore EDI, and reset the stack.
466          (emit-label restore-edi)
467          (loadw rdi-tn rbx-tn (frame-word-offset (+ sp->fp-offset 1)))
468          (inst mov rsp-tn rbx-tn)
469          (inst cld)))))
470   (values))
471 \f
472 ;;;; unknown values receiving
473
474 ;;; Emit code needed at the return point for an unknown-values call
475 ;;; for an arbitrary number of values.
476 ;;;
477 ;;; We do the single and non-single cases with no shared code: there
478 ;;; doesn't seem to be any potential overlap, and receiving a single
479 ;;; value is more important efficiency-wise.
480 ;;;
481 ;;; When there is a single value, we just push it on the stack,
482 ;;; returning the old SP and 1.
483 ;;;
484 ;;; When there is a variable number of values, we move all of the
485 ;;; argument registers onto the stack, and return ARGS and NARGS.
486 ;;;
487 ;;; ARGS and NARGS are TNs wired to the named locations. We must
488 ;;; explicitly allocate these TNs, since their lifetimes overlap with
489 ;;; the results start and count. (Also, it's nice to be able to target
490 ;;; them.)
491 (defun receive-unknown-values (args nargs start count node)
492   (declare (type tn args nargs start count))
493   (let ((type (sb!c::basic-combination-derived-type node))
494         (variable-values (gen-label))
495         (stack-values (gen-label))
496         (done (gen-label)))
497     (when (sb!kernel:values-type-may-be-single-value-p type)
498       (inst jmp :c variable-values)
499       (cond ((location= start (first *register-arg-tns*))
500              (inst push (first *register-arg-tns*))
501              (inst lea start (make-ea :qword :base rsp-tn :disp n-word-bytes)))
502             (t (inst mov start rsp-tn)
503                (inst push (first *register-arg-tns*))))
504       (inst mov count (fixnumize 1))
505       (inst jmp done)
506       (emit-label variable-values))
507     ;; The stack frame is burnt and RETurned from if there are no
508     ;; stack values. In this case quickly reallocate sufficient space.
509     (when (<= (sb!kernel:values-type-min-value-count type)
510               register-arg-count)
511       (inst cmp nargs (fixnumize register-arg-count))
512       (inst jmp :g stack-values)
513       #!+#.(cl:if (cl:= sb!vm:word-shift sb!vm:n-fixnum-tag-bits) '(and) '(or))
514       (inst sub rsp-tn nargs)
515       #!-#.(cl:if (cl:= sb!vm:word-shift sb!vm:n-fixnum-tag-bits) '(and) '(or))
516       (progn
517         ;; FIXME: This can't be efficient, but LEA (my first choice)
518         ;; doesn't do subtraction.
519         (inst shl nargs (- word-shift n-fixnum-tag-bits))
520         (inst sub rsp-tn nargs)
521         (inst shr nargs (- word-shift n-fixnum-tag-bits)))
522       (emit-label stack-values))
523     ;; dtc: this writes the registers onto the stack even if they are
524     ;; not needed, only the number specified in rcx are used and have
525     ;; stack allocated to them. No harm is done.
526     (loop
527       for arg in *register-arg-tns*
528       for i downfrom -1
529       for j below (sb!kernel:values-type-max-value-count type)
530       do (storew arg args i))
531     (move start args)
532     (move count nargs)
533
534     (emit-label done))
535   (values))
536
537 ;;; VOP that can be inherited by unknown values receivers. The main thing this
538 ;;; handles is allocation of the result temporaries.
539 (define-vop (unknown-values-receiver)
540   (:temporary (:sc descriptor-reg :offset rbx-offset
541                    :from :eval :to (:result 0))
542               values-start)
543   (:temporary (:sc any-reg :offset rcx-offset
544                :from :eval :to (:result 1))
545               nvals)
546   (:results (start :scs (any-reg control-stack))
547             (count :scs (any-reg control-stack))))
548 \f
549 ;;;; local call with unknown values convention return
550
551 (defun check-ocfp-and-return-pc (old-fp return-pc)
552   #+nil
553   (format t "*known-return: old-fp ~S, tn-kind ~S; ~S ~S~%"
554           old-fp (sb!c::tn-kind old-fp) (sb!c::tn-save-tn old-fp)
555           (sb!c::tn-kind (sb!c::tn-save-tn old-fp)))
556   #+nil
557   (format t "*known-return: return-pc ~S, tn-kind ~S; ~S ~S~%"
558           return-pc (sb!c::tn-kind return-pc)
559           (sb!c::tn-save-tn return-pc)
560           (sb!c::tn-kind (sb!c::tn-save-tn return-pc)))
561   (unless (and (sc-is old-fp control-stack)
562                (= (tn-offset old-fp) ocfp-save-offset))
563     (error "ocfp not on stack in standard save location?"))
564   (unless (and (sc-is return-pc sap-stack)
565                (= (tn-offset return-pc) return-pc-save-offset))
566     (error "return-pc not on stack in standard save location?")))
567
568 ;;; The local call convention doesn't fit that well with x86-style
569 ;;; calls. Emit a header for local calls to pop the return address
570 ;;; in the right place.
571 (defun emit-block-header (start-label trampoline-label fall-thru-p alignp)
572   (when (and fall-thru-p trampoline-label)
573     (inst jmp start-label))
574   (when trampoline-label
575     (emit-label trampoline-label)
576     (popw rbp-tn (frame-word-offset return-pc-save-offset)))
577   (when alignp
578     (emit-alignment n-lowtag-bits #x90))
579   (emit-label start-label))
580
581 ;;; Non-TR local call for a fixed number of values passed according to
582 ;;; the unknown values convention.
583 ;;;
584 ;;; FP is the frame pointer in install before doing the call.
585 ;;;
586 ;;; NFP would be the number-stack frame pointer if we had a separate
587 ;;; number stack.
588 ;;;
589 ;;; Args are the argument passing locations, which are specified only
590 ;;; to terminate their lifetimes in the caller.
591 ;;;
592 ;;; VALUES are the return value locations (wired to the standard
593 ;;; passing locations). NVALS is the number of values received.
594 ;;;
595 ;;; Save is the save info, which we can ignore since saving has been
596 ;;; done.
597 ;;;
598 ;;; TARGET is a continuation pointing to the start of the called
599 ;;; function.
600 (define-vop (call-local)
601   (:args (fp)
602          (nfp)
603          (args :more t))
604   (:results (values :more t))
605   (:save-p t)
606   (:move-args :local-call)
607   (:info arg-locs callee target nvals)
608   (:vop-var vop)
609   (:ignore nfp arg-locs args callee)
610   (:node-var node)
611   (:generator 5
612     (trace-table-entry trace-table-call-site)
613     (move rbp-tn fp)
614     (note-this-location vop :call-site)
615     (inst call target)
616     (default-unknown-values vop values nvals node)
617     (trace-table-entry trace-table-normal)))
618
619 ;;; Non-TR local call for a variable number of return values passed according
620 ;;; to the unknown values convention. The results are the start of the values
621 ;;; glob and the number of values received.
622 (define-vop (multiple-call-local unknown-values-receiver)
623   (:args (fp)
624          (nfp)
625          (args :more t))
626   (:save-p t)
627   (:move-args :local-call)
628   (:info save callee target)
629   (:ignore args save nfp callee)
630   (:vop-var vop)
631   (:node-var node)
632   (:generator 20
633     (trace-table-entry trace-table-call-site)
634     (move rbp-tn fp)
635     (note-this-location vop :call-site)
636     (inst call target)
637     (note-this-location vop :unknown-return)
638     (receive-unknown-values values-start nvals start count node)
639     (trace-table-entry trace-table-normal)))
640 \f
641 ;;;; local call with known values return
642
643 ;;; Non-TR local call with known return locations. Known-value return
644 ;;; works just like argument passing in local call.
645 ;;;
646 ;;; Note: we can't use normal load-tn allocation for the fixed args,
647 ;;; since all registers may be tied up by the more operand. Instead,
648 ;;; we use MAYBE-LOAD-STACK-TN.
649 (define-vop (known-call-local)
650   (:args (fp)
651          (nfp)
652          (args :more t))
653   (:results (res :more t))
654   (:move-args :local-call)
655   (:save-p t)
656   (:info save callee target)
657   (:ignore args res save nfp callee)
658   (:vop-var vop)
659   (:generator 5
660     (trace-table-entry trace-table-call-site)
661     (move rbp-tn fp)
662     (note-this-location vop :call-site)
663     (inst call target)
664     (note-this-location vop :known-return)
665     (trace-table-entry trace-table-normal)))
666 \f
667 ;;; From Douglas Crosher
668 ;;; Return from known values call. We receive the return locations as
669 ;;; arguments to terminate their lifetimes in the returning function. We
670 ;;; restore FP and CSP and jump to the Return-PC.
671 (define-vop (known-return)
672   (:args (old-fp)
673          (return-pc)
674          (vals :more t))
675   (:move-args :known-return)
676   (:info val-locs)
677   (:ignore val-locs vals)
678   (:vop-var vop)
679   (:generator 6
680     (check-ocfp-and-return-pc old-fp return-pc)
681     (trace-table-entry trace-table-fun-epilogue)
682     ;; Zot all of the stack except for the old-fp and return-pc.
683     (inst mov rsp-tn rbp-tn)
684     (inst pop rbp-tn)
685     (inst ret)
686     (trace-table-entry trace-table-normal)))
687 \f
688 ;;;; full call
689 ;;;
690 ;;; There is something of a cross-product effect with full calls.
691 ;;; Different versions are used depending on whether we know the
692 ;;; number of arguments or the name of the called function, and
693 ;;; whether we want fixed values, unknown values, or a tail call.
694 ;;;
695 ;;; In full call, the arguments are passed creating a partial frame on
696 ;;; the stack top and storing stack arguments into that frame. On
697 ;;; entry to the callee, this partial frame is pointed to by FP.
698
699 ;;; This macro helps in the definition of full call VOPs by avoiding
700 ;;; code replication in defining the cross-product VOPs.
701 ;;;
702 ;;; NAME is the name of the VOP to define.
703 ;;;
704 ;;; NAMED is true if the first argument is an fdefinition object whose
705 ;;; definition is to be called.
706 ;;;
707 ;;; RETURN is either :FIXED, :UNKNOWN or :TAIL:
708 ;;; -- If :FIXED, then the call is for a fixed number of values, returned in
709 ;;;    the standard passing locations (passed as result operands).
710 ;;; -- If :UNKNOWN, then the result values are pushed on the stack, and the
711 ;;;    result values are specified by the Start and Count as in the
712 ;;;    unknown-values continuation representation.
713 ;;; -- If :TAIL, then do a tail-recursive call. No values are returned.
714 ;;;    The Old-Fp and Return-PC are passed as the second and third arguments.
715 ;;;
716 ;;; In non-tail calls, the pointer to the stack arguments is passed as
717 ;;; the last fixed argument. If Variable is false, then the passing
718 ;;; locations are passed as a more arg. Variable is true if there are
719 ;;; a variable number of arguments passed on the stack. Variable
720 ;;; cannot be specified with :TAIL return. TR variable argument call
721 ;;; is implemented separately.
722 ;;;
723 ;;; In tail call with fixed arguments, the passing locations are
724 ;;; passed as a more arg, but there is no new-FP, since the arguments
725 ;;; have been set up in the current frame.
726 (macrolet ((define-full-call (name named return variable)
727             (aver (not (and variable (eq return :tail))))
728             `(define-vop (,name
729                           ,@(when (eq return :unknown)
730                               '(unknown-values-receiver)))
731                (:args
732                ,@(unless (eq return :tail)
733                    '((new-fp :scs (any-reg) :to (:argument 1))))
734
735                (fun :scs (descriptor-reg control-stack)
736                     :target rax :to (:argument 0))
737
738                ,@(when (eq return :tail)
739                    '((old-fp)
740                      (return-pc)))
741
742                ,@(unless variable '((args :more t :scs (descriptor-reg)))))
743
744                ,@(when (eq return :fixed)
745                '((:results (values :more t))))
746
747                (:save-p ,(if (eq return :tail) :compute-only t))
748
749                ,@(unless (or (eq return :tail) variable)
750                '((:move-args :full-call)))
751
752                (:vop-var vop)
753                (:info
754                ,@(unless (or variable (eq return :tail)) '(arg-locs))
755                ,@(unless variable '(nargs))
756                ,@(when (eq return :fixed) '(nvals))
757                step-instrumenting)
758
759                (:ignore
760                ,@(unless (or variable (eq return :tail)) '(arg-locs))
761                ,@(unless variable '(args)))
762
763                ;; We pass either the fdefn object (for named call) or
764                ;; the actual function object (for unnamed call) in
765                ;; RAX. With named call, closure-tramp will replace it
766                ;; with the real function and invoke the real function
767                ;; for closures. Non-closures do not need this value,
768                ;; so don't care what shows up in it.
769                (:temporary
770                (:sc descriptor-reg
771                     :offset rax-offset
772                     :from (:argument 0)
773                     :to :eval)
774                rax)
775
776                ;; We pass the number of arguments in RCX.
777                (:temporary (:sc unsigned-reg :offset rcx-offset :to :eval) rcx)
778
779                ;; With variable call, we have to load the
780                ;; register-args out of the (new) stack frame before
781                ;; doing the call. Therefore, we have to tell the
782                ;; lifetime stuff that we need to use them.
783                ,@(when variable
784                    (mapcar (lambda (name offset)
785                              `(:temporary (:sc descriptor-reg
786                                                :offset ,offset
787                                                :from (:argument 0)
788                                                :to :eval)
789                                           ,name))
790                            *register-arg-names* *register-arg-offsets*))
791
792                ,@(when (eq return :tail)
793                    '((:temporary (:sc unsigned-reg
794                                       :from (:argument 1)
795                                       :to (:argument 2))
796                                  old-fp-tmp)))
797                ,@(unless (eq return :tail)
798                    '((:node-var node)))
799
800                (:generator ,(+ (if named 5 0)
801                                (if variable 19 1)
802                                (if (eq return :tail) 0 10)
803                                15
804                                (if (eq return :unknown) 25 0))
805                (trace-table-entry trace-table-call-site)
806
807                ;; This has to be done before the frame pointer is
808                ;; changed! RAX stores the 'lexical environment' needed
809                ;; for closures.
810                (move rax fun)
811
812
813                ,@(if variable
814                      ;; For variable call, compute the number of
815                      ;; arguments and move some of the arguments to
816                      ;; registers.
817                      (collect ((noise))
818                               ;; Compute the number of arguments.
819                               (noise '(inst mov rcx new-fp))
820                               (noise '(inst sub rcx rsp-tn))
821                               #.(unless (= word-shift n-fixnum-tag-bits)
822                                   '(noise '(inst shr rcx
823                                             (- word-shift n-fixnum-tag-bits))))
824                               ;; Move the necessary args to registers,
825                               ;; this moves them all even if they are
826                               ;; not all needed.
827                               (loop
828                                for name in *register-arg-names*
829                                for index downfrom -1
830                                do (noise `(loadw ,name new-fp ,index)))
831                               (noise))
832                    '((if (zerop nargs)
833                          (zeroize rcx)
834                        (inst mov rcx (fixnumize nargs)))))
835                ,@(cond ((eq return :tail)
836                         '(;; Python has figured out what frame we should
837                           ;; return to so might as well use that clue.
838                           ;; This seems really important to the
839                           ;; implementation of things like
840                           ;; (without-interrupts ...)
841                           ;;
842                           ;; dtc; Could be doing a tail call from a
843                           ;; known-local-call etc in which the old-fp
844                           ;; or ret-pc are in regs or in non-standard
845                           ;; places. If the passing location were
846                           ;; wired to the stack in standard locations
847                           ;; then these moves will be un-necessary;
848                           ;; this is probably best for the x86.
849                           (sc-case old-fp
850                                    ((control-stack)
851                                     (unless (= ocfp-save-offset
852                                                (tn-offset old-fp))
853                                       ;; FIXME: FORMAT T for stale
854                                       ;; diagnostic output (several of
855                                       ;; them around here), ick
856                                       (error "** tail-call old-fp not S0~%")
857                                       (move old-fp-tmp old-fp)
858                                       (storew old-fp-tmp
859                                               rbp-tn
860                                               (frame-word-offset ocfp-save-offset))))
861                                    ((any-reg descriptor-reg)
862                                     (error "** tail-call old-fp in reg not S0~%")
863                                     (storew old-fp
864                                             rbp-tn
865                                             (frame-word-offset ocfp-save-offset))))
866
867                           ;; For tail call, we have to push the
868                           ;; return-pc so that it looks like we CALLed
869                           ;; despite the fact that we are going to JMP.
870                           (inst push return-pc)
871                           ))
872                        (t
873                         ;; For non-tail call, we have to save our
874                         ;; frame pointer and install the new frame
875                         ;; pointer. We can't load stack tns after this
876                         ;; point.
877                         `(;; Python doesn't seem to allocate a frame
878                           ;; here which doesn't leave room for the
879                           ;; ofp/ret stuff.
880
881                           ;; The variable args are on the stack and
882                           ;; become the frame, but there may be <3
883                           ;; args and 3 stack slots are assumed
884                           ;; allocate on the call. So need to ensure
885                           ;; there are at least 3 slots. This hack
886                           ;; just adds 3 more.
887                           ,(if variable
888                                '(inst sub rsp-tn (* 3 n-word-bytes)))
889
890                           ;; Bias the new-fp for use as an fp
891                           ,(if variable
892                                '(inst sub new-fp (* sp->fp-offset n-word-bytes)))
893
894                           ;; Save the fp
895                           (storew rbp-tn new-fp
896                                   (frame-word-offset ocfp-save-offset))
897
898                           (move rbp-tn new-fp) ; NB - now on new stack frame.
899                           )))
900
901                (when step-instrumenting
902                  (emit-single-step-test)
903                  (inst jmp :eq DONE)
904                  (inst break single-step-around-trap))
905                DONE
906
907                (note-this-location vop :call-site)
908
909                (inst ,(if (eq return :tail) 'jmp 'call)
910                      (make-ea :qword :base rax
911                               :disp ,(if named
912                                          '(- (* fdefn-raw-addr-slot
913                                                 n-word-bytes)
914                                              other-pointer-lowtag)
915                                        '(- (* closure-fun-slot n-word-bytes)
916                                            fun-pointer-lowtag))))
917                ,@(ecase return
918                    (:fixed
919                     '((default-unknown-values vop values nvals node)))
920                    (:unknown
921                     '((note-this-location vop :unknown-return)
922                       (receive-unknown-values values-start nvals start count
923                                               node)))
924                    (:tail))
925                (trace-table-entry trace-table-normal)))))
926
927   (define-full-call call nil :fixed nil)
928   (define-full-call call-named t :fixed nil)
929   (define-full-call multiple-call nil :unknown nil)
930   (define-full-call multiple-call-named t :unknown nil)
931   (define-full-call tail-call nil :tail nil)
932   (define-full-call tail-call-named t :tail nil)
933
934   (define-full-call call-variable nil :fixed t)
935   (define-full-call multiple-call-variable nil :unknown t))
936
937 ;;; This is defined separately, since it needs special code that BLT's
938 ;;; the arguments down. All the real work is done in the assembly
939 ;;; routine. We just set things up so that it can find what it needs.
940 (define-vop (tail-call-variable)
941   (:args (args :scs (any-reg control-stack) :target rsi)
942          (function :scs (descriptor-reg control-stack) :target rax)
943          (old-fp)
944          (return-pc))
945   (:temporary (:sc unsigned-reg :offset rsi-offset :from (:argument 0)) rsi)
946   (:temporary (:sc unsigned-reg :offset rax-offset :from (:argument 1)) rax)
947   (:temporary (:sc unsigned-reg) call-target)
948   (:generator 75
949     (check-ocfp-and-return-pc old-fp return-pc)
950     ;; Move these into the passing locations if they are not already there.
951     (move rsi args)
952     (move rax function)
953     ;; And jump to the assembly routine.
954     (inst lea call-target
955           (make-ea :qword
956                    :disp (make-fixup 'tail-call-variable :assembly-routine)))
957     (inst jmp call-target)))
958 \f
959 ;;;; unknown values return
960
961 ;;; Return a single-value using the Unknown-Values convention.
962 ;;;
963 ;;; pfw--get wired-tn conflicts sometimes if register sc specd for args
964 ;;; having problems targeting args to regs -- using temps instead.
965 ;;;
966 ;;; First off, modifying the return-pc defeats the branch-prediction
967 ;;; optimizations on modern CPUs quite handily. Second, we can do all
968 ;;; this without needing a temp register. Fixed the latter, at least.
969 ;;; -- AB 2006/Feb/04
970 (define-vop (return-single)
971   (:args (old-fp)
972          (return-pc)
973          (value))
974   (:ignore value)
975   (:generator 6
976     (check-ocfp-and-return-pc old-fp return-pc)
977     (trace-table-entry trace-table-fun-epilogue)
978     ;; Drop stack above old-fp
979     (inst mov rsp-tn rbp-tn)
980     ;; Clear the multiple-value return flag
981     (inst clc)
982     ;; Restore the old frame pointer
983     (inst pop rbp-tn)
984     ;; And return.
985     (inst ret)))
986
987 ;;; Do unknown-values return of a fixed (other than 1) number of
988 ;;; values. The VALUES are required to be set up in the standard
989 ;;; passing locations. NVALS is the number of values returned.
990 ;;;
991 ;;; Basically, we just load RCX with the number of values returned and
992 ;;; RBX with a pointer to the values, set RSP to point to the end of
993 ;;; the values, and jump directly to return-pc.
994 (define-vop (return)
995   (:args (old-fp)
996          (return-pc :to (:eval 1))
997          (values :more t))
998   (:ignore values)
999   (:info nvals)
1000   ;; In the case of other than one value, we need these registers to
1001   ;; tell the caller where they are and how many there are.
1002   (:temporary (:sc unsigned-reg :offset rbx-offset) rbx)
1003   (:temporary (:sc unsigned-reg :offset rcx-offset) rcx)
1004   ;; We need to stretch the lifetime of return-pc past the argument
1005   ;; registers so that we can default the argument registers without
1006   ;; trashing return-pc.
1007   (:temporary (:sc unsigned-reg :offset (first *register-arg-offsets*)
1008                    :from :eval) a0)
1009   (:temporary (:sc unsigned-reg :offset (second *register-arg-offsets*)
1010                    :from :eval) a1)
1011   (:temporary (:sc unsigned-reg :offset (third *register-arg-offsets*)
1012                    :from :eval) a2)
1013
1014   (:generator 6
1015     (check-ocfp-and-return-pc old-fp return-pc)
1016     (when (= nvals 1)
1017       ;; This is handled in RETURN-SINGLE.
1018       (error "nvalues is 1"))
1019     (trace-table-entry trace-table-fun-epilogue)
1020     ;; Establish the values pointer and values count.
1021     (inst lea rbx (make-ea :qword :base rbp-tn
1022                            :disp (* sp->fp-offset n-word-bytes)))
1023     (if (zerop nvals)
1024         (zeroize rcx) ; smaller
1025         (inst mov rcx (fixnumize nvals)))
1026     ;; Pre-default any argument register that need it.
1027     (when (< nvals register-arg-count)
1028       (let* ((arg-tns (nthcdr nvals (list a0 a1 a2)))
1029              (first (first arg-tns)))
1030         (inst mov first nil-value)
1031         (dolist (tn (cdr arg-tns))
1032           (inst mov tn first))))
1033     ;; Set the multiple value return flag.
1034     (inst stc)
1035     ;; And away we go. Except that return-pc is still on the
1036     ;; stack and we've changed the stack pointer. So we have to
1037     ;; tell it to index off of RBX instead of RBP.
1038     (cond ((<= nvals register-arg-count)
1039            (inst mov rsp-tn rbp-tn)
1040            (inst pop rbp-tn)
1041            (inst ret))
1042           (t
1043            ;; Some values are on the stack after RETURN-PC and OLD-FP,
1044            ;; can't return normally and some slots of the frame will
1045            ;; be used as temporaries by the receiver.
1046            ;;
1047            ;; Clear as much of the stack as possible, but not past the
1048            ;; old frame address.
1049            (inst lea rsp-tn
1050                  (make-ea :qword :base rbp-tn
1051                           :disp (frame-byte-offset (1- nvals))))
1052            (move rbp-tn old-fp)
1053            (inst push (make-ea :qword :base rbx
1054                                :disp (frame-byte-offset
1055                                       (+ sp->fp-offset
1056                                          (tn-offset return-pc)))))
1057            (inst ret)))
1058
1059     (trace-table-entry trace-table-normal)))
1060
1061 ;;; Do unknown-values return of an arbitrary number of values (passed
1062 ;;; on the stack.) We check for the common case of a single return
1063 ;;; value, and do that inline using the normal single value return
1064 ;;; convention. Otherwise, we branch off to code that calls an
1065 ;;; assembly-routine.
1066 ;;;
1067 ;;; The assembly routine takes the following args:
1068 ;;;  RCX -- number of values to find there.
1069 ;;;  RSI -- pointer to where to find the values.
1070 (define-vop (return-multiple)
1071   (:args (old-fp)
1072          (return-pc)
1073          (vals :scs (any-reg) :target rsi)
1074          (nvals :scs (any-reg) :target rcx))
1075   (:temporary (:sc unsigned-reg :offset rsi-offset :from (:argument 2)) rsi)
1076   (:temporary (:sc unsigned-reg :offset rcx-offset :from (:argument 3)) rcx)
1077   (:temporary (:sc unsigned-reg) return-asm)
1078   (:temporary (:sc descriptor-reg :offset (first *register-arg-offsets*)
1079                    :from (:eval 0)) a0)
1080   (:node-var node)
1081   (:generator 13
1082     (check-ocfp-and-return-pc old-fp return-pc)
1083     (trace-table-entry trace-table-fun-epilogue)
1084     (unless (policy node (> space speed))
1085       ;; Check for the single case.
1086       (let ((not-single (gen-label)))
1087         (inst cmp nvals (fixnumize 1))
1088         (inst jmp :ne not-single)
1089         ;; Return with one value.
1090         (loadw a0 vals -1)
1091         ;; Clear the stack until ocfp.
1092         (inst mov rsp-tn rbp-tn)
1093         ;; clear the multiple-value return flag
1094         (inst clc)
1095         ;; Out of here.
1096         (inst pop rbp-tn)
1097         (inst ret)
1098         ;; Nope, not the single case. Jump to the assembly routine.
1099         (emit-label not-single)))
1100     (move rsi vals)
1101     (move rcx nvals)
1102     (inst lea return-asm
1103           (make-ea :qword :disp (make-fixup 'return-multiple
1104                                             :assembly-routine)))
1105     (inst jmp return-asm)
1106     (trace-table-entry trace-table-normal)))
1107 \f
1108 ;;;; XEP hackery
1109
1110 ;;; We don't need to do anything special for regular functions.
1111 (define-vop (setup-environment)
1112   (:info label)
1113   (:ignore label)
1114   (:generator 0
1115     ;; Don't bother doing anything.
1116     nil))
1117
1118 ;;; Get the lexical environment from its passing location.
1119 (define-vop (setup-closure-environment)
1120   (:results (closure :scs (descriptor-reg)))
1121   (:info label)
1122   (:ignore label)
1123   (:generator 6
1124     ;; Get result.
1125     (move closure rax-tn)))
1126
1127 ;;; Copy a &MORE arg from the argument area to the end of the current
1128 ;;; frame. FIXED is the number of non-&MORE arguments.
1129 (define-vop (copy-more-arg)
1130   (:temporary (:sc any-reg :offset r8-offset) copy-index)
1131   (:temporary (:sc any-reg :offset r9-offset) source)
1132   (:temporary (:sc descriptor-reg :offset r10-offset) temp)
1133   (:info fixed)
1134   (:generator 20
1135     ;; Avoid the copy if there are no more args.
1136     (cond ((zerop fixed)
1137            (inst jrcxz JUST-ALLOC-FRAME))
1138           (t
1139            (inst cmp rcx-tn (fixnumize fixed))
1140            (inst jmp :be JUST-ALLOC-FRAME)))
1141
1142     ;; Create a negated copy of the number of arguments to allow us to
1143     ;; use EA calculations in order to do scaled subtraction.
1144     (inst mov temp rcx-tn)
1145     (inst neg temp)
1146
1147     ;; Allocate the space on the stack.
1148     ;; stack = rbp + sp->fp-offset - (max 3 frame-size) - (nargs - fixed)
1149     (inst lea rsp-tn
1150           (make-ea :qword :base rbp-tn
1151                    :index temp :scale (ash 1 (- word-shift n-fixnum-tag-bits))
1152                    :disp (* n-word-bytes
1153                             (- (+ sp->fp-offset fixed)
1154                                (max 3 (sb-allocated-size 'stack))))))
1155
1156     ;; Now: nargs>=1 && nargs>fixed
1157
1158     ;; Save the original count of args.
1159     (inst mov rbx-tn rcx-tn)
1160
1161     (cond ((< fixed register-arg-count)
1162            ;; We must stop when we run out of stack args, not when we
1163            ;; run out of more args.
1164            ;; Number to copy = nargs-3
1165            (inst sub rcx-tn (fixnumize register-arg-count))
1166            ;; Everything of interest in registers.
1167            (inst jmp :be DO-REGS))
1168           (t
1169            ;; Number to copy = nargs-fixed
1170            (inst sub rcx-tn (fixnumize fixed))))
1171
1172     ;; Initialize R8 to be the end of args.
1173     (inst lea source (make-ea :qword :base rbp-tn
1174                               :index temp :scale (ash 1 (- word-shift n-fixnum-tag-bits))
1175                               :disp (* sp->fp-offset n-word-bytes)))
1176
1177     ;; We need to copy from downwards up to avoid overwriting some of
1178     ;; the yet uncopied args. So we need to use R9 as the copy index
1179     ;; and RCX as the loop counter, rather than using RCX for both.
1180     (zeroize copy-index)
1181
1182     ;; We used to use REP MOVS here, but on modern x86 it performs
1183     ;; much worse than an explicit loop for small blocks.
1184     COPY-LOOP
1185     (inst mov temp (make-ea :qword :base source :index copy-index))
1186     (inst mov (make-ea :qword :base rsp-tn :index copy-index) temp)
1187     (inst add copy-index n-word-bytes)
1188     (inst sub rcx-tn (fixnumize 1))
1189     (inst jmp :nz COPY-LOOP)
1190
1191     DO-REGS
1192
1193     ;; Restore RCX
1194     (inst mov rcx-tn rbx-tn)
1195
1196     ;; Here: nargs>=1 && nargs>fixed
1197     (when (< fixed register-arg-count)
1198       ;; Now we have to deposit any more args that showed up in
1199       ;; registers.
1200       (do ((i fixed))
1201           ( nil )
1202         ;; Store it relative to rbp
1203         (inst mov (make-ea :qword :base rbp-tn
1204                            :disp (* n-word-bytes
1205                                     (- sp->fp-offset
1206                                        (+ 1
1207                                           (- i fixed)
1208                                           (max 3 (sb-allocated-size
1209                                                   'stack))))))
1210               (nth i *register-arg-tns*))
1211
1212         (incf i)
1213         (when (>= i register-arg-count)
1214           (return))
1215
1216         ;; Don't deposit any more than there are.
1217         (if (zerop i)
1218             (inst test rcx-tn rcx-tn)
1219             (inst cmp rcx-tn (fixnumize i)))
1220         (inst jmp :eq DONE)))
1221
1222     (inst jmp DONE)
1223
1224     JUST-ALLOC-FRAME
1225     (inst lea rsp-tn
1226           (make-ea :qword :base rbp-tn
1227                    :disp (* n-word-bytes
1228                             (- sp->fp-offset
1229                                (max 3 (sb-allocated-size 'stack))))))
1230
1231     DONE))
1232
1233 (define-vop (more-kw-arg)
1234   (:translate sb!c::%more-kw-arg)
1235   (:policy :fast-safe)
1236   (:args (object :scs (descriptor-reg) :to (:result 1))
1237          (index :scs (any-reg) :to (:result 1) :target keyword))
1238   (:arg-types * tagged-num)
1239   (:results (value :scs (descriptor-reg any-reg))
1240             (keyword :scs (descriptor-reg any-reg)))
1241   (:result-types * *)
1242   (:generator 4
1243      (inst mov value (make-ea :qword :base object :index index
1244                               :scale (ash 1 (- word-shift n-fixnum-tag-bits))))
1245      (inst mov keyword (make-ea :qword :base object :index index
1246                                 :scale (ash 1 (- word-shift n-fixnum-tag-bits))
1247                                 :disp n-word-bytes))))
1248
1249 (define-vop (more-arg)
1250     (:translate sb!c::%more-arg)
1251   (:policy :fast-safe)
1252   (:args (object :scs (descriptor-reg) :to (:result 1))
1253          (index :scs (any-reg) :to (:result 1) :target value))
1254   (:arg-types * tagged-num)
1255   (:results (value :scs (descriptor-reg any-reg)))
1256   (:result-types *)
1257   (:generator 4
1258     (move value index)
1259     (inst neg value)
1260     (inst mov value (make-ea :qword :base object :index value
1261                              :scale (ash 1 (- word-shift n-fixnum-tag-bits))))))
1262
1263 ;;; Turn more arg (context, count) into a list.
1264 (define-vop (listify-rest-args)
1265   (:translate %listify-rest-args)
1266   (:policy :safe)
1267   (:args (context :scs (descriptor-reg) :target src)
1268          (count :scs (any-reg) :target rcx))
1269   (:arg-types * tagged-num)
1270   (:temporary (:sc unsigned-reg :offset rsi-offset :from (:argument 0)) src)
1271   (:temporary (:sc unsigned-reg :offset rcx-offset :from (:argument 1)) rcx)
1272   (:temporary (:sc unsigned-reg :offset rax-offset) rax)
1273   (:temporary (:sc unsigned-reg) dst)
1274   (:results (result :scs (descriptor-reg)))
1275   (:node-var node)
1276   (:generator 20
1277     (let ((enter (gen-label))
1278           (loop (gen-label))
1279           (done (gen-label))
1280           (stack-allocate-p (node-stack-allocate-p node)))
1281       (move src context)
1282       (move rcx count)
1283       ;; Check to see whether there are no args, and just return NIL if so.
1284       (inst mov result nil-value)
1285       (inst jrcxz done)
1286       (inst lea dst (make-ea :qword :index rcx :scale (ash 2 (- word-shift n-fixnum-tag-bits))))
1287       (maybe-pseudo-atomic stack-allocate-p
1288        (allocation dst dst node stack-allocate-p list-pointer-lowtag)
1289        ;; Set decrement mode (successive args at lower addresses)
1290        (inst std)
1291        ;; Set up the result.
1292        (move result dst)
1293        ;; Jump into the middle of the loop, 'cause that's where we want
1294        ;; to start.
1295        (inst jmp enter)
1296        (emit-label loop)
1297        ;; Compute a pointer to the next cons.
1298        (inst add dst (* cons-size n-word-bytes))
1299        ;; Store a pointer to this cons in the CDR of the previous cons.
1300        (storew dst dst -1 list-pointer-lowtag)
1301        (emit-label enter)
1302        ;; Grab one value and stash it in the car of this cons.
1303        (inst mov rax (make-ea :qword :base src))
1304        (inst sub src n-word-bytes)
1305        (storew rax dst 0 list-pointer-lowtag)
1306        ;; Go back for more.
1307        (inst sub rcx (fixnumize 1))
1308        (inst jmp :nz loop)
1309        ;; NIL out the last cons.
1310        (storew nil-value dst 1 list-pointer-lowtag)
1311        (inst cld))
1312       (emit-label done))))
1313
1314 ;;; Return the location and size of the &MORE arg glob created by
1315 ;;; COPY-MORE-ARG. SUPPLIED is the total number of arguments supplied
1316 ;;; (originally passed in RCX). FIXED is the number of non-rest
1317 ;;; arguments.
1318 ;;;
1319 ;;; We must duplicate some of the work done by COPY-MORE-ARG, since at
1320 ;;; that time the environment is in a pretty brain-damaged state,
1321 ;;; preventing this info from being returned as values. What we do is
1322 ;;; compute supplied - fixed, and return a pointer that many words
1323 ;;; below the current stack top.
1324 (define-vop (more-arg-context)
1325   (:policy :fast-safe)
1326   (:translate sb!c::%more-arg-context)
1327   (:args (supplied :scs (any-reg) :target count))
1328   (:arg-types positive-fixnum (:constant fixnum))
1329   (:info fixed)
1330   (:results (context :scs (descriptor-reg))
1331             (count :scs (any-reg)))
1332   (:result-types t tagged-num)
1333   (:note "more-arg-context")
1334   (:generator 5
1335     (move count supplied)
1336     ;; SP at this point points at the last arg pushed.
1337     ;; Point to the first more-arg, not above it.
1338     (inst lea context (make-ea :qword :base rsp-tn
1339                                :index count
1340                                :scale (ash 1 (- word-shift n-fixnum-tag-bits))
1341                                :disp (- (* (1+ fixed) n-word-bytes))))
1342     (unless (zerop fixed)
1343       (inst sub count (fixnumize fixed)))))
1344
1345 ;;; Signal wrong argument count error if NARGS isn't equal to COUNT.
1346 (define-vop (verify-arg-count)
1347   (:policy :fast-safe)
1348   (:translate sb!c::%verify-arg-count)
1349   (:args (nargs :scs (any-reg)))
1350   (:arg-types positive-fixnum (:constant t))
1351   (:info count)
1352   (:vop-var vop)
1353   (:save-p :compute-only)
1354   (:generator 3
1355     (let ((err-lab
1356            (generate-error-code vop 'invalid-arg-count-error nargs)))
1357       (if (zerop count)
1358           (inst test nargs nargs)  ; smaller instruction
1359         (inst cmp nargs (fixnumize count)))
1360       (inst jmp :ne err-lab))))
1361
1362 ;;; Various other error signallers.
1363 (macrolet ((def (name error translate &rest args)
1364              `(define-vop (,name)
1365                 ,@(when translate
1366                     `((:policy :fast-safe)
1367                       (:translate ,translate)))
1368                 (:args ,@(mapcar (lambda (arg)
1369                                    `(,arg :scs (any-reg descriptor-reg)))
1370                                  args))
1371                 (:vop-var vop)
1372                 (:save-p :compute-only)
1373                 (:generator 1000
1374                   (error-call vop ',error ,@args)))))
1375   (def arg-count-error invalid-arg-count-error
1376     sb!c::%arg-count-error nargs)
1377   (def type-check-error object-not-type-error sb!c::%type-check-error
1378     object type)
1379   (def layout-invalid-error layout-invalid-error sb!c::%layout-invalid-error
1380     object layout)
1381   (def odd-key-args-error odd-key-args-error
1382     sb!c::%odd-key-args-error)
1383   (def unknown-key-arg-error unknown-key-arg-error
1384     sb!c::%unknown-key-arg-error key)
1385   (def nil-fun-returned-error nil-fun-returned-error nil fun))
1386
1387 ;;; Single-stepping
1388
1389 (defun emit-single-step-test ()
1390   ;; We use different ways of representing whether stepping is on on
1391   ;; +SB-THREAD / -SB-THREAD: on +SB-THREAD, we use a slot in the
1392   ;; thread structure. On -SB-THREAD we use the value of a static
1393   ;; symbol. Things are done this way, since reading a thread-local
1394   ;; slot from a symbol would require an extra register on +SB-THREAD,
1395   ;; and reading a slot from a thread structure would require an extra
1396   ;; register on -SB-THREAD. While this isn't critical for x86-64,
1397   ;; it's more serious for x86.
1398   #!+sb-thread
1399   (inst cmp (make-ea :qword
1400                      :base thread-base-tn
1401                      :disp (* thread-stepping-slot n-word-bytes))
1402         nil-value)
1403   #!-sb-thread
1404   (inst cmp (make-ea :qword
1405                      :disp (+ nil-value (static-symbol-offset
1406                                          'sb!impl::*stepping*)
1407                               (* symbol-value-slot n-word-bytes)
1408                               (- other-pointer-lowtag)))
1409         nil-value))
1410
1411 (define-vop (step-instrument-before-vop)
1412   (:policy :fast-safe)
1413   (:vop-var vop)
1414   (:generator 3
1415      (emit-single-step-test)
1416      (inst jmp :eq DONE)
1417      (inst break single-step-before-trap)
1418      DONE
1419      (note-this-location vop :step-before-vop)))