b1c53956e786f1db6e7ead9ea2c78d3ad9bbe079
[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 word-shift)   ; 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 word-shift)   ; 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       (inst sub rsp-tn nargs)
514       (emit-label stack-values))
515     ;; dtc: this writes the registers onto the stack even if they are
516     ;; not needed, only the number specified in rcx are used and have
517     ;; stack allocated to them. No harm is done.
518     (loop
519       for arg in *register-arg-tns*
520       for i downfrom -1
521       for j below (sb!kernel:values-type-max-value-count type)
522       do (storew arg args i))
523     (move start args)
524     (move count nargs)
525
526     (emit-label done))
527   (values))
528
529 ;;; VOP that can be inherited by unknown values receivers. The main thing this
530 ;;; handles is allocation of the result temporaries.
531 (define-vop (unknown-values-receiver)
532   (:temporary (:sc descriptor-reg :offset rbx-offset
533                    :from :eval :to (:result 0))
534               values-start)
535   (:temporary (:sc any-reg :offset rcx-offset
536                :from :eval :to (:result 1))
537               nvals)
538   (:results (start :scs (any-reg control-stack))
539             (count :scs (any-reg control-stack))))
540 \f
541 ;;;; local call with unknown values convention return
542
543 (defun check-ocfp-and-return-pc (old-fp return-pc)
544   #+nil
545   (format t "*known-return: old-fp ~S, tn-kind ~S; ~S ~S~%"
546           old-fp (sb!c::tn-kind old-fp) (sb!c::tn-save-tn old-fp)
547           (sb!c::tn-kind (sb!c::tn-save-tn old-fp)))
548   #+nil
549   (format t "*known-return: return-pc ~S, tn-kind ~S; ~S ~S~%"
550           return-pc (sb!c::tn-kind return-pc)
551           (sb!c::tn-save-tn return-pc)
552           (sb!c::tn-kind (sb!c::tn-save-tn return-pc)))
553   (unless (and (sc-is old-fp control-stack)
554                (= (tn-offset old-fp) ocfp-save-offset))
555     (error "ocfp not on stack in standard save location?"))
556   (unless (and (sc-is return-pc sap-stack)
557                (= (tn-offset return-pc) return-pc-save-offset))
558     (error "return-pc not on stack in standard save location?")))
559
560 ;;; The local call convention doesn't fit that well with x86-style
561 ;;; calls. Emit a header for local calls to pop the return address
562 ;;; in the right place.
563 (defun emit-block-header (start-label trampoline-label fall-thru-p alignp)
564   (when (and fall-thru-p trampoline-label)
565     (inst jmp start-label))
566   (when trampoline-label
567     (emit-label trampoline-label)
568     (popw rbp-tn (frame-word-offset return-pc-save-offset)))
569   (when alignp
570     (emit-alignment n-lowtag-bits #x90))
571   (emit-label start-label))
572
573 ;;; Non-TR local call for a fixed number of values passed according to
574 ;;; the unknown values convention.
575 ;;;
576 ;;; FP is the frame pointer in install before doing the call.
577 ;;;
578 ;;; NFP would be the number-stack frame pointer if we had a separate
579 ;;; number stack.
580 ;;;
581 ;;; Args are the argument passing locations, which are specified only
582 ;;; to terminate their lifetimes in the caller.
583 ;;;
584 ;;; VALUES are the return value locations (wired to the standard
585 ;;; passing locations). NVALS is the number of values received.
586 ;;;
587 ;;; Save is the save info, which we can ignore since saving has been
588 ;;; done.
589 ;;;
590 ;;; TARGET is a continuation pointing to the start of the called
591 ;;; function.
592 (define-vop (call-local)
593   (:args (fp)
594          (nfp)
595          (args :more t))
596   (:results (values :more t))
597   (:save-p t)
598   (:move-args :local-call)
599   (:info arg-locs callee target nvals)
600   (:vop-var vop)
601   (:ignore nfp arg-locs args callee)
602   (:node-var node)
603   (:generator 5
604     (trace-table-entry trace-table-call-site)
605     (move rbp-tn fp)
606     (note-this-location vop :call-site)
607     (inst call target)
608     (default-unknown-values vop values nvals node)
609     (trace-table-entry trace-table-normal)))
610
611 ;;; Non-TR local call for a variable number of return values passed according
612 ;;; to the unknown values convention. The results are the start of the values
613 ;;; glob and the number of values received.
614 (define-vop (multiple-call-local unknown-values-receiver)
615   (:args (fp)
616          (nfp)
617          (args :more t))
618   (:save-p t)
619   (:move-args :local-call)
620   (:info save callee target)
621   (:ignore args save nfp callee)
622   (:vop-var vop)
623   (:node-var node)
624   (:generator 20
625     (trace-table-entry trace-table-call-site)
626     (move rbp-tn fp)
627     (note-this-location vop :call-site)
628     (inst call target)
629     (note-this-location vop :unknown-return)
630     (receive-unknown-values values-start nvals start count node)
631     (trace-table-entry trace-table-normal)))
632 \f
633 ;;;; local call with known values return
634
635 ;;; Non-TR local call with known return locations. Known-value return
636 ;;; works just like argument passing in local call.
637 ;;;
638 ;;; Note: we can't use normal load-tn allocation for the fixed args,
639 ;;; since all registers may be tied up by the more operand. Instead,
640 ;;; we use MAYBE-LOAD-STACK-TN.
641 (define-vop (known-call-local)
642   (:args (fp)
643          (nfp)
644          (args :more t))
645   (:results (res :more t))
646   (:move-args :local-call)
647   (:save-p t)
648   (:info save callee target)
649   (:ignore args res save nfp callee)
650   (:vop-var vop)
651   (:generator 5
652     (trace-table-entry trace-table-call-site)
653     (move rbp-tn fp)
654     (note-this-location vop :call-site)
655     (inst call target)
656     (note-this-location vop :known-return)
657     (trace-table-entry trace-table-normal)))
658 \f
659 ;;; From Douglas Crosher
660 ;;; Return from known values call. We receive the return locations as
661 ;;; arguments to terminate their lifetimes in the returning function. We
662 ;;; restore FP and CSP and jump to the Return-PC.
663 (define-vop (known-return)
664   (:args (old-fp)
665          (return-pc)
666          (vals :more t))
667   (:move-args :known-return)
668   (:info val-locs)
669   (:ignore val-locs vals)
670   (:vop-var vop)
671   (:generator 6
672     (check-ocfp-and-return-pc old-fp return-pc)
673     (trace-table-entry trace-table-fun-epilogue)
674     ;; Zot all of the stack except for the old-fp and return-pc.
675     (inst mov rsp-tn rbp-tn)
676     (inst pop rbp-tn)
677     (inst ret)
678     (trace-table-entry trace-table-normal)))
679 \f
680 ;;;; full call
681 ;;;
682 ;;; There is something of a cross-product effect with full calls.
683 ;;; Different versions are used depending on whether we know the
684 ;;; number of arguments or the name of the called function, and
685 ;;; whether we want fixed values, unknown values, or a tail call.
686 ;;;
687 ;;; In full call, the arguments are passed creating a partial frame on
688 ;;; the stack top and storing stack arguments into that frame. On
689 ;;; entry to the callee, this partial frame is pointed to by FP.
690
691 ;;; This macro helps in the definition of full call VOPs by avoiding
692 ;;; code replication in defining the cross-product VOPs.
693 ;;;
694 ;;; NAME is the name of the VOP to define.
695 ;;;
696 ;;; NAMED is true if the first argument is an fdefinition object whose
697 ;;; definition is to be called.
698 ;;;
699 ;;; RETURN is either :FIXED, :UNKNOWN or :TAIL:
700 ;;; -- If :FIXED, then the call is for a fixed number of values, returned in
701 ;;;    the standard passing locations (passed as result operands).
702 ;;; -- If :UNKNOWN, then the result values are pushed on the stack, and the
703 ;;;    result values are specified by the Start and Count as in the
704 ;;;    unknown-values continuation representation.
705 ;;; -- If :TAIL, then do a tail-recursive call. No values are returned.
706 ;;;    The Old-Fp and Return-PC are passed as the second and third arguments.
707 ;;;
708 ;;; In non-tail calls, the pointer to the stack arguments is passed as
709 ;;; the last fixed argument. If Variable is false, then the passing
710 ;;; locations are passed as a more arg. Variable is true if there are
711 ;;; a variable number of arguments passed on the stack. Variable
712 ;;; cannot be specified with :TAIL return. TR variable argument call
713 ;;; is implemented separately.
714 ;;;
715 ;;; In tail call with fixed arguments, the passing locations are
716 ;;; passed as a more arg, but there is no new-FP, since the arguments
717 ;;; have been set up in the current frame.
718 (macrolet ((define-full-call (name named return variable)
719             (aver (not (and variable (eq return :tail))))
720             `(define-vop (,name
721                           ,@(when (eq return :unknown)
722                               '(unknown-values-receiver)))
723                (:args
724                ,@(unless (eq return :tail)
725                    '((new-fp :scs (any-reg) :to (:argument 1))))
726
727                (fun :scs (descriptor-reg control-stack)
728                     :target rax :to (:argument 0))
729
730                ,@(when (eq return :tail)
731                    '((old-fp)
732                      (return-pc)))
733
734                ,@(unless variable '((args :more t :scs (descriptor-reg)))))
735
736                ,@(when (eq return :fixed)
737                '((:results (values :more t))))
738
739                (:save-p ,(if (eq return :tail) :compute-only t))
740
741                ,@(unless (or (eq return :tail) variable)
742                '((:move-args :full-call)))
743
744                (:vop-var vop)
745                (:info
746                ,@(unless (or variable (eq return :tail)) '(arg-locs))
747                ,@(unless variable '(nargs))
748                ,@(when (eq return :fixed) '(nvals))
749                step-instrumenting)
750
751                (:ignore
752                ,@(unless (or variable (eq return :tail)) '(arg-locs))
753                ,@(unless variable '(args)))
754
755                ;; We pass either the fdefn object (for named call) or
756                ;; the actual function object (for unnamed call) in
757                ;; RAX. With named call, closure-tramp will replace it
758                ;; with the real function and invoke the real function
759                ;; for closures. Non-closures do not need this value,
760                ;; so don't care what shows up in it.
761                (:temporary
762                (:sc descriptor-reg
763                     :offset rax-offset
764                     :from (:argument 0)
765                     :to :eval)
766                rax)
767
768                ;; We pass the number of arguments in RCX.
769                (:temporary (:sc unsigned-reg :offset rcx-offset :to :eval) rcx)
770
771                ;; With variable call, we have to load the
772                ;; register-args out of the (new) stack frame before
773                ;; doing the call. Therefore, we have to tell the
774                ;; lifetime stuff that we need to use them.
775                ,@(when variable
776                    (mapcar (lambda (name offset)
777                              `(:temporary (:sc descriptor-reg
778                                                :offset ,offset
779                                                :from (:argument 0)
780                                                :to :eval)
781                                           ,name))
782                            *register-arg-names* *register-arg-offsets*))
783
784                ,@(when (eq return :tail)
785                    '((:temporary (:sc unsigned-reg
786                                       :from (:argument 1)
787                                       :to (:argument 2))
788                                  old-fp-tmp)))
789                ,@(unless (eq return :tail)
790                    '((:node-var node)))
791
792                (:generator ,(+ (if named 5 0)
793                                (if variable 19 1)
794                                (if (eq return :tail) 0 10)
795                                15
796                                (if (eq return :unknown) 25 0))
797                (trace-table-entry trace-table-call-site)
798
799                ;; This has to be done before the frame pointer is
800                ;; changed! RAX stores the 'lexical environment' needed
801                ;; for closures.
802                (move rax fun)
803
804
805                ,@(if variable
806                      ;; For variable call, compute the number of
807                      ;; arguments and move some of the arguments to
808                      ;; registers.
809                      (collect ((noise))
810                               ;; Compute the number of arguments.
811                               (noise '(inst mov rcx new-fp))
812                               (noise '(inst sub rcx rsp-tn))
813                               ;; Move the necessary args to registers,
814                               ;; this moves them all even if they are
815                               ;; not all needed.
816                               (loop
817                                for name in *register-arg-names*
818                                for index downfrom -1
819                                do (noise `(loadw ,name new-fp ,index)))
820                               (noise))
821                    '((if (zerop nargs)
822                          (zeroize rcx)
823                        (inst mov rcx (fixnumize nargs)))))
824                ,@(cond ((eq return :tail)
825                         '(;; Python has figured out what frame we should
826                           ;; return to so might as well use that clue.
827                           ;; This seems really important to the
828                           ;; implementation of things like
829                           ;; (without-interrupts ...)
830                           ;;
831                           ;; dtc; Could be doing a tail call from a
832                           ;; known-local-call etc in which the old-fp
833                           ;; or ret-pc are in regs or in non-standard
834                           ;; places. If the passing location were
835                           ;; wired to the stack in standard locations
836                           ;; then these moves will be un-necessary;
837                           ;; this is probably best for the x86.
838                           (sc-case old-fp
839                                    ((control-stack)
840                                     (unless (= ocfp-save-offset
841                                                (tn-offset old-fp))
842                                       ;; FIXME: FORMAT T for stale
843                                       ;; diagnostic output (several of
844                                       ;; them around here), ick
845                                       (error "** tail-call old-fp not S0~%")
846                                       (move old-fp-tmp old-fp)
847                                       (storew old-fp-tmp
848                                               rbp-tn
849                                               (frame-word-offset ocfp-save-offset))))
850                                    ((any-reg descriptor-reg)
851                                     (error "** tail-call old-fp in reg not S0~%")
852                                     (storew old-fp
853                                             rbp-tn
854                                             (frame-word-offset ocfp-save-offset))))
855
856                           ;; For tail call, we have to push the
857                           ;; return-pc so that it looks like we CALLed
858                           ;; despite the fact that we are going to JMP.
859                           (inst push return-pc)
860                           ))
861                        (t
862                         ;; For non-tail call, we have to save our
863                         ;; frame pointer and install the new frame
864                         ;; pointer. We can't load stack tns after this
865                         ;; point.
866                         `(;; Python doesn't seem to allocate a frame
867                           ;; here which doesn't leave room for the
868                           ;; ofp/ret stuff.
869
870                           ;; The variable args are on the stack and
871                           ;; become the frame, but there may be <3
872                           ;; args and 3 stack slots are assumed
873                           ;; allocate on the call. So need to ensure
874                           ;; there are at least 3 slots. This hack
875                           ;; just adds 3 more.
876                           ,(if variable
877                                '(inst sub rsp-tn (fixnumize 3)))
878
879                           ;; Bias the new-fp for use as an fp
880                           ,(if variable
881                                '(inst sub new-fp (fixnumize sp->fp-offset)))
882
883                           ;; Save the fp
884                           (storew rbp-tn new-fp
885                                   (frame-word-offset ocfp-save-offset))
886
887                           (move rbp-tn new-fp) ; NB - now on new stack frame.
888                           )))
889
890                (when step-instrumenting
891                  (emit-single-step-test)
892                  (inst jmp :eq DONE)
893                  (inst break single-step-around-trap))
894                DONE
895
896                (note-this-location vop :call-site)
897
898                (inst ,(if (eq return :tail) 'jmp 'call)
899                      (make-ea :qword :base rax
900                               :disp ,(if named
901                                          '(- (* fdefn-raw-addr-slot
902                                                 n-word-bytes)
903                                              other-pointer-lowtag)
904                                        '(- (* closure-fun-slot n-word-bytes)
905                                            fun-pointer-lowtag))))
906                ,@(ecase return
907                    (:fixed
908                     '((default-unknown-values vop values nvals node)))
909                    (:unknown
910                     '((note-this-location vop :unknown-return)
911                       (receive-unknown-values values-start nvals start count
912                                               node)))
913                    (:tail))
914                (trace-table-entry trace-table-normal)))))
915
916   (define-full-call call nil :fixed nil)
917   (define-full-call call-named t :fixed nil)
918   (define-full-call multiple-call nil :unknown nil)
919   (define-full-call multiple-call-named t :unknown nil)
920   (define-full-call tail-call nil :tail nil)
921   (define-full-call tail-call-named t :tail nil)
922
923   (define-full-call call-variable nil :fixed t)
924   (define-full-call multiple-call-variable nil :unknown t))
925
926 ;;; This is defined separately, since it needs special code that BLT's
927 ;;; the arguments down. All the real work is done in the assembly
928 ;;; routine. We just set things up so that it can find what it needs.
929 (define-vop (tail-call-variable)
930   (:args (args :scs (any-reg control-stack) :target rsi)
931          (function :scs (descriptor-reg control-stack) :target rax)
932          (old-fp)
933          (return-pc))
934   (:temporary (:sc unsigned-reg :offset rsi-offset :from (:argument 0)) rsi)
935   (:temporary (:sc unsigned-reg :offset rax-offset :from (:argument 1)) rax)
936   (:temporary (:sc unsigned-reg) call-target)
937   (:generator 75
938     (check-ocfp-and-return-pc old-fp return-pc)
939     ;; Move these into the passing locations if they are not already there.
940     (move rsi args)
941     (move rax function)
942     ;; And jump to the assembly routine.
943     (inst lea call-target
944           (make-ea :qword
945                    :disp (make-fixup 'tail-call-variable :assembly-routine)))
946     (inst jmp call-target)))
947 \f
948 ;;;; unknown values return
949
950 ;;; Return a single-value using the Unknown-Values convention.
951 ;;;
952 ;;; pfw--get wired-tn conflicts sometimes if register sc specd for args
953 ;;; having problems targeting args to regs -- using temps instead.
954 ;;;
955 ;;; First off, modifying the return-pc defeats the branch-prediction
956 ;;; optimizations on modern CPUs quite handily. Second, we can do all
957 ;;; this without needing a temp register. Fixed the latter, at least.
958 ;;; -- AB 2006/Feb/04
959 (define-vop (return-single)
960   (:args (old-fp)
961          (return-pc)
962          (value))
963   (:ignore value)
964   (:generator 6
965     (check-ocfp-and-return-pc old-fp return-pc)
966     (trace-table-entry trace-table-fun-epilogue)
967     ;; Drop stack above old-fp
968     (inst mov rsp-tn rbp-tn)
969     ;; Clear the multiple-value return flag
970     (inst clc)
971     ;; Restore the old frame pointer
972     (inst pop rbp-tn)
973     ;; And return.
974     (inst ret)))
975
976 ;;; Do unknown-values return of a fixed (other than 1) number of
977 ;;; values. The VALUES are required to be set up in the standard
978 ;;; passing locations. NVALS is the number of values returned.
979 ;;;
980 ;;; Basically, we just load RCX with the number of values returned and
981 ;;; RBX with a pointer to the values, set RSP to point to the end of
982 ;;; the values, and jump directly to return-pc.
983 (define-vop (return)
984   (:args (old-fp)
985          (return-pc :to (:eval 1))
986          (values :more t))
987   (:ignore values)
988   (:info nvals)
989   ;; In the case of other than one value, we need these registers to
990   ;; tell the caller where they are and how many there are.
991   (:temporary (:sc unsigned-reg :offset rbx-offset) rbx)
992   (:temporary (:sc unsigned-reg :offset rcx-offset) rcx)
993   ;; We need to stretch the lifetime of return-pc past the argument
994   ;; registers so that we can default the argument registers without
995   ;; trashing return-pc.
996   (:temporary (:sc unsigned-reg :offset (first *register-arg-offsets*)
997                    :from :eval) a0)
998   (:temporary (:sc unsigned-reg :offset (second *register-arg-offsets*)
999                    :from :eval) a1)
1000   (:temporary (:sc unsigned-reg :offset (third *register-arg-offsets*)
1001                    :from :eval) a2)
1002
1003   (:generator 6
1004     (check-ocfp-and-return-pc old-fp return-pc)
1005     (when (= nvals 1)
1006       ;; This is handled in RETURN-SINGLE.
1007       (error "nvalues is 1"))
1008     (trace-table-entry trace-table-fun-epilogue)
1009     ;; Establish the values pointer and values count.
1010     (inst lea rbx (make-ea :qword :base rbp-tn
1011                            :disp (* sp->fp-offset n-word-bytes)))
1012     (if (zerop nvals)
1013         (zeroize rcx) ; smaller
1014         (inst mov rcx (fixnumize nvals)))
1015     ;; Pre-default any argument register that need it.
1016     (when (< nvals register-arg-count)
1017       (let* ((arg-tns (nthcdr nvals (list a0 a1 a2)))
1018              (first (first arg-tns)))
1019         (inst mov first nil-value)
1020         (dolist (tn (cdr arg-tns))
1021           (inst mov tn first))))
1022     ;; Set the multiple value return flag.
1023     (inst stc)
1024     ;; And away we go. Except that return-pc is still on the
1025     ;; stack and we've changed the stack pointer. So we have to
1026     ;; tell it to index off of RBX instead of RBP.
1027     (cond ((<= nvals register-arg-count)
1028            (inst mov rsp-tn rbp-tn)
1029            (inst pop rbp-tn)
1030            (inst ret))
1031           (t
1032            ;; Some values are on the stack after RETURN-PC and OLD-FP,
1033            ;; can't return normally and some slots of the frame will
1034            ;; be used as temporaries by the receiver.
1035            ;;
1036            ;; Clear as much of the stack as possible, but not past the
1037            ;; old frame address.
1038            (inst lea rsp-tn
1039                  (make-ea :qword :base rbp-tn
1040                           :disp (frame-byte-offset (1- nvals))))
1041            (move rbp-tn old-fp)
1042            (inst push (make-ea :qword :base rbx
1043                                :disp (frame-byte-offset
1044                                       (+ sp->fp-offset
1045                                          (tn-offset return-pc)))))
1046            (inst ret)))
1047
1048     (trace-table-entry trace-table-normal)))
1049
1050 ;;; Do unknown-values return of an arbitrary number of values (passed
1051 ;;; on the stack.) We check for the common case of a single return
1052 ;;; value, and do that inline using the normal single value return
1053 ;;; convention. Otherwise, we branch off to code that calls an
1054 ;;; assembly-routine.
1055 ;;;
1056 ;;; The assembly routine takes the following args:
1057 ;;;  RCX -- number of values to find there.
1058 ;;;  RSI -- pointer to where to find the values.
1059 (define-vop (return-multiple)
1060   (:args (old-fp)
1061          (return-pc)
1062          (vals :scs (any-reg) :target rsi)
1063          (nvals :scs (any-reg) :target rcx))
1064   (:temporary (:sc unsigned-reg :offset rsi-offset :from (:argument 2)) rsi)
1065   (:temporary (:sc unsigned-reg :offset rcx-offset :from (:argument 3)) rcx)
1066   (:temporary (:sc unsigned-reg) return-asm)
1067   (:temporary (:sc descriptor-reg :offset (first *register-arg-offsets*)
1068                    :from (:eval 0)) a0)
1069   (:node-var node)
1070   (:generator 13
1071     (check-ocfp-and-return-pc old-fp return-pc)
1072     (trace-table-entry trace-table-fun-epilogue)
1073     (unless (policy node (> space speed))
1074       ;; Check for the single case.
1075       (let ((not-single (gen-label)))
1076         (inst cmp nvals (fixnumize 1))
1077         (inst jmp :ne not-single)
1078         ;; Return with one value.
1079         (loadw a0 vals -1)
1080         ;; Clear the stack until ocfp.
1081         (inst mov rsp-tn rbp-tn)
1082         ;; clear the multiple-value return flag
1083         (inst clc)
1084         ;; Out of here.
1085         (inst pop rbp-tn)
1086         (inst ret)
1087         ;; Nope, not the single case. Jump to the assembly routine.
1088         (emit-label not-single)))
1089     (move rsi vals)
1090     (move rcx nvals)
1091     (inst lea return-asm
1092           (make-ea :qword :disp (make-fixup 'return-multiple
1093                                             :assembly-routine)))
1094     (inst jmp return-asm)
1095     (trace-table-entry trace-table-normal)))
1096 \f
1097 ;;;; XEP hackery
1098
1099 ;;; We don't need to do anything special for regular functions.
1100 (define-vop (setup-environment)
1101   (:info label)
1102   (:ignore label)
1103   (:generator 0
1104     ;; Don't bother doing anything.
1105     nil))
1106
1107 ;;; Get the lexical environment from its passing location.
1108 (define-vop (setup-closure-environment)
1109   (:results (closure :scs (descriptor-reg)))
1110   (:info label)
1111   (:ignore label)
1112   (:generator 6
1113     ;; Get result.
1114     (move closure rax-tn)))
1115
1116 ;;; Copy a &MORE arg from the argument area to the end of the current
1117 ;;; frame. FIXED is the number of non-&MORE arguments.
1118 (define-vop (copy-more-arg)
1119   (:temporary (:sc any-reg :offset r8-offset) copy-index)
1120   (:temporary (:sc any-reg :offset r9-offset) source)
1121   (:temporary (:sc descriptor-reg :offset r10-offset) temp)
1122   (:info fixed)
1123   (:generator 20
1124     ;; Avoid the copy if there are no more args.
1125     (cond ((zerop fixed)
1126            (inst jrcxz JUST-ALLOC-FRAME))
1127           (t
1128            (inst cmp rcx-tn (fixnumize fixed))
1129            (inst jmp :be JUST-ALLOC-FRAME)))
1130
1131     ;; Allocate the space on the stack.
1132     ;; stack = rbp + sp->fp-offset - (max 3 frame-size) - (nargs - fixed)
1133     (inst lea rbx-tn
1134           (make-ea :qword :base rbp-tn
1135                    :disp (* n-word-bytes
1136                             (- (+ sp->fp-offset fixed)
1137                                (max 3 (sb-allocated-size 'stack))))))
1138     (inst sub rbx-tn rcx-tn)  ; Got the new stack in rbx
1139     (inst mov rsp-tn rbx-tn)
1140
1141     ;; Now: nargs>=1 && nargs>fixed
1142
1143     ;; Save the original count of args.
1144     (inst mov rbx-tn rcx-tn)
1145
1146     (cond ((< fixed register-arg-count)
1147            ;; We must stop when we run out of stack args, not when we
1148            ;; run out of more args.
1149            ;; Number to copy = nargs-3
1150            (inst sub rcx-tn (fixnumize register-arg-count))
1151            ;; Everything of interest in registers.
1152            (inst jmp :be DO-REGS))
1153           (t
1154            ;; Number to copy = nargs-fixed
1155            (inst sub rcx-tn (fixnumize fixed))))
1156
1157     ;; Initialize R8 to be the end of args.
1158     (inst lea source (make-ea :qword :base rbp-tn
1159                               :disp (* sp->fp-offset n-word-bytes)))
1160     (inst sub source rbx-tn)
1161
1162     ;; We need to copy from downwards up to avoid overwriting some of
1163     ;; the yet uncopied args. So we need to use R9 as the copy index
1164     ;; and RCX as the loop counter, rather than using RCX for both.
1165     (zeroize copy-index)
1166
1167     ;; We used to use REP MOVS here, but on modern x86 it performs
1168     ;; much worse than an explicit loop for small blocks.
1169     COPY-LOOP
1170     (inst mov temp (make-ea :qword :base source :index copy-index))
1171     (inst mov (make-ea :qword :base rsp-tn :index copy-index) temp)
1172     (inst add copy-index n-word-bytes)
1173     (inst sub rcx-tn n-word-bytes)
1174     (inst jmp :nz COPY-LOOP)
1175
1176     DO-REGS
1177
1178     ;; Restore RCX
1179     (inst mov rcx-tn rbx-tn)
1180
1181     ;; Here: nargs>=1 && nargs>fixed
1182     (when (< fixed register-arg-count)
1183       ;; Now we have to deposit any more args that showed up in
1184       ;; registers.
1185       (do ((i fixed))
1186           ( nil )
1187         ;; Store it relative to rbp
1188         (inst mov (make-ea :qword :base rbp-tn
1189                            :disp (* n-word-bytes
1190                                     (- sp->fp-offset
1191                                        (+ 1
1192                                           (- i fixed)
1193                                           (max 3 (sb-allocated-size
1194                                                   'stack))))))
1195               (nth i *register-arg-tns*))
1196
1197         (incf i)
1198         (when (>= i register-arg-count)
1199           (return))
1200
1201         ;; Don't deposit any more than there are.
1202         (if (zerop i)
1203             (inst test rcx-tn rcx-tn)
1204             (inst cmp rcx-tn (fixnumize i)))
1205         (inst jmp :eq DONE)))
1206
1207     (inst jmp DONE)
1208
1209     JUST-ALLOC-FRAME
1210     (inst lea rsp-tn
1211           (make-ea :qword :base rbp-tn
1212                    :disp (* n-word-bytes
1213                             (- sp->fp-offset
1214                                (max 3 (sb-allocated-size 'stack))))))
1215
1216     DONE))
1217
1218 (define-vop (more-kw-arg)
1219   (:translate sb!c::%more-kw-arg)
1220   (:policy :fast-safe)
1221   (:args (object :scs (descriptor-reg) :to (:result 1))
1222          (index :scs (any-reg) :to (:result 1) :target keyword))
1223   (:arg-types * tagged-num)
1224   (:results (value :scs (descriptor-reg any-reg))
1225             (keyword :scs (descriptor-reg any-reg)))
1226   (:result-types * *)
1227   (:generator 4
1228      (inst mov value (make-ea :qword :base object :index index))
1229      (inst mov keyword (make-ea :qword :base object :index index
1230                                 :disp n-word-bytes))))
1231
1232 (define-vop (more-arg)
1233     (:translate sb!c::%more-arg)
1234   (:policy :fast-safe)
1235   (:args (object :scs (descriptor-reg) :to (:result 1))
1236          (index :scs (any-reg) :to (:result 1) :target value))
1237   (:arg-types * tagged-num)
1238   (:results (value :scs (descriptor-reg any-reg)))
1239   (:result-types *)
1240   (:generator 4
1241     (move value index)
1242     (inst neg value)
1243     (inst mov value (make-ea :qword :base object :index value))))
1244
1245 ;;; Turn more arg (context, count) into a list.
1246 (define-vop (listify-rest-args)
1247   (:translate %listify-rest-args)
1248   (:policy :safe)
1249   (:args (context :scs (descriptor-reg) :target src)
1250          (count :scs (any-reg) :target rcx))
1251   (:arg-types * tagged-num)
1252   (:temporary (:sc unsigned-reg :offset rsi-offset :from (:argument 0)) src)
1253   (:temporary (:sc unsigned-reg :offset rcx-offset :from (:argument 1)) rcx)
1254   (:temporary (:sc unsigned-reg :offset rax-offset) rax)
1255   (:temporary (:sc unsigned-reg) dst)
1256   (:results (result :scs (descriptor-reg)))
1257   (:node-var node)
1258   (:generator 20
1259     (let ((enter (gen-label))
1260           (loop (gen-label))
1261           (done (gen-label))
1262           (stack-allocate-p (node-stack-allocate-p node)))
1263       (move src context)
1264       (move rcx count)
1265       ;; Check to see whether there are no args, and just return NIL if so.
1266       (inst mov result nil-value)
1267       (inst jrcxz done)
1268       (inst lea dst (make-ea :qword :base rcx :index rcx))
1269       (maybe-pseudo-atomic stack-allocate-p
1270        (allocation dst dst node stack-allocate-p list-pointer-lowtag)
1271        ;; Set decrement mode (successive args at lower addresses)
1272        (inst std)
1273        ;; Set up the result.
1274        (move result dst)
1275        ;; Jump into the middle of the loop, 'cause that's where we want
1276        ;; to start.
1277        (inst jmp enter)
1278        (emit-label loop)
1279        ;; Compute a pointer to the next cons.
1280        (inst add dst (* cons-size n-word-bytes))
1281        ;; Store a pointer to this cons in the CDR of the previous cons.
1282        (storew dst dst -1 list-pointer-lowtag)
1283        (emit-label enter)
1284        ;; Grab one value and stash it in the car of this cons.
1285        (inst mov rax (make-ea :qword :base src))
1286        (inst sub src n-word-bytes)
1287        (storew rax dst 0 list-pointer-lowtag)
1288        ;; Go back for more.
1289        (inst sub rcx n-word-bytes)
1290        (inst jmp :nz loop)
1291        ;; NIL out the last cons.
1292        (storew nil-value dst 1 list-pointer-lowtag)
1293        (inst cld))
1294       (emit-label done))))
1295
1296 ;;; Return the location and size of the &MORE arg glob created by
1297 ;;; COPY-MORE-ARG. SUPPLIED is the total number of arguments supplied
1298 ;;; (originally passed in RCX). FIXED is the number of non-rest
1299 ;;; arguments.
1300 ;;;
1301 ;;; We must duplicate some of the work done by COPY-MORE-ARG, since at
1302 ;;; that time the environment is in a pretty brain-damaged state,
1303 ;;; preventing this info from being returned as values. What we do is
1304 ;;; compute supplied - fixed, and return a pointer that many words
1305 ;;; below the current stack top.
1306 (define-vop (more-arg-context)
1307   (:policy :fast-safe)
1308   (:translate sb!c::%more-arg-context)
1309   (:args (supplied :scs (any-reg) :target count))
1310   (:arg-types positive-fixnum (:constant fixnum))
1311   (:info fixed)
1312   (:results (context :scs (descriptor-reg))
1313             (count :scs (any-reg)))
1314   (:result-types t tagged-num)
1315   (:note "more-arg-context")
1316   (:generator 5
1317     (move count supplied)
1318     ;; SP at this point points at the last arg pushed.
1319     ;; Point to the first more-arg, not above it.
1320     (inst lea context (make-ea :qword :base rsp-tn
1321                                :index count :scale 1
1322                                :disp (- (+ (fixnumize fixed) n-word-bytes))))
1323     (unless (zerop fixed)
1324       (inst sub count (fixnumize fixed)))))
1325
1326 ;;; Signal wrong argument count error if NARGS isn't equal to COUNT.
1327 (define-vop (verify-arg-count)
1328   (:policy :fast-safe)
1329   (:translate sb!c::%verify-arg-count)
1330   (:args (nargs :scs (any-reg)))
1331   (:arg-types positive-fixnum (:constant t))
1332   (:info count)
1333   (:vop-var vop)
1334   (:save-p :compute-only)
1335   (:generator 3
1336     (let ((err-lab
1337            (generate-error-code vop 'invalid-arg-count-error nargs)))
1338       (if (zerop count)
1339           (inst test nargs nargs)  ; smaller instruction
1340         (inst cmp nargs (fixnumize count)))
1341       (inst jmp :ne err-lab))))
1342
1343 ;;; Various other error signallers.
1344 (macrolet ((def (name error translate &rest args)
1345              `(define-vop (,name)
1346                 ,@(when translate
1347                     `((:policy :fast-safe)
1348                       (:translate ,translate)))
1349                 (:args ,@(mapcar (lambda (arg)
1350                                    `(,arg :scs (any-reg descriptor-reg)))
1351                                  args))
1352                 (:vop-var vop)
1353                 (:save-p :compute-only)
1354                 (:generator 1000
1355                   (error-call vop ',error ,@args)))))
1356   (def arg-count-error invalid-arg-count-error
1357     sb!c::%arg-count-error nargs)
1358   (def type-check-error object-not-type-error sb!c::%type-check-error
1359     object type)
1360   (def layout-invalid-error layout-invalid-error sb!c::%layout-invalid-error
1361     object layout)
1362   (def odd-key-args-error odd-key-args-error
1363     sb!c::%odd-key-args-error)
1364   (def unknown-key-arg-error unknown-key-arg-error
1365     sb!c::%unknown-key-arg-error key)
1366   (def nil-fun-returned-error nil-fun-returned-error nil fun))
1367
1368 ;;; Single-stepping
1369
1370 (defun emit-single-step-test ()
1371   ;; We use different ways of representing whether stepping is on on
1372   ;; +SB-THREAD / -SB-THREAD: on +SB-THREAD, we use a slot in the
1373   ;; thread structure. On -SB-THREAD we use the value of a static
1374   ;; symbol. Things are done this way, since reading a thread-local
1375   ;; slot from a symbol would require an extra register on +SB-THREAD,
1376   ;; and reading a slot from a thread structure would require an extra
1377   ;; register on -SB-THREAD. While this isn't critical for x86-64,
1378   ;; it's more serious for x86.
1379   #!+sb-thread
1380   (inst cmp (make-ea :qword
1381                      :base thread-base-tn
1382                      :disp (* thread-stepping-slot n-word-bytes))
1383         nil-value)
1384   #!-sb-thread
1385   (inst cmp (make-ea :qword
1386                      :disp (+ nil-value (static-symbol-offset
1387                                          'sb!impl::*stepping*)
1388                               (* symbol-value-slot n-word-bytes)
1389                               (- other-pointer-lowtag)))
1390         nil-value))
1391
1392 (define-vop (step-instrument-before-vop)
1393   (:policy :fast-safe)
1394   (:vop-var vop)
1395   (:generator 3
1396      (emit-single-step-test)
1397      (inst jmp :eq DONE)
1398      (inst break single-step-before-trap)
1399      DONE
1400      (note-this-location vop :step-before-vop)))