Debian Codegraph @

rpython/jit/backend/x86/callbuilder.py

raw symbols SCIP
1 import sys
2 from rpython.rlib.clibffi import FFI_DEFAULT_ABI
3 from rpython.rlib.objectmodel import we_are_translated
4 from rpython.rlib.rarithmetic import intmask
5 from rpython.jit.metainterp.history import INT, FLOAT
6 from rpython.jit.backend.x86.arch import (WORD, IS_X86_64, IS_X86_32,
7 PASS_ON_MY_FRAME, FRAME_FIXED_SIZE,
8 THREADLOCAL_OFS, WIN64)
9 from rpython.jit.backend.x86.regloc import (eax, ecx, edx, ebx, esp, ebp, esi,
10 xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, r8, r9, r10, r11, edi,
11 r12, r13, r14, r15, X86_64_SCRATCH_REG, X86_64_XMM_SCRATCH_REG,
12 RegLoc, RawEspLoc, RawEbpLoc, imm, ImmedLoc)
13 from rpython.jit.backend.x86.jump import remap_frame_layout
14 from rpython.jit.backend.x86 import codebuf
15 from rpython.jit.backend.llsupport.callbuilder import AbstractCallBuilder
16 from rpython.jit.backend.llsupport import llerrno, lltls
17 from rpython.rtyper.lltypesystem import llmemory, rffi
18
19
20 # darwin requires the stack to be 16 bytes aligned on calls.
21 # Same for gcc 4.5.0, better safe than sorry
22 CALL_ALIGN = 16 // WORD
23
24 stdcall_or_cdecl = sys.platform == "win32"
25 handle_lasterror = sys.platform == "win32"
26
27 def align_stack_words(words):
28 return (words + CALL_ALIGN - 1) & ~(CALL_ALIGN-1)
29
30 def follow_jump(addr):
31 # If 'addr' is immediately starting with another JMP instruction,
32 # follow it now. 'addr' is an absolute address here
33 while rffi.cast(rffi.CCHARP, addr)[0] == '\xE9': # JMP <4 bytes>
34 addr += 5
35 addr += intmask(rffi.cast(rffi.INTP, addr - 4)[0])
36 return addr
37
38
39 class CallBuilderX86(AbstractCallBuilder):
40
41 # max number of words we have room in esp; if we need more for
42 # arguments, we need to decrease esp temporarily
43 stack_max = PASS_ON_MY_FRAME
44
45 tlofs_reg = None
46 saved_stack_position_reg = None
47 result_value_saved_early = False
48
49 def __init__(self, assembler, fnloc, arglocs,
50 resloc=eax, restype=INT, ressize=WORD):
51 AbstractCallBuilder.__init__(self, assembler, fnloc, arglocs,
52 resloc, restype, ressize)
53 # Avoid tons of issues with a non-immediate fnloc by sticking it
54 # as an extra argument if needed
55 if isinstance(fnloc, ImmedLoc):
56 self.fnloc_is_immediate = True
57 self.fnloc = imm(follow_jump(fnloc.value))
58 else:
59 self.fnloc_is_immediate = False
60 self.fnloc = None
61 self.arglocs = arglocs + [fnloc]
62 self.start_frame_size = self.mc._frame_size
63
64 def subtract_esp_aligned(self, count):
65 if count > 0:
66 align = align_stack_words(count)
67 self.mc.SUB_ri(esp.value, align * WORD)
68
69 def get_current_esp(self):
70 return self.start_frame_size - self.mc._frame_size
71
72 def restore_stack_pointer(self, target_esp=0):
73 current_esp = self.get_current_esp()
74 if current_esp != target_esp:
75 self.mc.ADD_ri(esp.value, target_esp - current_esp)
76
77 def load_result(self):
78 """Overridden in CallBuilder32 and CallBuilder64"""
79 if self.ressize == 0:
80 return # void result
81 # use the code in load_from_mem to do the zero- or sign-extension
82 if self.restype == FLOAT:
83 srcloc = xmm0
84 else:
85 srcloc = eax
86 if self.ressize >= WORD and self.resloc is srcloc:
87 return # no need for any MOV
88 if self.ressize == 1 and isinstance(srcloc, RegLoc):
89 srcloc = srcloc.lowest8bits()
90 self.asm.load_from_mem(self.resloc, srcloc,
91 imm(self.ressize), imm(self.ressign))
92
93 def push_gcmap(self):
94 # we push *now* the gcmap, describing the status of GC registers
95 # after the rearrangements done just before, ignoring the return
96 # value eax, if necessary
97 assert not self.is_call_release_gil
98 current_esp = self.get_current_esp()
99 #
100 # * Note: these commented-out pieces of code about 'extra_stack_depth'
101 # * are not necessary any more, but they are kept around in case we
102 # * need in the future again to track the exact stack depth.
103 #
104 #self.change_extra_stack_depth = (current_esp != 0)
105 #if self.change_extra_stack_depth:
106 # self.asm.set_extra_stack_depth(self.mc, -current_esp)
107 noregs = self.asm.cpu.gc_ll_descr.is_shadow_stack()
108 gcmap = self.asm._regalloc.get_gcmap([eax], noregs=noregs)
109 self.asm.push_gcmap(self.mc, gcmap, store=True)
110
111 def pop_gcmap(self):
112 ssreg = None
113 gcrootmap = self.asm.cpu.gc_ll_descr.gcrootmap
114 if gcrootmap:
115 if gcrootmap.is_shadow_stack and self.is_call_release_gil:
116 # in this mode, 'ebx' happens to contain the shadowstack
117 # top at this point, so reuse it instead of loading it again
118 ssreg = ebx
119 self.asm._reload_frame_if_necessary(self.mc, shadowstack_reg=ssreg)
120 #if self.change_extra_stack_depth:
121 # self.asm.set_extra_stack_depth(self.mc, 0)
122 self.asm.pop_gcmap(self.mc)
123
124 def call_releasegil_addr_and_move_real_arguments(self, fastgil):
125 from rpython.jit.backend.x86.assembler import heap
126 assert self.is_call_release_gil
127 assert not self.asm._is_asmgcc()
128 #
129 # Save this thread's shadowstack pointer into 'ebx',
130 # for later comparison
131 gcrootmap = self.asm.cpu.gc_ll_descr.gcrootmap
132 if gcrootmap:
133 if gcrootmap.is_shadow_stack:
134 rst = gcrootmap.get_root_stack_top_addr()
135 self.mc.MOV(ebx, heap(rst))
136 #
137 # shadowstack: change 'rpy_fastgil' to 0 (it should be
138 # non-zero right now).
139 #self.change_extra_stack_depth = False
140 #
141 # <--here--> would come a memory fence, if the CPU needed one.
142 self.mc.MOV(heap(fastgil), imm(0))
143 #
144 if not we_are_translated(): # for testing: we should not access
145 self.mc.ADD(ebp, imm(1)) # ebp any more
146
147 def get_tlofs_reg(self):
148 """Load the THREADLOCAL_OFS from the stack into a callee-saved
149 register. Further calls just return the same register, by assuming
150 it is indeed saved."""
151 assert self.is_call_release_gil
152 if self.tlofs_reg is None:
153 # pick a register saved across calls
154 if IS_X86_32:
155 self.tlofs_reg = esi
156 else:
157 self.tlofs_reg = r12
158 self.mc.MOV_rs(self.tlofs_reg.value,
159 THREADLOCAL_OFS - self.get_current_esp())
160 return self.tlofs_reg
161
162 def save_stack_position(self):
163 """Load the current 'esp' value into a callee-saved register.
164 Further calls just return the same register, by assuming it is
165 indeed saved."""
166 assert IS_X86_32 # only for 32-bit Windows
167 assert stdcall_or_cdecl and self.is_call_release_gil
168 if self.saved_stack_position_reg is None:
169 # pick a register saved across calls
170 self.saved_stack_position_reg = edi
171 self.mc.MOV(self.saved_stack_position_reg, esp)
172
173 def write_real_errno(self, save_err):
174 """This occurs just before emit_raw_call().
175 """
176 mc = self.mc
177
178 if handle_lasterror and (save_err & rffi.RFFI_READSAVED_LASTERROR):
179 # must call SetLastError(). There are no registers to save
180 # if we are on 32-bit in this case: no register contains
181 # the arguments to the main function we want to call afterwards.
182 # On win64, though, it's more messy. It could be better optimized
183 # but for now we save (again) the registers containing arguments,
184 # and restore them afterwards.
185 from rpython.rlib.rwin32 import _SetLastError
186 adr = llmemory.cast_ptr_to_adr(_SetLastError)
187 SetLastError_addr = self.asm.cpu.cast_adr_to_int(adr)
188 #
189 if save_err & rffi.RFFI_ALT_ERRNO:
190 lasterror = llerrno.get_alt_lasterror_offset(self.asm.cpu)
191 else:
192 lasterror = llerrno.get_rpy_lasterror_offset(self.asm.cpu)
193 tlofsreg = self.get_tlofs_reg() # => esi or r12, callee-saved
194 if not WIN64:
195 self.save_stack_position() # => edi, callee-saved
196 mc.PUSH_m((tlofsreg.value, lasterror))
197 mc.CALL(imm(follow_jump(SetLastError_addr)))
198 # restore the stack position without assuming a particular
199 # calling convention of _SetLastError()
200 self.mc.stack_frame_size_delta(-WORD)
201 self.mc.MOV(esp, self.saved_stack_position_reg)
202 else:
203 self.win64_save_register_args()
204 mc.MOV_rm(ecx.value, (tlofsreg.value, lasterror))
205 mc.CALL(imm(follow_jump(SetLastError_addr)))
206 self.win64_restore_register_args()
207
208 if save_err & rffi.RFFI_READSAVED_ERRNO:
209 # Just before a call, read '*_errno' and write it into the
210 # real 'errno'. Most registers are free here, including the
211 # callee-saved ones, except 'ebx' and except the ones used to
212 # pass the arguments on x86-64.
213 if save_err & rffi.RFFI_ALT_ERRNO:
214 rpy_errno = llerrno.get_alt_errno_offset(self.asm.cpu)
215 else:
216 rpy_errno = llerrno.get_rpy_errno_offset(self.asm.cpu)
217 p_errno = llerrno.get_p_errno_offset(self.asm.cpu)
218 tlofsreg = self.get_tlofs_reg() # => esi or r12, callee-saved
219 if IS_X86_32:
220 tmpreg = edx
221 else:
222 tmpreg = r10 # edx is used for 3rd argument
223 mc.MOV_rm(tmpreg.value, (tlofsreg.value, p_errno))
224 mc.MOV32_rm(eax.value, (tlofsreg.value, rpy_errno))
225 mc.MOV32_mr((tmpreg.value, 0), eax.value)
226 elif save_err & rffi.RFFI_ZERO_ERRNO_BEFORE:
227 # Same, but write zero.
228 p_errno = llerrno.get_p_errno_offset(self.asm.cpu)
229 tlofsreg = self.get_tlofs_reg() # => esi or r12, callee-saved
230 mc.MOV_rm(eax.value, (tlofsreg.value, p_errno))
231 mc.MOV32_mi((eax.value, 0), 0)
232
233 def read_real_errno(self, save_err):
234 """This occurs after emit_raw_call() and after restore_stack_pointer().
235 """
236 mc = self.mc
237
238 if save_err & rffi.RFFI_SAVE_ERRNO:
239 # Just after a call, read the real 'errno' and save a copy of
240 # it inside our thread-local '*_errno'. Most registers are
241 # free here, including the callee-saved ones, except 'ebx'.
242 # The tlofs register might have been loaded earlier and is
243 # callee-saved, so it does not need to be reloaded.
244 if save_err & rffi.RFFI_ALT_ERRNO:
245 rpy_errno = llerrno.get_alt_errno_offset(self.asm.cpu)
246 else:
247 rpy_errno = llerrno.get_rpy_errno_offset(self.asm.cpu)
248 p_errno = llerrno.get_p_errno_offset(self.asm.cpu)
249 tlofsreg = self.get_tlofs_reg() # => esi or r12 (possibly reused)
250 mc.MOV_rm(ecx.value, (tlofsreg.value, p_errno))
251 mc.MOV32_rm(ecx.value, (ecx.value, 0))
252 mc.MOV32_mr((tlofsreg.value, rpy_errno), ecx.value)
253
254 if handle_lasterror and (save_err & (rffi.RFFI_SAVE_LASTERROR |
255 rffi.RFFI_SAVE_WSALASTERROR)):
256 if save_err & rffi.RFFI_SAVE_LASTERROR:
257 from rpython.rlib.rwin32 import _GetLastError
258 adr = llmemory.cast_ptr_to_adr(_GetLastError)
259 else:
260 from rpython.rlib._rsocket_rffi import _WSAGetLastError
261 adr = llmemory.cast_ptr_to_adr(_WSAGetLastError)
262 GetLastError_addr = self.asm.cpu.cast_adr_to_int(adr)
263 #
264 if save_err & rffi.RFFI_ALT_ERRNO:
265 lasterror = llerrno.get_alt_lasterror_offset(self.asm.cpu)
266 else:
267 lasterror = llerrno.get_rpy_lasterror_offset(self.asm.cpu)
268 self.save_result_value(save_edx=True) # save eax/edx/xmm0
269 self.result_value_saved_early = True
270 mc.CALL(imm(follow_jump(GetLastError_addr)))
271 #
272 tlofsreg = self.get_tlofs_reg() # => esi or r12 (possibly reused)
273 mc.MOV32_mr((tlofsreg.value, lasterror), eax.value)
274
275 class ReacqGilSlowPath(codebuf.SlowPath):
276 early_jump_addr = 0
277
278 def generate_body(self, assembler, mc):
279 if self.early_jump_addr != 0:
280 # This slow-path has two entry points, with two
281 # conditional jumps. We can jump to the regular start
282 # of this slow-path with the 2nd conditional jump. Or,
283 # we can jump past the "MOV(heap(fastgil), 0)"
284 # instruction from the 1st conditional jump.
285 # This instruction reverts the rpy_fastgil acquired
286 # previously, so that the general 'reacqgil_addr'
287 # function can acquire it again. It must only be done
288 # if we actually succeeded in acquiring rpy_fastgil.
289 from rpython.jit.backend.x86.assembler import heap
290 mc.MOV(heap(self.fastgil), imm(0))
291 offset = mc.get_relative_pos() - self.early_jump_addr
292 mc.overwrite32(self.early_jump_addr-4, offset)
293 # scratch register forgotten here, by get_relative_pos()
294
295 # call the reacqgil() function
296 cb = self.callbuilder
297 if not cb.result_value_saved_early:
298 cb.save_result_value(save_edx=False)
299 mc.CALL(imm(follow_jump(assembler.reacqgil_addr)))
300 if not cb.result_value_saved_early:
301 cb.restore_result_value(save_edx=False)
302
303 def move_real_result_and_call_reacqgil_addr(self, fastgil):
304 from rpython.jit.backend.x86 import rx86
305 #
306 # check if we need to call the reacqgil() function or not
307 # (to acquiring the GIL)
308 mc = self.mc
309 restore_edx = False
310 #
311 # Make sure we can use 'eax' in the sequel for CMPXCHG
312 # On 32-bit, we also need to check if restype is 'L' for long long,
313 # in which case we need to save eax and edx because they are both
314 # used for the return value.
315 if self.restype in (INT, 'L') and not self.result_value_saved_early:
316 self.save_result_value(save_edx = self.restype == 'L')
317 self.result_value_saved_early = True
318 #
319 # Use LOCK CMPXCHG as a compare-and-swap with memory barrier.
320 tlsreg = self.get_tlofs_reg()
321 thread_ident_ofs = lltls.get_thread_ident_offset(self.asm.cpu)
322 #
323 mc.MOV_rm(ecx.value, (tlsreg.value, thread_ident_ofs))
324 mc.XOR_rr(eax.value, eax.value)
325
326 if rx86.fits_in_32bits(fastgil):
327 mc.LOCK()
328 mc.CMPXCHG_jr(fastgil, ecx.value)
329 else:
330 mc.MOV_ri(X86_64_SCRATCH_REG.value, fastgil)
331 mc.LOCK()
332 mc.CMPXCHG_mr((X86_64_SCRATCH_REG.value, 0), ecx.value)
333 #
334 gcrootmap = self.asm.cpu.gc_ll_descr.gcrootmap
335 if bool(gcrootmap):
336 from rpython.jit.backend.x86.assembler import heap
337 assert gcrootmap.is_shadow_stack
338 #
339 # When doing a call_release_gil with shadowstack, there
340 # is the risk that the 'rpy_fastgil' was free but the
341 # current shadowstack can be the one of a different
342 # thread. So here we check if the shadowstack pointer
343 # is still the same as before we released the GIL (saved
344 # in 'ebx'), and if not, we fall back to 'reacqgil_addr'.
345 mc.J_il(rx86.Conditions['NZ'], 0xfffff) # patched later
346 early_jump_addr = mc.get_relative_pos(break_basic_block=False)
347 # ^^^ this jump will go to almost the same place as the
348 # ReacqGilSlowPath() computes, but one instruction further,
349 # i.e. just after the "MOV(heap(fastgil), 0)".
350
351 rst = gcrootmap.get_root_stack_top_addr()
352 mc = self.mc
353 mc.CMP(ebx, heap(rst))
354 sp = self.ReacqGilSlowPath(mc, rx86.Conditions['NE'])
355 sp.early_jump_addr = early_jump_addr
356 sp.fastgil = fastgil
357 else:
358 sp = self.ReacqGilSlowPath(mc, rx86.Conditions['NZ'])
359 sp.callbuilder = self
360 sp.set_continue_addr(mc)
361 self.asm.pending_slowpaths.append(sp)
362 #
363 if restore_edx:
364 mc.MOV_rs(edx.value, 12) # restore this
365 #
366 if self.result_value_saved_early:
367 self.restore_result_value(save_edx=True)
368 #
369 if not we_are_translated(): # for testing: now we can access
370 mc.SUB(ebp, imm(1)) # ebp again
371 #
372 # Now that we required the GIL, we will reload a possibly modified ebp:
373 # this done for us by _reload_frame_if_necessary()
374
375 def save_result_value(self, save_edx):
376 """Overridden in CallBuilder32 and CallBuilder64"""
377 raise NotImplementedError
378
379 def restore_result_value(self, save_edx):
380 """Overridden in CallBuilder32 and CallBuilder64"""
381 raise NotImplementedError
382
383
384 class CallBuilder32(CallBuilderX86):
385
386 def prepare_arguments(self):
387 arglocs = self.arglocs
388 stack_depth = 0
389 n = len(arglocs)
390 for i in range(n):
391 loc = arglocs[i]
392 stack_depth += loc.get_width() // WORD
393 self.subtract_esp_aligned(stack_depth - self.stack_max)
394 #
395 p = 0
396 num_moves = 0
397 for i in range(n):
398 loc = arglocs[i]
399 if isinstance(loc, RegLoc):
400 num_moves += 1
401 if loc.is_xmm:
402 self.mc.MOVSD_sx(p, loc.value)
403 else:
404 self.mc.MOV_sr(p, loc.value)
405 p += loc.get_width()
406 p = 0
407 for i in range(n):
408 loc = arglocs[i]
409 if not isinstance(loc, RegLoc):
410 if loc.get_width() == 8:
411 num_moves += 2
412 self.mc.MOVSD(xmm0, loc)
413 self.mc.MOVSD_sx(p, xmm0.value)
414 elif isinstance(loc, ImmedLoc):
415 num_moves += 1
416 self.mc.MOV_si(p, loc.value)
417 else:
418 num_moves += 2
419 self.mc.MOV(eax, loc)
420 self.mc.MOV_sr(p, eax.value)
421 p += loc.get_width()
422 self.total_stack_used_by_arguments = p
423 #
424 if not self.fnloc_is_immediate: # the last "argument" pushed above
425 self.fnloc = RawEspLoc(p - WORD, INT)
426 self.num_moves = num_moves
427
428 def emit_raw_call(self):
429 if IS_X86_32 and stdcall_or_cdecl and self.is_call_release_gil:
430 # Dynamically accept both stdcall and cdecl functions.
431 # We could try to detect from pyjitpl which calling
432 # convention this particular function takes, which would
433 # avoid these two extra MOVs... but later.
434 self.save_stack_position() # => edi (possibly reused)
435 self.mc.CALL(self.fnloc)
436 self.mc.MOV(esp, self.saved_stack_position_reg)
437 else:
438 self.mc.CALL(self.fnloc)
439 if IS_X86_32 and self.callconv != FFI_DEFAULT_ABI:
440 # in the STDCALL ABI, the CALL above has an effect on
441 # the stack depth. Adjust 'mc._frame_size'.
442 delta = self._fix_stdcall(self.callconv)
443 self.mc.stack_frame_size_delta(-delta)
444
445 def _fix_stdcall(self, callconv):
446 from rpython.rlib.clibffi import FFI_STDCALL
447 assert callconv == FFI_STDCALL
448 return self.total_stack_used_by_arguments
449
450 def load_result(self):
451 resloc = self.resloc
452 if resloc is not None and resloc.is_float():
453 # a float or a long long return
454 if self.restype == 'L': # long long
455 # move eax/edx -> xmm0
456 self.mc.MOVD32_xr(resloc.value^1, edx.value)
457 self.mc.MOVD32_xr(resloc.value, eax.value)
458 self.mc.PUNPCKLDQ_xx(resloc.value, resloc.value^1)
459 else:
460 # float: we have to go via the stack
461 self.mc.FSTPL_s(0)
462 self.mc.MOVSD_xs(resloc.value, 0)
463 #
464 elif self.restype == 'S':
465 # singlefloat return: must convert ST(0) to a 32-bit singlefloat
466 # and load it into self.resloc. mess mess mess
467 self.mc.FSTPS_s(0)
468 self.mc.MOV_rs(resloc.value, 0)
469 else:
470 CallBuilderX86.load_result(self)
471
472 def save_result_value(self, save_edx):
473 # Temporarily save the result value into [ESP+8]. We use "+8"
474 # in order to leave the two initial words free, in case it's needed.
475 # Also note that in this 32-bit case, a long long return value is
476 # in eax/edx, but we already saved the value of edx in
477 # move_real_result_and_call_reacqgil_addr().
478 if self.ressize == 0: # void return
479 return
480 if self.resloc.is_float():
481 # a float or a long long return
482 if self.restype == 'L':
483 self.mc.MOV_sr(8, eax.value) # long long
484 if save_edx:
485 self.mc.MOV_sr(12, edx.value)
486 else:
487 self.mc.FSTPL_s(8) # float return
488 else:
489 if self.restype == 'S':
490 self.mc.FSTPS_s(8)
491 else:
492 assert self.restype == INT
493 assert self.ressize <= WORD
494 self.mc.MOV_sr(8, eax.value)
495
496 def restore_result_value(self, save_edx):
497 # Opposite of save_result_value()
498 if self.ressize == 0: # void return
499 return
500 if self.resloc.is_float():
501 # a float or a long long return
502 if self.restype == 'L':
503 self.mc.MOV_rs(eax.value, 8) # long long
504 if save_edx:
505 self.mc.MOV_rs(edx.value, 12)
506 else:
507 self.mc.FLDL_s(8) # float return
508 else:
509 if self.restype == 'S':
510 self.mc.FLDS_s(8)
511 else:
512 assert self.restype == INT
513 assert self.ressize <= WORD
514 self.mc.MOV_rs(eax.value, 8)
515
516
517 class CallBuilder64(CallBuilderX86):
518
519 if not WIN64:
520 ARGUMENTS_GPR = [edi, esi, edx, ecx, r8, r9]
521 ARGUMENTS_XMM = [xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7]
522 else:
523 ARGUMENTS_GPR = [ecx, edx, r8, r9]
524 ARGUMENTS_XMM = [xmm0, xmm1, xmm2, xmm3]
525 ARG0 = ARGUMENTS_GPR[0]
526 ARG1 = ARGUMENTS_GPR[1]
527 ARG2 = ARGUMENTS_GPR[2]
528
529 next_arg_gpr = 0
530 next_arg_xmm = 0
531 win64_arg_gpr = 0
532 win64_arg_xmm = 0
533
534 def _unused_gpr(self, hint):
535 i = self.next_arg_gpr
536 self.next_arg_gpr = i + 1
537 if WIN64:
538 self.next_arg_xmm = self.next_arg_gpr
539 try:
540 res = self.ARGUMENTS_GPR[i]
541 except IndexError:
542 return None
543 if WIN64:
544 self.win64_arg_gpr |= 1 << i
545 return res
546
547 def _unused_xmm(self):
548 i = self.next_arg_xmm
549 self.next_arg_xmm = i + 1
550 if WIN64:
551 self.next_arg_gpr = self.next_arg_xmm
552 try:
553 res = self.ARGUMENTS_XMM[i]
554 except IndexError:
555 return None
556 if WIN64:
557 self.win64_arg_xmm |= 1 << i
558 return res
559
560 def win64_save_register_args(self):
561 # Arguments 0 to 3 are in argument registers; further arguments are already in the stack
562 # beyond 4 unused words that will be the shadow space for the CALL. We can save these
563 # arguments 0 to 3 inside that space, but after we do, we need to reserve another shadow
564 # space for the call to SetLastError that we'll do immediately afterwards...
565 # We might instead save arguments inside esi/edi/r14/r15 at this point, which should
566 # be free and callee-save on Win64. Unclear it's worth the crash if I'm wrong, though...
567 assert len(self.ARGUMENTS_GPR) == 4
568 assert len(self.ARGUMENTS_XMM) == 4
569 for i in range(4):
570 if self.win64_arg_gpr & (1 << i):
571 self.mc.MOV_sr(i * WORD, self.ARGUMENTS_GPR[i].value)
572 elif self.win64_arg_xmm & (1 << i):
573 self.mc.MOVSD_sx(i * WORD, self.ARGUMENTS_XMM[i].value)
574 self.mc.SUB_ri(esp.value, 4 * WORD)
575
576 def win64_restore_register_args(self):
577 self.mc.ADD_ri(esp.value, 4 * WORD)
578 for i in range(4):
579 if self.win64_arg_gpr & (1 << i):
580 self.mc.MOV_rs(self.ARGUMENTS_GPR[i].value, i * WORD)
581 elif self.win64_arg_xmm & (1 << i):
582 self.mc.MOVSD_xs(self.ARGUMENTS_XMM[i].value, i * WORD)
583
584 def prepare_arguments(self):
585 src_locs = []
586 dst_locs = []
587 xmm_src_locs = []
588 xmm_dst_locs = []
589 singlefloats = None
590
591 arglocs = self.arglocs
592 argtypes = self.argtypes
593
594 on_stack = 0
595 if WIN64:
596 on_stack = 4 # shadow parameters (space reserved by the caller)
597 for i in range(len(arglocs)):
598 loc = arglocs[i]
599 if loc.is_float():
600 tgt = self._unused_xmm()
601 if tgt is None:
602 tgt = RawEspLoc(on_stack * WORD, FLOAT)
603 on_stack += 1
604 xmm_src_locs.append(loc)
605 xmm_dst_locs.append(tgt)
606 elif i < len(argtypes) and argtypes[i] == 'S':
607 # Singlefloat argument
608 if singlefloats is None:
609 singlefloats = []
610 tgt = self._unused_xmm()
611 if tgt is None:
612 tgt = RawEspLoc(on_stack * WORD, INT)
613 on_stack += 1
614 singlefloats.append((loc, tgt))
615 else:
616 tgt = self._unused_gpr(hint=loc)
617 if tgt is None:
618 tgt = RawEspLoc(on_stack * WORD, INT)
619 on_stack += 1
620 src_locs.append(loc)
621 dst_locs.append(tgt)
622
623 if not self.fnloc_is_immediate:
624 self.fnloc = dst_locs[-1] # the last "argument" prepared above
625
626 if not we_are_translated(): # assert that we got the right stack depth
627 floats = 0
628 for i in range(len(arglocs)):
629 arg = arglocs[i]
630 if arg.is_float() or (i < len(argtypes) and argtypes[i]=='S'):
631 floats += 1
632 all_args = len(arglocs)
633 if not WIN64:
634 stack_depth = (max(all_args - floats - len(self.ARGUMENTS_GPR), 0)
635 + max(floats - len(self.ARGUMENTS_XMM), 0))
636 else:
637 stack_depth = max(all_args, 4)
638 assert stack_depth == on_stack
639
640 self.subtract_esp_aligned(on_stack - self.stack_max)
641
642 # Handle register arguments: first remap the xmm arguments
643 num_moves = remap_frame_layout(self.asm, xmm_src_locs, xmm_dst_locs,
644 X86_64_XMM_SCRATCH_REG)
645 # Load the singlefloat arguments from main regs or stack to xmm regs
646 if singlefloats is not None:
647 for src, dst in singlefloats:
648 if isinstance(dst, RawEspLoc):
649 # XXX too much special logic
650 if isinstance(src, RawEbpLoc):
651 num_moves += 2
652 self.mc.MOV32(X86_64_SCRATCH_REG, src)
653 self.mc.MOV32(dst, X86_64_SCRATCH_REG)
654 else:
655 num_moves += 1
656 self.mc.MOV32(dst, src)
657 continue
658 if isinstance(src, ImmedLoc):
659 num_moves += 1
660 self.mc.MOV(X86_64_SCRATCH_REG, src)
661 src = X86_64_SCRATCH_REG
662 num_moves += 1
663 self.mc.MOVD32(dst, src)
664 # Finally remap the arguments in the main regs
665 num_moves += remap_frame_layout(self.asm, src_locs, dst_locs, X86_64_SCRATCH_REG)
666 self.num_moves = num_moves
667
668
669 def emit_raw_call(self):
670 assert self.callconv == FFI_DEFAULT_ABI
671 self.mc.CALL(self.fnloc)
672
673 def load_result(self):
674 if self.restype == 'S':
675 # singlefloat return: use MOVD to load the target register
676 # from the lower 32 bits of XMM0
677 self.mc.MOVD32(self.resloc, xmm0)
678 else:
679 CallBuilderX86.load_result(self)
680
681 def save_result_value(self, save_edx):
682 # Temporarily save the result value into [ESP].
683 if self.ressize == 0: # void return
684 return
685 #
686 if self.restype == FLOAT: # and not 'S'
687 self.mc.MOVSD_sx(0, xmm0.value)
688 return
689 #
690 if self.restype == 'S':
691 # singlefloat return: use MOVD to store the lower 32 bits
692 # of XMM0 into [ESP]
693 self.mc.MOVD32_sx(0, xmm0.value)
694 else:
695 assert self.restype == INT
696 self.mc.MOV_sr(0, eax.value)
697
698 def restore_result_value(self, save_edx):
699 # Opposite of save_result_value()
700 if self.ressize == 0: # void return
701 return
702 #
703 if self.restype == FLOAT: # and not 'S'
704 self.mc.MOVSD_xs(xmm0.value, 0)
705 return
706 #
707 if self.restype == 'S':
708 self.mc.MOVD32_xs(xmm0.value, 0)
709 else:
710 assert self.restype == INT
711 self.mc.MOV_rs(eax.value, 0)
712
713
714 if IS_X86_32:
715 CallBuilder = CallBuilder32
716 if IS_X86_64:
717 CallBuilder = CallBuilder64