1 //===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the JIT interfaces for the X86 target.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "jit"
15 #include "X86JITInfo.h"
16 #include "X86Relocations.h"
17 #include "X86Subtarget.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/Function.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/Valgrind.h"
27 // Determine the platform we're running on
28 #if defined (__x86_64__) || defined (_M_AMD64) || defined (_M_X64)
30 #elif defined(__i386__) || defined(i386) || defined(_M_IX86)
34 void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
35 unsigned char *OldByte = (unsigned char *)Old;
36 *OldByte++ = 0xE9; // Emit JMP opcode.
37 unsigned *OldWord = (unsigned *)OldByte;
38 unsigned NewAddr = (intptr_t)New;
39 unsigned OldAddr = (intptr_t)OldWord;
40 *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
42 // X86 doesn't need to invalidate the processor cache, so just invalidate
43 // Valgrind's cache directly.
44 sys::ValgrindDiscardTranslations(Old, 5);
48 /// JITCompilerFunction - This contains the address of the JIT function used to
49 /// compile a function lazily.
50 static TargetJITInfo::JITCompilerFn JITCompilerFunction;
52 // Get the ASMPREFIX for the current host. This is often '_'.
53 #ifndef __USER_LABEL_PREFIX__
54 #define __USER_LABEL_PREFIX__
56 #define GETASMPREFIX2(X) #X
57 #define GETASMPREFIX(X) GETASMPREFIX2(X)
58 #define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__)
60 // For ELF targets, use a .size and .type directive, to let tools
61 // know the extent of functions defined in assembler.
63 # define SIZE(sym) ".size " #sym ", . - " #sym "\n"
64 # define TYPE_FUNCTION(sym) ".type " #sym ", @function\n"
67 # define TYPE_FUNCTION(sym)
70 // Provide a convenient way for disabling usage of CFI directives.
71 // This is needed for old/broken assemblers (for example, gas on
72 // Darwin is pretty old and doesn't support these directives)
73 #if defined(__APPLE__)
76 // FIXME: Disable this until we really want to use it. Also, we will
77 // need to add some workarounds for compilers, which support
78 // only subset of these directives.
82 // Provide a wrapper for X86CompilationCallback2 that saves non-traditional
83 // callee saved registers, for the fastcc calling convention.
85 #if defined(X86_64_JIT)
87 // No need to save EAX/EDX for X86-64.
88 void X86CompilationCallback(void);
92 ".globl " ASMPREFIX "X86CompilationCallback\n"
93 TYPE_FUNCTION(X86CompilationCallback)
94 ASMPREFIX "X86CompilationCallback:\n"
95 CFI(".cfi_startproc\n")
98 CFI(".cfi_def_cfa_offset 16\n")
99 CFI(".cfi_offset %rbp, -16\n")
102 CFI(".cfi_def_cfa_register %rbp\n")
103 // Save all int arg registers
105 CFI(".cfi_rel_offset %rdi, 0\n")
107 CFI(".cfi_rel_offset %rsi, 8\n")
109 CFI(".cfi_rel_offset %rdx, 16\n")
111 CFI(".cfi_rel_offset %rcx, 24\n")
113 CFI(".cfi_rel_offset %r8, 32\n")
115 CFI(".cfi_rel_offset %r9, 40\n")
116 // Align stack on 16-byte boundary. ESP might not be properly aligned
117 // (8 byte) if this is called from an indirect stub.
119 // Save all XMM arg registers
121 "movaps %xmm0, (%rsp)\n"
122 "movaps %xmm1, 16(%rsp)\n"
123 "movaps %xmm2, 32(%rsp)\n"
124 "movaps %xmm3, 48(%rsp)\n"
125 "movaps %xmm4, 64(%rsp)\n"
126 "movaps %xmm5, 80(%rsp)\n"
127 "movaps %xmm6, 96(%rsp)\n"
128 "movaps %xmm7, 112(%rsp)\n"
132 "movq %rbp, %rcx\n" // Pass prev frame and return address
133 "movq 8(%rbp), %rdx\n"
134 "call " ASMPREFIX "X86CompilationCallback2\n"
137 "movq %rbp, %rdi\n" // Pass prev frame and return address
138 "movq 8(%rbp), %rsi\n"
139 "call " ASMPREFIX "X86CompilationCallback2\n"
141 // Restore all XMM arg registers
142 "movaps 112(%rsp), %xmm7\n"
143 "movaps 96(%rsp), %xmm6\n"
144 "movaps 80(%rsp), %xmm5\n"
145 "movaps 64(%rsp), %xmm4\n"
146 "movaps 48(%rsp), %xmm3\n"
147 "movaps 32(%rsp), %xmm2\n"
148 "movaps 16(%rsp), %xmm1\n"
149 "movaps (%rsp), %xmm0\n"
152 CFI(".cfi_def_cfa_register %rsp\n")
153 // Restore all int arg registers
155 CFI(".cfi_adjust_cfa_offset 48\n")
157 CFI(".cfi_adjust_cfa_offset -8\n")
158 CFI(".cfi_restore %r9\n")
160 CFI(".cfi_adjust_cfa_offset -8\n")
161 CFI(".cfi_restore %r8\n")
163 CFI(".cfi_adjust_cfa_offset -8\n")
164 CFI(".cfi_restore %rcx\n")
166 CFI(".cfi_adjust_cfa_offset -8\n")
167 CFI(".cfi_restore %rdx\n")
169 CFI(".cfi_adjust_cfa_offset -8\n")
170 CFI(".cfi_restore %rsi\n")
172 CFI(".cfi_adjust_cfa_offset -8\n")
173 CFI(".cfi_restore %rdi\n")
176 CFI(".cfi_adjust_cfa_offset -8\n")
177 CFI(".cfi_restore %rbp\n")
179 CFI(".cfi_endproc\n")
180 SIZE(X86CompilationCallback)
183 // No inline assembler support on this platform. The routine is in external
185 void X86CompilationCallback();
188 #elif defined (X86_32_JIT)
190 void X86CompilationCallback(void);
194 ".globl " ASMPREFIX "X86CompilationCallback\n"
195 TYPE_FUNCTION(X86CompilationCallback)
196 ASMPREFIX "X86CompilationCallback:\n"
197 CFI(".cfi_startproc\n")
199 CFI(".cfi_def_cfa_offset 8\n")
200 CFI(".cfi_offset %ebp, -8\n")
201 "movl %esp, %ebp\n" // Standard prologue
202 CFI(".cfi_def_cfa_register %ebp\n")
204 CFI(".cfi_rel_offset %eax, 0\n")
205 "pushl %edx\n" // Save EAX/EDX/ECX
206 CFI(".cfi_rel_offset %edx, 4\n")
208 CFI(".cfi_rel_offset %ecx, 8\n")
209 # if defined(__APPLE__)
210 "andl $-16, %esp\n" // Align ESP on 16-byte boundary
213 "movl 4(%ebp), %eax\n" // Pass prev frame and return address
214 "movl %eax, 4(%esp)\n"
215 "movl %ebp, (%esp)\n"
216 "call " ASMPREFIX "X86CompilationCallback2\n"
217 "movl %ebp, %esp\n" // Restore ESP
218 CFI(".cfi_def_cfa_register %esp\n")
220 CFI(".cfi_adjust_cfa_offset 12\n")
222 CFI(".cfi_adjust_cfa_offset -4\n")
223 CFI(".cfi_restore %ecx\n")
225 CFI(".cfi_adjust_cfa_offset -4\n")
226 CFI(".cfi_restore %edx\n")
228 CFI(".cfi_adjust_cfa_offset -4\n")
229 CFI(".cfi_restore %eax\n")
231 CFI(".cfi_adjust_cfa_offset -4\n")
232 CFI(".cfi_restore %ebp\n")
234 CFI(".cfi_endproc\n")
235 SIZE(X86CompilationCallback)
238 // Same as X86CompilationCallback but also saves XMM argument registers.
239 void X86CompilationCallback_SSE(void);
243 ".globl " ASMPREFIX "X86CompilationCallback_SSE\n"
244 TYPE_FUNCTION(X86CompilationCallback_SSE)
245 ASMPREFIX "X86CompilationCallback_SSE:\n"
246 CFI(".cfi_startproc\n")
248 CFI(".cfi_def_cfa_offset 8\n")
249 CFI(".cfi_offset %ebp, -8\n")
250 "movl %esp, %ebp\n" // Standard prologue
251 CFI(".cfi_def_cfa_register %ebp\n")
253 CFI(".cfi_rel_offset %eax, 0\n")
254 "pushl %edx\n" // Save EAX/EDX/ECX
255 CFI(".cfi_rel_offset %edx, 4\n")
257 CFI(".cfi_rel_offset %ecx, 8\n")
258 "andl $-16, %esp\n" // Align ESP on 16-byte boundary
259 // Save all XMM arg registers
261 // FIXME: provide frame move information for xmm registers.
262 // This can be tricky, because CFA register is ebp (unaligned)
263 // and we need to produce offsets relative to it.
264 "movaps %xmm0, (%esp)\n"
265 "movaps %xmm1, 16(%esp)\n"
266 "movaps %xmm2, 32(%esp)\n"
267 "movaps %xmm3, 48(%esp)\n"
269 "movl 4(%ebp), %eax\n" // Pass prev frame and return address
270 "movl %eax, 4(%esp)\n"
271 "movl %ebp, (%esp)\n"
272 "call " ASMPREFIX "X86CompilationCallback2\n"
274 "movaps 48(%esp), %xmm3\n"
275 CFI(".cfi_restore %xmm3\n")
276 "movaps 32(%esp), %xmm2\n"
277 CFI(".cfi_restore %xmm2\n")
278 "movaps 16(%esp), %xmm1\n"
279 CFI(".cfi_restore %xmm1\n")
280 "movaps (%esp), %xmm0\n"
281 CFI(".cfi_restore %xmm0\n")
282 "movl %ebp, %esp\n" // Restore ESP
283 CFI(".cfi_def_cfa_register esp\n")
285 CFI(".cfi_adjust_cfa_offset 12\n")
287 CFI(".cfi_adjust_cfa_offset -4\n")
288 CFI(".cfi_restore %ecx\n")
290 CFI(".cfi_adjust_cfa_offset -4\n")
291 CFI(".cfi_restore %edx\n")
293 CFI(".cfi_adjust_cfa_offset -4\n")
294 CFI(".cfi_restore %eax\n")
296 CFI(".cfi_adjust_cfa_offset -4\n")
297 CFI(".cfi_restore %ebp\n")
299 CFI(".cfi_endproc\n")
300 SIZE(X86CompilationCallback_SSE)
303 // the following function is called only from this translation unit,
304 // unless we are under 64bit Windows with MSC, where there is
305 // no support for inline assembly
306 static void X86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr);
308 _declspec(naked) void X86CompilationCallback(void) {
317 mov eax, dword ptr [ebp+4]
318 mov dword ptr [esp+4], eax
319 mov dword ptr [esp], ebp
320 call X86CompilationCallback2
333 #else // Not an i386 host
334 void X86CompilationCallback() {
335 llvm_unreachable("Cannot call X86CompilationCallback() on a non-x86 arch!");
340 /// X86CompilationCallback2 - This is the target-specific function invoked by the
341 /// function stub when we did not know the real target of a call. This function
342 /// must locate the start of the stub or call site and pass it into the JIT
343 /// compiler function.
345 #if !(defined (X86_64_JIT) && defined(_MSC_VER))
346 // the following function is called only from this translation unit,
347 // unless we are under 64bit Windows with MSC, where there is
348 // no support for inline assembly
351 void LLVM_ATTRIBUTE_USED
352 X86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr) {
353 intptr_t *RetAddrLoc = &StackPtr[1];
354 assert(*RetAddrLoc == RetAddr &&
355 "Could not find return address on the stack!");
357 // It's a stub if there is an interrupt marker after the call.
358 bool isStub = ((unsigned char*)RetAddr)[0] == 0xCE;
360 // The call instruction should have pushed the return value onto the stack...
361 #if defined (X86_64_JIT)
362 RetAddr--; // Backtrack to the reference itself...
364 RetAddr -= 4; // Backtrack to the reference itself...
368 DEBUG(dbgs() << "In callback! Addr=" << (void*)RetAddr
369 << " ESP=" << (void*)StackPtr
370 << ": Resolving call to function: "
371 << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
374 // Sanity check to make sure this really is a call instruction.
375 #if defined (X86_64_JIT)
376 assert(((unsigned char*)RetAddr)[-2] == 0x41 &&"Not a call instr!");
377 assert(((unsigned char*)RetAddr)[-1] == 0xFF &&"Not a call instr!");
379 assert(((unsigned char*)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
382 intptr_t NewVal = (intptr_t)JITCompilerFunction((void*)RetAddr);
384 // Rewrite the call target... so that we don't end up here every time we
386 #if defined (X86_64_JIT)
388 "X86-64 doesn't support rewriting non-stub lazy compilation calls:"
389 " the call instruction varies too much.");
391 *(intptr_t *)RetAddr = (intptr_t)(NewVal-RetAddr-4);
395 // If this is a stub, rewrite the call into an unconditional branch
396 // instruction so that two return addresses are not pushed onto the stack
397 // when the requested function finally gets called. This also makes the
398 // 0xCE byte (interrupt) dead, so the marker doesn't effect anything.
399 #if defined (X86_64_JIT)
400 // If the target address is within 32-bit range of the stub, use a
401 // PC-relative branch instead of loading the actual address. (This is
402 // considerably shorter than the 64-bit immediate load already there.)
403 // We assume here intptr_t is 64 bits.
404 intptr_t diff = NewVal-RetAddr+7;
405 if (diff >= -2147483648LL && diff <= 2147483647LL) {
406 *(unsigned char*)(RetAddr-0xc) = 0xE9;
407 *(intptr_t *)(RetAddr-0xb) = diff & 0xffffffff;
409 *(intptr_t *)(RetAddr - 0xa) = NewVal;
410 ((unsigned char*)RetAddr)[0] = (2 | (4 << 3) | (3 << 6));
412 sys::ValgrindDiscardTranslations((void*)(RetAddr-0xc), 0xd);
414 ((unsigned char*)RetAddr)[-1] = 0xE9;
415 sys::ValgrindDiscardTranslations((void*)(RetAddr-1), 5);
419 // Change the return address to reexecute the call instruction...
420 #if defined (X86_64_JIT)
428 TargetJITInfo::LazyResolverFn
429 X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
430 TsanIgnoreWritesBegin();
431 JITCompilerFunction = F;
432 TsanIgnoreWritesEnd();
434 #if defined (X86_32_JIT) && !defined (_MSC_VER)
435 if (Subtarget->hasSSE1())
436 return X86CompilationCallback_SSE;
439 return X86CompilationCallback;
442 X86JITInfo::X86JITInfo(X86TargetMachine &tm) : TM(tm) {
443 Subtarget = &TM.getSubtarget<X86Subtarget>();
448 void *X86JITInfo::emitGlobalValueIndirectSym(const GlobalValue* GV, void *ptr,
449 JITCodeEmitter &JCE) {
450 #if defined (X86_64_JIT)
451 const unsigned Alignment = 8;
453 uint8_t *Cur = Buffer;
454 MachineCodeEmitter::emitWordLEInto(Cur, (unsigned)(intptr_t)ptr);
455 MachineCodeEmitter::emitWordLEInto(Cur, (unsigned)(((intptr_t)ptr) >> 32));
457 const unsigned Alignment = 4;
459 uint8_t *Cur = Buffer;
460 MachineCodeEmitter::emitWordLEInto(Cur, (intptr_t)ptr);
462 return JCE.allocIndirectGV(GV, Buffer, sizeof(Buffer), Alignment);
465 TargetJITInfo::StubLayout X86JITInfo::getStubLayout() {
466 // The 64-bit stub contains:
467 // movabs r10 <- 8-byte-target-address # 10 bytes
468 // call|jmp *r10 # 3 bytes
469 // The 32-bit stub contains a 5-byte call|jmp.
470 // If the stub is a call to the compilation callback, an extra byte is added
471 // to mark it as a stub.
472 StubLayout Result = {14, 4};
476 void *X86JITInfo::emitFunctionStub(const Function* F, void *Target,
477 JITCodeEmitter &JCE) {
478 // Note, we cast to intptr_t here to silence a -pedantic warning that
479 // complains about casting a function pointer to a normal pointer.
480 #if defined (X86_32_JIT) && !defined (_MSC_VER)
481 bool NotCC = (Target != (void*)(intptr_t)X86CompilationCallback &&
482 Target != (void*)(intptr_t)X86CompilationCallback_SSE);
484 bool NotCC = Target != (void*)(intptr_t)X86CompilationCallback;
486 JCE.emitAlignment(4);
487 void *Result = (void*)JCE.getCurrentPCValue();
489 #if defined (X86_64_JIT)
490 JCE.emitByte(0x49); // REX prefix
491 JCE.emitByte(0xB8+2); // movabsq r10
492 JCE.emitWordLE((unsigned)(intptr_t)Target);
493 JCE.emitWordLE((unsigned)(((intptr_t)Target) >> 32));
494 JCE.emitByte(0x41); // REX prefix
495 JCE.emitByte(0xFF); // jmpq *r10
496 JCE.emitByte(2 | (4 << 3) | (3 << 6));
499 JCE.emitWordLE((intptr_t)Target-JCE.getCurrentPCValue()-4);
504 #if defined (X86_64_JIT)
505 JCE.emitByte(0x49); // REX prefix
506 JCE.emitByte(0xB8+2); // movabsq r10
507 JCE.emitWordLE((unsigned)(intptr_t)Target);
508 JCE.emitWordLE((unsigned)(((intptr_t)Target) >> 32));
509 JCE.emitByte(0x41); // REX prefix
510 JCE.emitByte(0xFF); // callq *r10
511 JCE.emitByte(2 | (2 << 3) | (3 << 6));
513 JCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
515 JCE.emitWordLE((intptr_t)Target-JCE.getCurrentPCValue()-4);
518 // This used to use 0xCD, but that value is used by JITMemoryManager to
519 // initialize the buffer with garbage, which means it may follow a
520 // noreturn function call, confusing X86CompilationCallback2. PR 4929.
521 JCE.emitByte(0xCE); // Interrupt - Just a marker identifying the stub!
525 /// getPICJumpTableEntry - Returns the value of the jumptable entry for the
526 /// specific basic block.
527 uintptr_t X86JITInfo::getPICJumpTableEntry(uintptr_t BB, uintptr_t Entry) {
528 #if defined(X86_64_JIT)
535 /// relocate - Before the JIT can run a block of code that has been emitted,
536 /// it must rewrite the code to contain the actual addresses of any
537 /// referenced global symbols.
538 void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
539 unsigned NumRelocs, unsigned char* GOTBase) {
540 for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
541 void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
542 intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
543 switch ((X86::RelocationType)MR->getRelocationType()) {
544 case X86::reloc_pcrel_word: {
545 // PC relative relocation, add the relocated value to the value already in
546 // memory, after we adjust it for where the PC is.
547 ResultPtr = ResultPtr -(intptr_t)RelocPos - 4 - MR->getConstantVal();
548 *((unsigned*)RelocPos) += (unsigned)ResultPtr;
551 case X86::reloc_picrel_word: {
552 // PIC base relative relocation, add the relocated value to the value
553 // already in memory, after we adjust it for where the PIC base is.
554 ResultPtr = ResultPtr - ((intptr_t)Function + MR->getConstantVal());
555 *((unsigned*)RelocPos) += (unsigned)ResultPtr;
558 case X86::reloc_absolute_word:
559 case X86::reloc_absolute_word_sext:
560 // Absolute relocation, just add the relocated value to the value already
562 *((unsigned*)RelocPos) += (unsigned)ResultPtr;
564 case X86::reloc_absolute_dword:
565 *((intptr_t*)RelocPos) += ResultPtr;
571 char* X86JITInfo::allocateThreadLocalMemory(size_t size) {
572 #if defined(X86_32_JIT) && !defined(__APPLE__) && !defined(_MSC_VER)
576 llvm_unreachable("Cannot allocate thread local storage on this arch!");