32fb566f0d3a5a22f398c7574984cada9b97016c
[sbcl.git] / src / compiler / x86-64 / c-call.lisp
1 ;;;; the VOPs and other necessary machine specific support
2 ;;;; routines for call-out to C
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!VM")
14
15 ;; The MOVE-ARG vop is going to store args on the stack for
16 ;; call-out. These tn's will be used for that. move-arg is normally
17 ;; used for things going down the stack but C wants to have args
18 ;; indexed in the positive direction.
19
20 (defun my-make-wired-tn (prim-type-name sc-name offset)
21   (make-wired-tn (primitive-type-or-lose prim-type-name)
22                  (sc-number-or-lose sc-name)
23                  offset))
24
25 (defstruct (arg-state (:copier nil))
26   (register-args 0)
27   (xmm-args 0)
28   (stack-frame-size 0))
29
30 (defun int-arg (state prim-type reg-sc stack-sc)
31   (let ((reg-args (arg-state-register-args state)))
32     (cond ((< reg-args 6)
33            (setf (arg-state-register-args state) (1+ reg-args))
34            (my-make-wired-tn prim-type reg-sc
35                              (nth reg-args *c-call-register-arg-offsets*)))
36           (t
37            (let ((frame-size (arg-state-stack-frame-size state)))
38              (setf (arg-state-stack-frame-size state) (1+ frame-size))
39              (my-make-wired-tn prim-type stack-sc frame-size))))))
40
41 (define-alien-type-method (integer :arg-tn) (type state)
42   (if (alien-integer-type-signed type)
43       (int-arg state 'signed-byte-64 'signed-reg 'signed-stack)
44       (int-arg state 'unsigned-byte-64 'unsigned-reg 'unsigned-stack)))
45
46 (define-alien-type-method (system-area-pointer :arg-tn) (type state)
47   (declare (ignore type))
48   (int-arg state 'system-area-pointer 'sap-reg 'sap-stack))
49
50 (defun float-arg (state prim-type reg-sc stack-sc)
51   (let ((xmm-args (arg-state-xmm-args state)))
52     (cond ((< xmm-args 8)
53            (setf (arg-state-xmm-args state) (1+ xmm-args))
54            (my-make-wired-tn prim-type reg-sc
55                              (nth xmm-args *float-regs*)))
56           (t
57            (let ((frame-size (arg-state-stack-frame-size state)))
58              (setf (arg-state-stack-frame-size state) (1+ frame-size))
59              (my-make-wired-tn prim-type stack-sc frame-size))))))
60
61 (define-alien-type-method (double-float :arg-tn) (type state)
62   (declare (ignore type))
63   (float-arg state 'double-float 'double-reg 'double-stack))
64
65 (define-alien-type-method (single-float :arg-tn) (type state)
66   (declare (ignore type))
67   (float-arg state 'single-float 'single-reg 'single-stack))
68
69 (defstruct (result-state (:copier nil))
70   (num-results 0))
71
72 (defun result-reg-offset (slot)
73   (ecase slot
74     (0 eax-offset)
75     (1 edx-offset)))
76
77 ;; XXX The return handling probably doesn't conform to the ABI
78
79 (define-alien-type-method (integer :result-tn) (type state)
80   (let ((num-results (result-state-num-results state)))
81     (setf (result-state-num-results state) (1+ num-results))
82     (multiple-value-bind (ptype reg-sc)
83         (if (alien-integer-type-signed type)
84             (values 'signed-byte-64 'signed-reg)
85             (values 'unsigned-byte-64 'unsigned-reg))
86       (my-make-wired-tn ptype reg-sc (result-reg-offset num-results)))))
87
88 (define-alien-type-method (integer :naturalize-gen) (type alien)
89   (if (and (alien-integer-type-signed type)
90            (<= (alien-type-bits type) 32))
91       `(sign-extend ,alien)
92       alien))
93
94 (define-alien-type-method (system-area-pointer :result-tn) (type state)
95   (declare (ignore type))
96   (let ((num-results (result-state-num-results state)))
97     (setf (result-state-num-results state) (1+ num-results))
98     (my-make-wired-tn 'system-area-pointer 'sap-reg
99                       (result-reg-offset num-results))))
100
101 (define-alien-type-method (double-float :result-tn) (type state)
102   (declare (ignore type))
103   (let ((num-results (result-state-num-results state)))
104     (setf (result-state-num-results state) (1+ num-results))
105     (my-make-wired-tn 'double-float 'double-reg num-results)))
106
107 (define-alien-type-method (single-float :result-tn) (type state)
108   (declare (ignore type))
109   (let ((num-results (result-state-num-results state)))
110     (setf (result-state-num-results state) (1+ num-results))
111     (my-make-wired-tn 'single-float 'single-reg num-results)))
112
113 (define-alien-type-method (values :result-tn) (type state)
114   (let ((values (alien-values-type-values type)))
115     (when (> (length values) 2)
116       (error "Too many result values from c-call."))
117     (mapcar (lambda (type)
118               (invoke-alien-type-method :result-tn type state))
119             values)))
120
121 (!def-vm-support-routine make-call-out-tns (type)
122   (let ((arg-state (make-arg-state)))
123     (collect ((arg-tns))
124       (dolist (arg-type (alien-fun-type-arg-types type))
125         (arg-tns (invoke-alien-type-method :arg-tn arg-type arg-state)))
126       (values (my-make-wired-tn 'positive-fixnum 'any-reg esp-offset)
127               (* (arg-state-stack-frame-size arg-state) n-word-bytes)
128               (arg-tns)
129               (invoke-alien-type-method :result-tn
130                                         (alien-fun-type-result-type type)
131                                         (make-result-state))))))
132
133
134 (deftransform %alien-funcall ((function type &rest args) * * :node node)
135   (aver (sb!c::constant-lvar-p type))
136   (let* ((type (sb!c::lvar-value type))
137          (env (sb!c::node-lexenv node))
138          (arg-types (alien-fun-type-arg-types type))
139          (result-type (alien-fun-type-result-type type)))
140     (aver (= (length arg-types) (length args)))
141     (if (or (some #'(lambda (type)
142                       (and (alien-integer-type-p type)
143                            (> (sb!alien::alien-integer-type-bits type) 64)))
144                   arg-types)
145             (and (alien-integer-type-p result-type)
146                  (> (sb!alien::alien-integer-type-bits result-type) 64)))
147         (collect ((new-args) (lambda-vars) (new-arg-types))
148           (dolist (type arg-types)
149             (let ((arg (gensym)))
150               (lambda-vars arg)
151               (cond ((and (alien-integer-type-p type)
152                           (> (sb!alien::alien-integer-type-bits type) 64))
153                      (new-args `(logand ,arg #xffffffff))
154                      (new-args `(ash ,arg -64))
155                      (new-arg-types (parse-alien-type '(unsigned 64) env))
156                      (if (alien-integer-type-signed type)
157                          (new-arg-types (parse-alien-type '(signed 64) env))
158                          (new-arg-types (parse-alien-type '(unsigned 64) env))))
159                     (t
160                      (new-args arg)
161                      (new-arg-types type)))))
162           (cond ((and (alien-integer-type-p result-type)
163                       (> (sb!alien::alien-integer-type-bits result-type) 64))
164                  (let ((new-result-type
165                         (let ((sb!alien::*values-type-okay* t))
166                           (parse-alien-type
167                            (if (alien-integer-type-signed result-type)
168                                '(values (unsigned 64) (signed 64))
169                                '(values (unsigned 64) (unsigned 64)))
170                            env))))
171                    `(lambda (function type ,@(lambda-vars))
172                       (declare (ignore type))
173                       (multiple-value-bind (low high)
174                           (%alien-funcall function
175                                           ',(make-alien-fun-type
176                                              :arg-types (new-arg-types)
177                                              :result-type new-result-type)
178                                           ,@(new-args))
179                         (logior low (ash high 64))))))
180                 (t
181                  `(lambda (function type ,@(lambda-vars))
182                     (declare (ignore type))
183                     (%alien-funcall function
184                                     ',(make-alien-fun-type
185                                        :arg-types (new-arg-types)
186                                        :result-type result-type)
187                                     ,@(new-args))))))
188         (sb!c::give-up-ir1-transform))))
189
190 ;;; The ABI specifies that signed short/int's are returned as 32-bit
191 ;;; values. Negative values need to be sign-extended to 64-bits (done
192 ;;; in a :NATURALIZE-GEN alien-type-method).
193 (defknown sign-extend ((signed-byte 32)) fixnum
194           (foldable flushable movable))
195
196 (define-vop (sign-extend)
197   (:translate sign-extend)
198   (:policy :fast-safe)
199   (:args (val :scs (signed-reg)))
200   (:arg-types fixnum)
201   (:results (res :scs (signed-reg)))
202   (:result-types fixnum)
203   (:generator 1
204    (inst movsxd res
205          (make-random-tn :kind :normal
206                          :sc (sc-or-lose 'dword-reg)
207                          :offset (tn-offset val)))))
208
209 (defun sign-extend (x)
210   (declare (type (signed-byte 32) x))
211   (sign-extend x))
212
213 (define-vop (foreign-symbol-sap)
214   (:translate foreign-symbol-sap)
215   (:policy :fast-safe)
216   (:args)
217   (:arg-types (:constant simple-string))
218   (:info foreign-symbol)
219   (:results (res :scs (sap-reg)))
220   (:result-types system-area-pointer)
221   (:generator 2
222    (inst lea res (make-fixup foreign-symbol :foreign))))
223
224 #!+linkage-table
225 (define-vop (foreign-symbol-dataref-sap)
226   (:translate foreign-symbol-dataref-sap)
227   (:policy :fast-safe)
228   (:args)
229   (:arg-types (:constant simple-string))
230   (:info foreign-symbol)
231   (:results (res :scs (sap-reg)))
232   (:result-types system-area-pointer)
233   (:generator 2
234    (inst mov res (make-fixup foreign-symbol :foreign-dataref))))
235
236 (define-vop (call-out)
237   (:args (function :scs (sap-reg))
238          (args :more t))
239   (:results (results :more t))
240   (:temporary (:sc unsigned-reg :offset rax-offset :to :result) rax)
241   (:ignore results)
242   (:vop-var vop)
243   (:save-p t)
244   (:generator 0
245     ;; ABI: Direction flag must be clear on function entry. -- JES, 2006-01-20
246     (inst cld)
247     ;; ABI: AL contains amount of arguments passed in XMM registers
248     ;; for vararg calls.
249     (move-immediate rax
250                     (loop for tn-ref = args then (tn-ref-across tn-ref)
251                        while tn-ref
252                        count (eq (sb-name (sc-sb (tn-sc (tn-ref-tn tn-ref))))
253                                  'float-registers)))
254     (inst call function)
255     ;; To give the debugger a clue. XX not really internal-error?
256     (note-this-location vop :internal-error)))
257
258 (define-vop (alloc-number-stack-space)
259   (:info amount)
260   (:results (result :scs (sap-reg any-reg)))
261   (:generator 0
262     (aver (location= result rsp-tn))
263     (unless (zerop amount)
264       (let ((delta (logandc2 (+ amount 7) 7)))
265         (inst sub rsp-tn delta)))
266     ;; C stack must be 16 byte aligned
267     (inst and rsp-tn -16)
268     (move result rsp-tn)))
269
270 (define-vop (dealloc-number-stack-space)
271   (:info amount)
272   (:generator 0
273     (unless (zerop amount)
274       (let ((delta (logandc2 (+ amount 7) 7)))
275         (inst add rsp-tn delta)))))
276
277 (define-vop (alloc-alien-stack-space)
278   (:info amount)
279   #!+sb-thread (:temporary (:sc unsigned-reg) temp)
280   (:results (result :scs (sap-reg any-reg)))
281   #!+sb-thread
282   (:generator 0
283     (aver (not (location= result rsp-tn)))
284     (unless (zerop amount)
285       (let ((delta (logandc2 (+ amount 7) 7)))
286         (inst mov temp
287               (make-ea :qword
288                        :disp (+ nil-value
289                                 (static-symbol-offset '*alien-stack*)
290                                 (ash symbol-tls-index-slot word-shift)
291                                 (- other-pointer-lowtag))))
292         (inst sub (make-ea :qword :base thread-base-tn
293                            :scale 1 :index temp) delta)))
294     (load-tl-symbol-value result *alien-stack*))
295   #!-sb-thread
296   (:generator 0
297     (aver (not (location= result rsp-tn)))
298     (unless (zerop amount)
299       (let ((delta (logandc2 (+ amount 7) 7)))
300         (inst sub (make-ea :qword
301                            :disp (+ nil-value
302                                     (static-symbol-offset '*alien-stack*)
303                                     (ash symbol-value-slot word-shift)
304                                     (- other-pointer-lowtag)))
305               delta)))
306     (load-symbol-value result *alien-stack*)))
307
308 (define-vop (dealloc-alien-stack-space)
309   (:info amount)
310   #!+sb-thread (:temporary (:sc unsigned-reg) temp)
311   #!+sb-thread
312   (:generator 0
313     (unless (zerop amount)
314       (let ((delta (logandc2 (+ amount 7) 7)))
315         (inst mov temp
316               (make-ea :qword
317                        :disp (+ nil-value
318                                 (static-symbol-offset '*alien-stack*)
319                                 (ash symbol-tls-index-slot word-shift)
320                                 (- other-pointer-lowtag))))
321         (inst add (make-ea :qword :base thread-base-tn :scale 1 :index temp)
322               delta))))
323   #!-sb-thread
324   (:generator 0
325     (unless (zerop amount)
326       (let ((delta (logandc2 (+ amount 7) 7)))
327         (inst add (make-ea :qword
328                            :disp (+ nil-value
329                                     (static-symbol-offset '*alien-stack*)
330                                     (ash symbol-value-slot word-shift)
331                                     (- other-pointer-lowtag)))
332               delta)))))
333
334 ;;; these are not strictly part of the c-call convention, but are
335 ;;; needed for the WITH-PRESERVED-POINTERS macro used for "locking
336 ;;; down" lisp objects so that GC won't move them while foreign
337 ;;; functions go to work.
338
339 (define-vop (push-word-on-c-stack)
340     (:translate push-word-on-c-stack)
341   (:args (val :scs (sap-reg)))
342   (:policy :fast-safe)
343   (:arg-types system-area-pointer)
344   (:generator 2
345     (inst push val)))
346
347 (define-vop (pop-words-from-c-stack)
348     (:translate pop-words-from-c-stack)
349   (:args)
350   (:arg-types (:constant (unsigned-byte 60)))
351   (:info number)
352   (:policy :fast-safe)
353   (:generator 2
354     (inst add rsp-tn (fixnumize number))))
355
356 ;;; Callbacks
357
358 #-sb-xc-host
359 (defun alien-callback-accessor-form (type sp offset)
360   `(deref (sap-alien (sap+ ,sp ,offset) (* ,type))))
361
362 #-sb-xc-host
363 (defun alien-callback-assembler-wrapper (index result-type argument-types)
364   (labels ((make-tn-maker (sc-name)
365              (lambda (offset)
366                (make-random-tn :kind :normal
367                                :sc (sc-or-lose sc-name)
368                                :offset offset)))
369            (out-of-registers-error ()
370              (error "Too many arguments in callback")))
371     (let* ((segment (make-segment))
372            (rax rax-tn)
373            (rcx rcx-tn)
374            (rdi rdi-tn)
375            (rsi rsi-tn)
376            (rdx rdx-tn)
377            (rbp rbp-tn)
378            (rsp rsp-tn)
379            (xmm0 float0-tn)
380            ([rsp] (make-ea :qword :base rsp :disp 0))
381            ;; How many arguments have been copied
382            (arg-count 0)
383            ;; How many arguments have been copied from the stack
384            (stack-argument-count 0)
385            (gprs (mapcar (make-tn-maker 'any-reg) *c-call-register-arg-offsets*))
386            (fprs (mapcar (make-tn-maker 'double-reg)
387                          ;; Only 8 first XMM registers are used for
388                          ;; passing arguments
389                          (subseq *float-regs* 0 8))))
390       (assemble (segment)
391         ;; Make room on the stack for arguments.
392         (inst sub rsp (* n-word-bytes (length argument-types)))
393         ;; Copy arguments from registers to stack
394         (dolist (type argument-types)
395           (let ((integerp (not (alien-float-type-p type)))
396                 ;; A TN pointing to the stack location where the
397                 ;; current argument should be stored for the purposes
398                 ;; of ENTER-ALIEN-CALLBACK.
399                 (target-tn (make-ea :qword :base rsp
400                                    :disp (* arg-count
401                                             n-word-bytes)))
402                 ;; A TN pointing to the stack location that contains
403                 ;; the next argument passed on the stack.
404                 (stack-arg-tn (make-ea :qword :base rsp
405                                        :disp (* (+ 1
406                                                    (length argument-types)
407                                                    stack-argument-count)
408                                                 n-word-bytes))))
409             (incf arg-count)
410             (cond (integerp
411                    (let ((gpr (pop gprs)))
412                      ;; Argument not in register, copy it from the old
413                      ;; stack location to a temporary register.
414                      (unless gpr
415                        (incf stack-argument-count)
416                        (setf gpr temp-reg-tn)
417                        (inst mov gpr stack-arg-tn))
418                      ;; Copy from either argument register or temporary
419                      ;; register to target.
420                      (inst mov target-tn gpr)))
421                   ((or (alien-single-float-type-p type)
422                        (alien-double-float-type-p type))
423                    (let ((fpr (pop fprs)))
424                      (cond (fpr
425                             ;; Copy from float register to target location.
426                             (inst movq target-tn fpr))
427                            (t
428                             ;; Not in float register. Copy from stack to
429                             ;; temporary (general purpose) register, and
430                             ;; from there to the target location.
431                             (incf stack-argument-count)
432                             (inst mov temp-reg-tn stack-arg-tn)
433                             (inst mov target-tn temp-reg-tn)))))
434                   (t
435                    (bug "Unknown alien floating point type: ~S" type)))))
436
437         ;; arg0 to FUNCALL3 (function)
438         ;;
439         ;; Indirect the access to ENTER-ALIEN-CALLBACK through
440         ;; the symbol-value slot of SB-ALIEN::*ENTER-ALIEN-CALLBACK*
441         ;; to ensure it'll work even if the GC moves ENTER-ALIEN-CALLBACK.
442         ;; Skip any SB-THREAD TLS magic, since we don't expect anyone
443         ;; to rebind the variable. -- JES, 2006-01-01
444         (inst mov rdi (+ nil-value (static-symbol-offset
445                                     'sb!alien::*enter-alien-callback*)))
446         (loadw rdi rdi symbol-value-slot other-pointer-lowtag)
447         ;; arg0 to ENTER-ALIEN-CALLBACK (trampoline index)
448         (inst mov rsi (fixnumize index))
449         ;; arg1 to ENTER-ALIEN-CALLBACK (pointer to argument vector)
450         (inst mov rdx rsp)
451         ;; add room on stack for return value
452         (inst sub rsp 8)
453         ;; arg2 to ENTER-ALIEN-CALLBACK (pointer to return value)
454         (inst mov rcx rsp)
455
456         ;; Make new frame
457         (inst push rbp)
458         (inst mov  rbp rsp)
459
460         ;; Call
461         (inst mov  rax (foreign-symbol-address "funcall3"))
462         (inst call rax)
463
464         ;; Back! Restore frame
465         (inst mov rsp rbp)
466         (inst pop rbp)
467
468         ;; Result now on top of stack, put it in the right register
469         (cond
470           ((or (alien-integer-type-p result-type)
471                (alien-pointer-type-p result-type)
472                (alien-type-= #.(parse-alien-type 'system-area-pointer nil)
473                              result-type))
474            (inst mov rax [rsp]))
475           ((or (alien-single-float-type-p result-type)
476                (alien-double-float-type-p result-type))
477            (inst movq xmm0 [rsp]))
478           ((alien-void-type-p result-type))
479           (t
480            (error "unrecognized alien type: ~A" result-type)))
481
482         ;; Pop the arguments and the return value from the stack to get
483         ;; the return address at top of stack.
484         (inst add rsp (* (1+ (length argument-types)) n-word-bytes))
485         ;; Return
486         (inst ret))
487       (finalize-segment segment)
488       ;; Now that the segment is done, convert it to a static
489       ;; vector we can point foreign code to.
490       (let ((buffer (sb!assem::segment-buffer segment)))
491         (make-static-vector (length buffer)
492                             :element-type '(unsigned-byte 8)
493                             :initial-contents buffer)))))