1.0.25.49: x86/x86-64 unithread: use the allocated alien stack
[sbcl.git] / src / compiler / x86 / 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   (stack-frame-size 0))
27
28 (define-alien-type-method (integer :arg-tn) (type state)
29   (let ((stack-frame-size (arg-state-stack-frame-size state)))
30     (setf (arg-state-stack-frame-size state) (1+ stack-frame-size))
31     (multiple-value-bind (ptype stack-sc)
32         (if (alien-integer-type-signed type)
33             (values 'signed-byte-32 'signed-stack)
34             (values 'unsigned-byte-32 'unsigned-stack))
35       (my-make-wired-tn ptype stack-sc stack-frame-size))))
36
37 (define-alien-type-method (system-area-pointer :arg-tn) (type state)
38   (declare (ignore type))
39   (let ((stack-frame-size (arg-state-stack-frame-size state)))
40     (setf (arg-state-stack-frame-size state) (1+ stack-frame-size))
41     (my-make-wired-tn 'system-area-pointer
42                       'sap-stack
43                       stack-frame-size)))
44
45 #!+long-float
46 (define-alien-type-method (long-float :arg-tn) (type state)
47   (declare (ignore type))
48   (let ((stack-frame-size (arg-state-stack-frame-size state)))
49     (setf (arg-state-stack-frame-size state) (+ stack-frame-size 3))
50     (my-make-wired-tn 'long-float 'long-stack stack-frame-size)))
51
52 (define-alien-type-method (double-float :arg-tn) (type state)
53   (declare (ignore type))
54   (let ((stack-frame-size (arg-state-stack-frame-size state)))
55     (setf (arg-state-stack-frame-size state) (+ stack-frame-size 2))
56     (my-make-wired-tn 'double-float 'double-stack stack-frame-size)))
57
58 (define-alien-type-method (single-float :arg-tn) (type state)
59   (declare (ignore type))
60   (let ((stack-frame-size (arg-state-stack-frame-size state)))
61     (setf (arg-state-stack-frame-size state) (1+ stack-frame-size))
62     (my-make-wired-tn 'single-float 'single-stack stack-frame-size)))
63
64 (defstruct (result-state (:copier nil))
65   (num-results 0))
66
67 (defun result-reg-offset (slot)
68   (ecase slot
69     (0 eax-offset)
70     (1 edx-offset)))
71
72 (define-alien-type-method (integer :result-tn) (type state)
73   (let ((num-results (result-state-num-results state)))
74     (setf (result-state-num-results state) (1+ num-results))
75     (multiple-value-bind (ptype reg-sc)
76         (if (alien-integer-type-signed type)
77             (values 'signed-byte-32 'signed-reg)
78             (values 'unsigned-byte-32 'unsigned-reg))
79       (my-make-wired-tn ptype reg-sc (result-reg-offset num-results)))))
80
81 (define-alien-type-method (integer :naturalize-gen) (type alien)
82   (if (and (alien-integer-type-signed type)
83            (<= (alien-type-bits type) 16))
84       `(sign-extend ,alien ,(alien-type-bits type))
85       alien))
86
87 (define-alien-type-method (system-area-pointer :result-tn) (type state)
88   (declare (ignore type))
89   (let ((num-results (result-state-num-results state)))
90     (setf (result-state-num-results state) (1+ num-results))
91     (my-make-wired-tn 'system-area-pointer 'sap-reg
92                       (result-reg-offset num-results))))
93
94 #!+long-float
95 (define-alien-type-method (long-float :result-tn) (type state)
96   (declare (ignore type))
97   (let ((num-results (result-state-num-results state)))
98     (setf (result-state-num-results state) (1+ num-results))
99     (my-make-wired-tn 'long-float 'long-reg (* num-results 2))))
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 2))))
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 2))))
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) 32)))
144                   arg-types)
145             (and (alien-integer-type-p result-type)
146                  (> (sb!alien::alien-integer-type-bits result-type) 32)))
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) 32))
153                      (new-args `(logand ,arg #xffffffff))
154                      (new-args `(ash ,arg -32))
155                      (new-arg-types (parse-alien-type '(unsigned 32) env))
156                      (if (alien-integer-type-signed type)
157                          (new-arg-types (parse-alien-type '(signed 32) env))
158                          (new-arg-types (parse-alien-type '(unsigned 32) 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) 32))
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 32) (signed 32))
169                                '(values (unsigned 32) (unsigned 32)))
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 32))))))
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 is vague about how signed sub-word integer return values
191 ;;; are handled, but since gcc versions >=4.3 no longer do sign
192 ;;; extension in the callee, we need to do it in the caller.
193 (defknown sign-extend ((signed-byte 16) t) fixnum
194     (foldable flushable movable))
195
196 (define-vop (sign-extend)
197   (:translate sign-extend)
198   (:policy :fast-safe)
199   ;; Need to wire this to EAX since in x86 some dword registers don't
200   ;; have a matching word or byte register.
201   (:args (val :scs (signed-reg) :target eax))
202   (:temporary (:sc signed-reg :offset eax-offset :from :eval :to :result) eax)
203   (:arg-types fixnum (:constant fixnum))
204   (:info size)
205   (:results (res :scs (signed-reg)))
206   (:result-types fixnum)
207   (:ignore eax)
208   (:generator 1
209    (inst movsx res
210          (make-random-tn :kind :normal
211                          :sc (sc-or-lose (ecase size
212                                            (8 'byte-reg)
213                                            (16 'word-reg)))
214                          :offset (tn-offset val)))))
215
216 #-sb-xc-host
217 (defun sign-extend (x size)
218   (declare (type fixnum x))
219   (ecase size
220     (8 (sign-extend x size))
221     (16 (sign-extend x size))))
222
223 #+sb-xc-host
224 (defun sign-extend (x size)
225   (if (logbitp (1- size) x)
226       (dpb x (byte size 0) -1)
227       x))
228
229 (define-vop (foreign-symbol-sap)
230   (:translate foreign-symbol-sap)
231   (:policy :fast-safe)
232   (:args)
233   (:arg-types (:constant simple-string))
234   (:info foreign-symbol)
235   (:results (res :scs (sap-reg)))
236   (:result-types system-area-pointer)
237   (:generator 2
238    (inst lea res (make-fixup foreign-symbol :foreign))))
239
240 #!+linkage-table
241 (define-vop (foreign-symbol-dataref-sap)
242   (:translate foreign-symbol-dataref-sap)
243   (:policy :fast-safe)
244   (:args)
245   (:arg-types (:constant simple-string))
246   (:info foreign-symbol)
247   (:results (res :scs (sap-reg)))
248   (:result-types system-area-pointer)
249   (:generator 2
250    (inst mov res (make-fixup foreign-symbol :foreign-dataref))))
251
252 (define-vop (call-out)
253   (:args (function :scs (sap-reg))
254          (args :more t))
255   (:results (results :more t))
256   (:temporary (:sc unsigned-reg :offset eax-offset
257                    :from :eval :to :result) eax)
258   (:temporary (:sc unsigned-reg :offset ecx-offset
259                    :from :eval :to :result) ecx)
260   (:temporary (:sc unsigned-reg :offset edx-offset
261                    :from :eval :to :result) edx)
262   (:node-var node)
263   (:vop-var vop)
264   (:save-p t)
265   (:ignore args ecx edx)
266   (:generator 0
267     ;; FIXME & OAOOM: This is brittle and error-prone to maintain two
268     ;; instances of the same logic, on in arch-assem.S, and one in
269     ;; c-call.lisp. If you modify this, modify that one too...
270     (cond ((policy node (> space speed))
271            (move eax function)
272            (inst call (make-fixup "call_into_c" :foreign)))
273           (t
274            ;; Setup the NPX for C; all the FP registers need to be
275            ;; empty; pop them all.
276            (dotimes (i 8)
277              (inst fstp fr0-tn))
278
279            ;; Clear out DF: Darwin, Windows, and Solaris at least require
280            ;; this, and it should not hurt others either.
281            (inst cld)
282
283            (inst call function)
284            ;; To give the debugger a clue. FIXME: not really internal-error?
285            (note-this-location vop :internal-error)
286
287            ;; Restore the NPX for lisp; ensure no regs are empty
288            (dotimes (i 7)
289              (inst fldz))
290
291            (if (and results
292                     (location= (tn-ref-tn results) fr0-tn))
293                ;; The return result is in fr0.
294                (inst fxch fr7-tn)       ; move the result back to fr0
295                (inst fldz))             ; insure no regs are empty
296            ))))
297
298 ;;; While SBCL uses the FPU in 53-bit mode, most C libraries assume that
299 ;;; the FPU is in 64-bit mode. So we change the FPU mode to 64-bit with
300 ;;; the SET-FPU-WORD-FOR-C VOP before calling out to C and set it back
301 ;;; to 53-bit mode after coming back using the SET-FPU-WORD-FOR-LISP VOP.
302 (define-vop (set-fpu-word-for-c)
303   (:node-var node)
304   (:generator 0
305     (when (policy node (= sb!c::float-accuracy 3))
306       (inst sub esp-tn 4)
307       (inst fnstcw (make-ea :word :base esp-tn))
308       (inst wait)
309       (inst or (make-ea :word :base esp-tn) #x300)
310       (inst fldcw (make-ea :word :base esp-tn))
311       (inst wait))))
312
313 (define-vop (set-fpu-word-for-lisp)
314   (:node-var node)
315   (:generator 0
316     (when (policy node (= sb!c::float-accuracy 3))
317       (inst fnstcw (make-ea :word :base esp-tn))
318       (inst wait)
319       (inst and (make-ea :word :base esp-tn) #xfeff)
320       (inst fldcw (make-ea :word :base esp-tn))
321       (inst wait)
322       (inst add esp-tn 4))))
323
324 (define-vop (alloc-number-stack-space)
325   (:info amount)
326   (:results (result :scs (sap-reg any-reg)))
327   (:result-types system-area-pointer)
328   (:generator 0
329     (aver (location= result esp-tn))
330     (unless (zerop amount)
331       (let ((delta (logandc2 (+ amount 3) 3)))
332         (inst sub esp-tn delta)))
333     (align-stack-pointer esp-tn)
334     (move result esp-tn)))
335
336 (define-vop (alloc-alien-stack-space)
337   (:info amount)
338   #!+sb-thread (:temporary (:sc unsigned-reg) temp)
339   (:results (result :scs (sap-reg any-reg)))
340   (:result-types system-area-pointer)
341   #!+sb-thread
342   (:generator 0
343     (aver (not (location= result esp-tn)))
344     (unless (zerop amount)
345       (let ((delta (logandc2 (+ amount 3) 3)))
346         (inst mov temp
347               (make-ea-for-symbol-tls-index *alien-stack*))
348         (inst sub (make-ea :dword :base temp) delta :fs)))
349     (load-tl-symbol-value result *alien-stack*))
350   #!-sb-thread
351   (:generator 0
352     (aver (not (location= result esp-tn)))
353     (unless (zerop amount)
354       (let ((delta (logandc2 (+ amount 3) 3)))
355         (inst sub (make-ea-for-symbol-value *alien-stack*)
356               delta)))
357     (load-symbol-value result *alien-stack*)))
358
359 (define-vop (dealloc-alien-stack-space)
360   (:info amount)
361   #!+sb-thread (:temporary (:sc unsigned-reg) temp)
362   #!+sb-thread
363   (:generator 0
364     (unless (zerop amount)
365       (let ((delta (logandc2 (+ amount 3) 3)))
366         (inst mov temp
367               (make-ea-for-symbol-tls-index *alien-stack*))
368         (inst add (make-ea :dword :base temp) delta :fs))))
369   #!-sb-thread
370   (:generator 0
371     (unless (zerop amount)
372       (let ((delta (logandc2 (+ amount 3) 3)))
373         (inst add (make-ea-for-symbol-value *alien-stack*)
374               delta)))))
375
376 ;;; not strictly part of the c-call convention, but needed for the
377 ;;; WITH-PINNED-OBJECTS macro used for "locking down" lisp objects so
378 ;;; that GC won't move them while foreign functions go to work.
379 (define-vop (touch-object)
380   (:translate touch-object)
381   (:args (object))
382   (:ignore object)
383   (:policy :fast-safe)
384   (:arg-types t)
385   (:generator 0))
386
387 #-sb-xc-host
388 (defun alien-callback-accessor-form (type sp offset)
389   `(deref (sap-alien (sap+ ,sp ,offset) (* ,type))))
390
391 #-sb-xc-host
392 (defun alien-callback-assembler-wrapper (index return-type arg-types)
393   "Cons up a piece of code which calls call-callback with INDEX and a
394 pointer to the arguments."
395   (declare (ignore arg-types))
396   (let* ((segment (make-segment))
397          (eax eax-tn)
398          (edx edx-tn)
399          (ebp ebp-tn)
400          (esp esp-tn)
401          ([ebp-8] (make-ea :dword :base ebp :disp -8))
402          ([ebp-4] (make-ea :dword :base ebp :disp -4)))
403     (assemble (segment)
404               (inst push ebp)                       ; save old frame pointer
405               (inst mov  ebp esp)                   ; establish new frame
406               (inst mov  eax esp)                   ;
407               (inst sub  eax 8)                     ; place for result
408               (inst push eax)                       ; arg2
409               (inst add  eax 16)                    ; arguments
410               (inst push eax)                       ; arg1
411               (inst push (ash index 2))             ; arg0
412
413               ;; Indirect the access to ENTER-ALIEN-CALLBACK through
414               ;; the symbol-value slot of SB-ALIEN::*ENTER-ALIEN-CALLBACK*
415               ;; to ensure it'll work even if the GC moves ENTER-ALIEN-CALLBACK.
416               ;; Skip any SB-THREAD TLS magic, since we don't expecte anyone
417               ;; to rebind the variable. -- JES, 2006-01-01
418               (load-symbol-value eax sb!alien::*enter-alien-callback*)
419               (inst push eax) ; function
420               (inst mov  eax (foreign-symbol-address "funcall3"))
421               (inst call eax)
422               ;; now put the result into the right register
423               (cond
424                 ((and (alien-integer-type-p return-type)
425                       (eql (alien-type-bits return-type) 64))
426                  (inst mov eax [ebp-8])
427                  (inst mov edx [ebp-4]))
428                 ((or (alien-integer-type-p return-type)
429                      (alien-pointer-type-p return-type)
430                      (alien-type-= #.(parse-alien-type 'system-area-pointer nil)
431                                    return-type))
432                  (inst mov eax [ebp-8]))
433                 ((alien-single-float-type-p return-type)
434                  (inst fld  [ebp-8]))
435                 ((alien-double-float-type-p return-type)
436                  (inst fldd [ebp-8]))
437                 ((alien-void-type-p return-type))
438                 (t
439                  (error "unrecognized alien type: ~A" return-type)))
440               (inst mov esp ebp)                   ; discard frame
441               (inst pop ebp)                       ; restore frame pointer
442               (inst ret))
443     (finalize-segment segment)
444     ;; Now that the segment is done, convert it to a static
445     ;; vector we can point foreign code to.
446     (let ((buffer (sb!assem::segment-buffer segment)))
447       (make-static-vector (length buffer)
448                           :element-type '(unsigned-byte 8)
449                           :initial-contents buffer))))