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 #include "X86JITInfo.h"
15 #include "X86Relocations.h"
16 #include "X86Subtarget.h"
17 #include "X86TargetMachine.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/Valgrind.h"
27 #define DEBUG_TYPE "jit"
29 // Determine the platform we're running on
30 #if defined (__x86_64__) || defined (_M_AMD64) || defined (_M_X64)
32 #elif defined(__i386__) || defined(i386) || defined(_M_IX86)
36 // x86 is little-endian, and we can do unaligned memory accesses.
37 template<typename value_type>
38 static value_type read_x86(const void *memory) {
39 return support::endian::read<value_type, support::little, 1>(memory);
42 template<typename value_type>
43 static void write_x86(void *memory, value_type value) {
44 support::endian::write<value_type, support::little, 1>(memory, value);
47 void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
48 unsigned char *OldPtr = static_cast<unsigned char*>(Old);
49 write_x86<unsigned char>(OldPtr++, 0xE9); // Emit JMP opcode.
50 unsigned NewAddr = (intptr_t)New;
51 unsigned OldAddr = (intptr_t)OldPtr;
53 OldPtr, NewAddr - OldAddr - 4); // Emit PC-relative addr of New code.
55 // X86 doesn't need to invalidate the processor cache, so just invalidate
56 // Valgrind's cache directly.
57 sys::ValgrindDiscardTranslations(Old, 5);
61 /// JITCompilerFunction - This contains the address of the JIT function used to
62 /// compile a function lazily.
63 static TargetJITInfo::JITCompilerFn JITCompilerFunction;
65 // Get the ASMPREFIX for the current host. This is often '_'.
66 #ifndef __USER_LABEL_PREFIX__
67 #define __USER_LABEL_PREFIX__
69 #define GETASMPREFIX2(X) #X
70 #define GETASMPREFIX(X) GETASMPREFIX2(X)
71 #define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__)
73 // For ELF targets, use a .size and .type directive, to let tools
74 // know the extent of functions defined in assembler.
76 # define SIZE(sym) ".size " #sym ", . - " #sym "\n"
77 # define TYPE_FUNCTION(sym) ".type " #sym ", @function\n"
80 # define TYPE_FUNCTION(sym)
83 // Provide a convenient way for disabling usage of CFI directives.
84 // This is needed for old/broken assemblers (for example, gas on
85 // Darwin is pretty old and doesn't support these directives)
86 #if defined(__APPLE__)
89 // FIXME: Disable this until we really want to use it. Also, we will
90 // need to add some workarounds for compilers, which support
91 // only subset of these directives.
95 // Provide a wrapper for LLVMX86CompilationCallback2 that saves non-traditional
96 // callee saved registers, for the fastcc calling convention.
98 #if defined(X86_64_JIT)
100 // No need to save EAX/EDX for X86-64.
101 void X86CompilationCallback(void);
105 ".globl " ASMPREFIX "X86CompilationCallback\n"
106 TYPE_FUNCTION(X86CompilationCallback)
107 ASMPREFIX "X86CompilationCallback:\n"
108 CFI(".cfi_startproc\n")
111 CFI(".cfi_def_cfa_offset 16\n")
112 CFI(".cfi_offset %rbp, -16\n")
115 CFI(".cfi_def_cfa_register %rbp\n")
116 // Save all int arg registers
118 CFI(".cfi_rel_offset %rdi, 0\n")
120 CFI(".cfi_rel_offset %rsi, 8\n")
122 CFI(".cfi_rel_offset %rdx, 16\n")
124 CFI(".cfi_rel_offset %rcx, 24\n")
126 CFI(".cfi_rel_offset %r8, 32\n")
128 CFI(".cfi_rel_offset %r9, 40\n")
129 // Align stack on 16-byte boundary. ESP might not be properly aligned
130 // (8 byte) if this is called from an indirect stub.
132 // Save all XMM arg registers
134 "movaps %xmm0, (%rsp)\n"
135 "movaps %xmm1, 16(%rsp)\n"
136 "movaps %xmm2, 32(%rsp)\n"
137 "movaps %xmm3, 48(%rsp)\n"
138 "movaps %xmm4, 64(%rsp)\n"
139 "movaps %xmm5, 80(%rsp)\n"
140 "movaps %xmm6, 96(%rsp)\n"
141 "movaps %xmm7, 112(%rsp)\n"
143 #if defined(_WIN64) || defined(__CYGWIN__)
145 "movq %rbp, %rcx\n" // Pass prev frame and return address
146 "movq 8(%rbp), %rdx\n"
147 "call " ASMPREFIX "LLVMX86CompilationCallback2\n"
150 "movq %rbp, %rdi\n" // Pass prev frame and return address
151 "movq 8(%rbp), %rsi\n"
152 "call " ASMPREFIX "LLVMX86CompilationCallback2\n"
154 // Restore all XMM arg registers
155 "movaps 112(%rsp), %xmm7\n"
156 "movaps 96(%rsp), %xmm6\n"
157 "movaps 80(%rsp), %xmm5\n"
158 "movaps 64(%rsp), %xmm4\n"
159 "movaps 48(%rsp), %xmm3\n"
160 "movaps 32(%rsp), %xmm2\n"
161 "movaps 16(%rsp), %xmm1\n"
162 "movaps (%rsp), %xmm0\n"
165 CFI(".cfi_def_cfa_register %rsp\n")
166 // Restore all int arg registers
168 CFI(".cfi_adjust_cfa_offset 48\n")
170 CFI(".cfi_adjust_cfa_offset -8\n")
171 CFI(".cfi_restore %r9\n")
173 CFI(".cfi_adjust_cfa_offset -8\n")
174 CFI(".cfi_restore %r8\n")
176 CFI(".cfi_adjust_cfa_offset -8\n")
177 CFI(".cfi_restore %rcx\n")
179 CFI(".cfi_adjust_cfa_offset -8\n")
180 CFI(".cfi_restore %rdx\n")
182 CFI(".cfi_adjust_cfa_offset -8\n")
183 CFI(".cfi_restore %rsi\n")
185 CFI(".cfi_adjust_cfa_offset -8\n")
186 CFI(".cfi_restore %rdi\n")
189 CFI(".cfi_adjust_cfa_offset -8\n")
190 CFI(".cfi_restore %rbp\n")
192 CFI(".cfi_endproc\n")
193 SIZE(X86CompilationCallback)
196 // No inline assembler support on this platform. The routine is in external
198 void X86CompilationCallback();
201 #elif defined (X86_32_JIT)
203 void X86CompilationCallback(void);
207 ".globl " ASMPREFIX "X86CompilationCallback\n"
208 TYPE_FUNCTION(X86CompilationCallback)
209 ASMPREFIX "X86CompilationCallback:\n"
210 CFI(".cfi_startproc\n")
212 CFI(".cfi_def_cfa_offset 8\n")
213 CFI(".cfi_offset %ebp, -8\n")
214 "movl %esp, %ebp\n" // Standard prologue
215 CFI(".cfi_def_cfa_register %ebp\n")
217 CFI(".cfi_rel_offset %eax, 0\n")
218 "pushl %edx\n" // Save EAX/EDX/ECX
219 CFI(".cfi_rel_offset %edx, 4\n")
221 CFI(".cfi_rel_offset %ecx, 8\n")
222 # if defined(__APPLE__)
223 "andl $-16, %esp\n" // Align ESP on 16-byte boundary
226 "movl 4(%ebp), %eax\n" // Pass prev frame and return address
227 "movl %eax, 4(%esp)\n"
228 "movl %ebp, (%esp)\n"
229 "call " ASMPREFIX "LLVMX86CompilationCallback2\n"
230 "movl %ebp, %esp\n" // Restore ESP
231 CFI(".cfi_def_cfa_register %esp\n")
233 CFI(".cfi_adjust_cfa_offset 12\n")
235 CFI(".cfi_adjust_cfa_offset -4\n")
236 CFI(".cfi_restore %ecx\n")
238 CFI(".cfi_adjust_cfa_offset -4\n")
239 CFI(".cfi_restore %edx\n")
241 CFI(".cfi_adjust_cfa_offset -4\n")
242 CFI(".cfi_restore %eax\n")
244 CFI(".cfi_adjust_cfa_offset -4\n")
245 CFI(".cfi_restore %ebp\n")
247 CFI(".cfi_endproc\n")
248 SIZE(X86CompilationCallback)
251 // Same as X86CompilationCallback but also saves XMM argument registers.
252 void X86CompilationCallback_SSE(void);
256 ".globl " ASMPREFIX "X86CompilationCallback_SSE\n"
257 TYPE_FUNCTION(X86CompilationCallback_SSE)
258 ASMPREFIX "X86CompilationCallback_SSE:\n"
259 CFI(".cfi_startproc\n")
261 CFI(".cfi_def_cfa_offset 8\n")
262 CFI(".cfi_offset %ebp, -8\n")
263 "movl %esp, %ebp\n" // Standard prologue
264 CFI(".cfi_def_cfa_register %ebp\n")
266 CFI(".cfi_rel_offset %eax, 0\n")
267 "pushl %edx\n" // Save EAX/EDX/ECX
268 CFI(".cfi_rel_offset %edx, 4\n")
270 CFI(".cfi_rel_offset %ecx, 8\n")
271 "andl $-16, %esp\n" // Align ESP on 16-byte boundary
272 // Save all XMM arg registers
274 // FIXME: provide frame move information for xmm registers.
275 // This can be tricky, because CFA register is ebp (unaligned)
276 // and we need to produce offsets relative to it.
277 "movaps %xmm0, (%esp)\n"
278 "movaps %xmm1, 16(%esp)\n"
279 "movaps %xmm2, 32(%esp)\n"
280 "movaps %xmm3, 48(%esp)\n"
282 "movl 4(%ebp), %eax\n" // Pass prev frame and return address
283 "movl %eax, 4(%esp)\n"
284 "movl %ebp, (%esp)\n"
285 "call " ASMPREFIX "LLVMX86CompilationCallback2\n"
287 "movaps 48(%esp), %xmm3\n"
288 CFI(".cfi_restore %xmm3\n")
289 "movaps 32(%esp), %xmm2\n"
290 CFI(".cfi_restore %xmm2\n")
291 "movaps 16(%esp), %xmm1\n"
292 CFI(".cfi_restore %xmm1\n")
293 "movaps (%esp), %xmm0\n"
294 CFI(".cfi_restore %xmm0\n")
295 "movl %ebp, %esp\n" // Restore ESP
296 CFI(".cfi_def_cfa_register esp\n")
298 CFI(".cfi_adjust_cfa_offset 12\n")
300 CFI(".cfi_adjust_cfa_offset -4\n")
301 CFI(".cfi_restore %ecx\n")
303 CFI(".cfi_adjust_cfa_offset -4\n")
304 CFI(".cfi_restore %edx\n")
306 CFI(".cfi_adjust_cfa_offset -4\n")
307 CFI(".cfi_restore %eax\n")
309 CFI(".cfi_adjust_cfa_offset -4\n")
310 CFI(".cfi_restore %ebp\n")
312 CFI(".cfi_endproc\n")
313 SIZE(X86CompilationCallback_SSE)
316 void LLVMX86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr);
318 _declspec(naked) void X86CompilationCallback(void) {
327 mov eax, dword ptr [ebp+4]
328 mov dword ptr [esp+4], eax
329 mov dword ptr [esp], ebp
330 call LLVMX86CompilationCallback2
343 #else // Not an i386 host
344 void X86CompilationCallback() {
345 llvm_unreachable("Cannot call X86CompilationCallback() on a non-x86 arch!");
350 /// This is the target-specific function invoked by the
351 /// function stub when we did not know the real target of a call. This function
352 /// must locate the start of the stub or call site and pass it into the JIT
353 /// compiler function.
355 LLVM_ATTRIBUTE_USED // Referenced from inline asm.
356 LLVM_LIBRARY_VISIBILITY void LLVMX86CompilationCallback2(intptr_t *StackPtr,
358 intptr_t *RetAddrLoc = &StackPtr[1];
359 // We are reading raw stack data here. Tell MemorySanitizer that it is
360 // sufficiently initialized.
361 __msan_unpoison(RetAddrLoc, sizeof(*RetAddrLoc));
362 assert(*RetAddrLoc == RetAddr &&
363 "Could not find return address on the stack!");
365 // It's a stub if there is an interrupt marker after the call.
366 unsigned char *RetAddrPtr = (unsigned char*)RetAddr;
367 bool isStub = read_x86<unsigned char>(RetAddrPtr) == 0xCE;
369 // The call instruction should have pushed the return value onto the stack...
370 #if defined (X86_64_JIT)
371 RetAddrPtr--; // Backtrack to the reference itself...
373 RetAddrPtr -= 4; // Backtrack to the reference itself...
377 DEBUG(dbgs() << "In callback! Addr=" << RetAddrPtr
378 << " ESP=" << (void*)StackPtr
379 << ": Resolving call to function: "
380 << TheVM->getFunctionReferencedName(RetAddrPtr) << "\n");
383 // Sanity check to make sure this really is a call instruction.
384 #if defined (X86_64_JIT)
385 assert(read_x86<unsigned char>(RetAddrPtr - 2) == 0x41 &&
386 "Not a call instr!");
387 assert(read_x86<unsigned char>(RetAddrPtr - 1) == 0xFF &&
388 "Not a call instr!");
390 assert(read_x86<unsigned char>(RetAddrPtr - 1) == 0xE8 &&
391 "Not a call instr!");
394 intptr_t NewVal = (intptr_t)JITCompilerFunction(RetAddrPtr);
396 // Rewrite the call target... so that we don't end up here every time we
398 #if defined (X86_64_JIT)
400 "X86-64 doesn't support rewriting non-stub lazy compilation calls:"
401 " the call instruction varies too much.");
403 write_x86<intptr_t>(RetAddrPtr, NewVal - (intptr_t)RetAddrPtr - 4);
407 // If this is a stub, rewrite the call into an unconditional branch
408 // instruction so that two return addresses are not pushed onto the stack
409 // when the requested function finally gets called. This also makes the
410 // 0xCE byte (interrupt) dead, so the marker doesn't effect anything.
411 #if defined (X86_64_JIT)
412 // If the target address is within 32-bit range of the stub, use a
413 // PC-relative branch instead of loading the actual address. (This is
414 // considerably shorter than the 64-bit immediate load already there.)
415 // We assume here intptr_t is 64 bits.
416 intptr_t diff = NewVal - (intptr_t)RetAddrPtr + 7;
417 if (diff >= -2147483648LL && diff <= 2147483647LL) {
418 write_x86<unsigned char>(RetAddrPtr - 0xC, 0xE9);
419 write_x86<intptr_t>(RetAddrPtr - 0xB, diff & 0xffffffff);
421 write_x86<intptr_t>(RetAddrPtr - 0xA, NewVal);
422 write_x86<unsigned char>(RetAddrPtr, (2 | (4 << 3) | (3 << 6)));
424 sys::ValgrindDiscardTranslations(RetAddrPtr - 0xC, 0xd);
426 write_x86<unsigned char>(RetAddrPtr - 1, 0xE9);
427 sys::ValgrindDiscardTranslations(RetAddrPtr - 1, 5);
431 // Change the return address to reexecute the call instruction...
432 #if defined (X86_64_JIT)
440 TargetJITInfo::LazyResolverFn
441 X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
442 TsanIgnoreWritesBegin();
443 JITCompilerFunction = F;
444 TsanIgnoreWritesEnd();
446 #if defined (X86_32_JIT) && !defined (_MSC_VER)
448 // SSE Callback should be called for SSE-enabled LLVM.
449 return X86CompilationCallback_SSE;
452 return X86CompilationCallback_SSE;
456 return X86CompilationCallback;
459 X86JITInfo::X86JITInfo(bool UseSSE) {
465 void *X86JITInfo::emitGlobalValueIndirectSym(const GlobalValue* GV, void *ptr,
466 JITCodeEmitter &JCE) {
467 #if defined (X86_64_JIT)
468 const unsigned Alignment = 8;
470 uint8_t *Cur = Buffer;
471 MachineCodeEmitter::emitWordLEInto(Cur, (unsigned)(intptr_t)ptr);
472 MachineCodeEmitter::emitWordLEInto(Cur, (unsigned)(((intptr_t)ptr) >> 32));
474 const unsigned Alignment = 4;
476 uint8_t *Cur = Buffer;
477 MachineCodeEmitter::emitWordLEInto(Cur, (intptr_t)ptr);
479 return JCE.allocIndirectGV(GV, Buffer, sizeof(Buffer), Alignment);
482 TargetJITInfo::StubLayout X86JITInfo::getStubLayout() {
483 // The 64-bit stub contains:
484 // movabs r10 <- 8-byte-target-address # 10 bytes
485 // call|jmp *r10 # 3 bytes
486 // The 32-bit stub contains a 5-byte call|jmp.
487 // If the stub is a call to the compilation callback, an extra byte is added
488 // to mark it as a stub.
489 StubLayout Result = {14, 4};
493 void *X86JITInfo::emitFunctionStub(const Function* F, void *Target,
494 JITCodeEmitter &JCE) {
495 // Note, we cast to intptr_t here to silence a -pedantic warning that
496 // complains about casting a function pointer to a normal pointer.
497 #if defined (X86_32_JIT) && !defined (_MSC_VER)
498 bool NotCC = (Target != (void*)(intptr_t)X86CompilationCallback &&
499 Target != (void*)(intptr_t)X86CompilationCallback_SSE);
501 bool NotCC = Target != (void*)(intptr_t)X86CompilationCallback;
503 JCE.emitAlignment(4);
504 void *Result = (void*)JCE.getCurrentPCValue();
506 #if defined (X86_64_JIT)
507 JCE.emitByte(0x49); // REX prefix
508 JCE.emitByte(0xB8+2); // movabsq r10
509 JCE.emitWordLE((unsigned)(intptr_t)Target);
510 JCE.emitWordLE((unsigned)(((intptr_t)Target) >> 32));
511 JCE.emitByte(0x41); // REX prefix
512 JCE.emitByte(0xFF); // jmpq *r10
513 JCE.emitByte(2 | (4 << 3) | (3 << 6));
516 JCE.emitWordLE((intptr_t)Target-JCE.getCurrentPCValue()-4);
521 #if defined (X86_64_JIT)
522 JCE.emitByte(0x49); // REX prefix
523 JCE.emitByte(0xB8+2); // movabsq r10
524 JCE.emitWordLE((unsigned)(intptr_t)Target);
525 JCE.emitWordLE((unsigned)(((intptr_t)Target) >> 32));
526 JCE.emitByte(0x41); // REX prefix
527 JCE.emitByte(0xFF); // callq *r10
528 JCE.emitByte(2 | (2 << 3) | (3 << 6));
530 JCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
532 JCE.emitWordLE((intptr_t)Target-JCE.getCurrentPCValue()-4);
535 // This used to use 0xCD, but that value is used by JITMemoryManager to
536 // initialize the buffer with garbage, which means it may follow a
537 // noreturn function call, confusing LLVMX86CompilationCallback2. PR 4929.
538 JCE.emitByte(0xCE); // Interrupt - Just a marker identifying the stub!
542 /// getPICJumpTableEntry - Returns the value of the jumptable entry for the
543 /// specific basic block.
544 uintptr_t X86JITInfo::getPICJumpTableEntry(uintptr_t BB, uintptr_t Entry) {
545 #if defined(X86_64_JIT)
552 template<typename T> static void addUnaligned(void *Pos, T Delta) {
554 std::memcpy(reinterpret_cast<char*>(&Value), reinterpret_cast<char*>(Pos),
557 std::memcpy(reinterpret_cast<char*>(Pos), reinterpret_cast<char*>(&Value),
561 /// relocate - Before the JIT can run a block of code that has been emitted,
562 /// it must rewrite the code to contain the actual addresses of any
563 /// referenced global symbols.
564 void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
565 unsigned NumRelocs, unsigned char* GOTBase) {
566 for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
567 void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
568 intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
569 switch ((X86::RelocationType)MR->getRelocationType()) {
570 case X86::reloc_pcrel_word: {
571 // PC relative relocation, add the relocated value to the value already in
572 // memory, after we adjust it for where the PC is.
573 ResultPtr = ResultPtr -(intptr_t)RelocPos - 4 - MR->getConstantVal();
574 addUnaligned<unsigned>(RelocPos, ResultPtr);
577 case X86::reloc_picrel_word: {
578 // PIC base relative relocation, add the relocated value to the value
579 // already in memory, after we adjust it for where the PIC base is.
580 ResultPtr = ResultPtr - ((intptr_t)Function + MR->getConstantVal());
581 addUnaligned<unsigned>(RelocPos, ResultPtr);
584 case X86::reloc_absolute_word:
585 case X86::reloc_absolute_word_sext:
586 // Absolute relocation, just add the relocated value to the value already
588 addUnaligned<unsigned>(RelocPos, ResultPtr);
590 case X86::reloc_absolute_dword:
591 addUnaligned<intptr_t>(RelocPos, ResultPtr);
597 char* X86JITInfo::allocateThreadLocalMemory(size_t size) {
598 #if defined(X86_32_JIT) && !defined(__APPLE__) && !defined(_MSC_VER)
602 llvm_unreachable("Cannot allocate thread local storage on this arch!");