Removed even more std::cerr and #include <iostream> things.
[oota-llvm.git] / lib / Target / X86 / X86JITInfo.cpp
1 //===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the JIT interfaces for the X86 target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "jit"
15 #include "X86JITInfo.h"
16 #include "X86Relocations.h"
17 #include "X86Subtarget.h"
18 #include "llvm/CodeGen/MachineCodeEmitter.h"
19 #include "llvm/Config/alloca.h"
20 #include <cstdlib>
21 using namespace llvm;
22
23 #ifdef _MSC_VER
24   extern "C" void *_AddressOfReturnAddress(void);
25   #pragma intrinsic(_AddressOfReturnAddress)
26 #endif
27
28 void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
29   unsigned char *OldByte = (unsigned char *)Old;
30   *OldByte++ = 0xE9;                // Emit JMP opcode.
31   unsigned *OldWord = (unsigned *)OldByte;
32   unsigned NewAddr = (intptr_t)New;
33   unsigned OldAddr = (intptr_t)OldWord;
34   *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
35 }
36
37
38 /// JITCompilerFunction - This contains the address of the JIT function used to
39 /// compile a function lazily.
40 static TargetJITInfo::JITCompilerFn JITCompilerFunction;
41
42 // Get the ASMPREFIX for the current host.  This is often '_'.
43 #ifndef __USER_LABEL_PREFIX__
44 #define __USER_LABEL_PREFIX__
45 #endif
46 #define GETASMPREFIX2(X) #X
47 #define GETASMPREFIX(X) GETASMPREFIX2(X)
48 #define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__)
49
50 // Provide a wrapper for X86CompilationCallback2 that saves non-traditional
51 // callee saved registers, for the fastcc calling convention.
52 extern "C" {
53 #if defined(__x86_64__)
54   // No need to save EAX/EDX for X86-64.
55   void X86CompilationCallback(void);
56   asm(
57     ".text\n"
58     ".align 8\n"
59     ".globl " ASMPREFIX "X86CompilationCallback\n"
60   ASMPREFIX "X86CompilationCallback:\n"
61     // Save RBP
62     "pushq   %rbp\n"
63     // Save RSP
64     "movq    %rsp, %rbp\n"
65     // Save all int arg registers
66     "pushq   %rdi\n"
67     "pushq   %rsi\n"
68     "pushq   %rdx\n"
69     "pushq   %rcx\n"
70     "pushq   %r8\n"
71     "pushq   %r9\n"
72     // Align stack on 16-byte boundary. ESP might not be properly aligned
73     // (8 byte) if this is called from an indirect stub.
74     "andq    $-16, %rsp\n"
75     // Save all XMM arg registers
76     "subq    $128, %rsp\n"
77     "movaps  %xmm0, (%rsp)\n"
78     "movaps  %xmm1, 16(%rsp)\n"
79     "movaps  %xmm2, 32(%rsp)\n"
80     "movaps  %xmm3, 48(%rsp)\n"
81     "movaps  %xmm4, 64(%rsp)\n"
82     "movaps  %xmm5, 80(%rsp)\n"
83     "movaps  %xmm6, 96(%rsp)\n"
84     "movaps  %xmm7, 112(%rsp)\n"
85     // JIT callee
86     "movq    %rbp, %rdi\n"    // Pass prev frame and return address
87     "movq    8(%rbp), %rsi\n"
88     "call    " ASMPREFIX "X86CompilationCallback2\n"
89     // Restore all XMM arg registers
90     "movaps  112(%rsp), %xmm7\n"
91     "movaps  96(%rsp), %xmm6\n"
92     "movaps  80(%rsp), %xmm5\n"
93     "movaps  64(%rsp), %xmm4\n"
94     "movaps  48(%rsp), %xmm3\n"
95     "movaps  32(%rsp), %xmm2\n"
96     "movaps  16(%rsp), %xmm1\n"
97     "movaps  (%rsp), %xmm0\n"
98     // Restore RSP
99     "movq    %rbp, %rsp\n"
100     // Restore all int arg registers
101     "subq    $48, %rsp\n"
102     "popq    %r9\n"
103     "popq    %r8\n"
104     "popq    %rcx\n"
105     "popq    %rdx\n"
106     "popq    %rsi\n"
107     "popq    %rdi\n"
108     // Restore RBP
109     "popq    %rbp\n"
110     "ret\n");
111 #elif defined(__i386__) || defined(i386) || defined(_M_IX86)
112 #ifndef _MSC_VER
113   void X86CompilationCallback(void);
114   asm(
115     ".text\n"
116     ".align 8\n"
117     ".globl " ASMPREFIX  "X86CompilationCallback\n"
118   ASMPREFIX "X86CompilationCallback:\n"
119     "pushl   %ebp\n"
120     "movl    %esp, %ebp\n"    // Standard prologue
121 #if FASTCC_NUM_INT_ARGS_INREGS > 0
122     "pushl   %eax\n"
123     "pushl   %edx\n"          // Save EAX/EDX
124 #endif
125 #if defined(__APPLE__)
126     "andl    $-16, %esp\n"    // Align ESP on 16-byte boundary
127 #endif
128     "subl    $16, %esp\n"
129     "movl    4(%ebp), %eax\n" // Pass prev frame and return address
130     "movl    %eax, 4(%esp)\n"
131     "movl    %ebp, (%esp)\n"
132     "call    " ASMPREFIX "X86CompilationCallback2\n"
133     "movl    %ebp, %esp\n"    // Restore ESP
134 #if FASTCC_NUM_INT_ARGS_INREGS > 0
135     "subl    $8, %esp\n"
136     "popl    %edx\n"
137     "popl    %eax\n"
138 #endif
139     "popl    %ebp\n"
140     "ret\n");
141
142   // Same as X86CompilationCallback but also saves XMM argument registers.
143   void X86CompilationCallback_SSE(void);
144   asm(
145     ".text\n"
146     ".align 8\n"
147     ".globl " ASMPREFIX  "X86CompilationCallback_SSE\n"
148   ASMPREFIX "X86CompilationCallback_SSE:\n"
149     "pushl   %ebp\n"
150     "movl    %esp, %ebp\n"    // Standard prologue
151 #if FASTCC_NUM_INT_ARGS_INREGS > 0
152     "pushl   %eax\n"
153     "pushl   %edx\n"          // Save EAX/EDX
154 #endif
155     "andl    $-16, %esp\n"    // Align ESP on 16-byte boundary
156     // Save all XMM arg registers
157     "subl    $64, %esp\n"
158     "movaps  %xmm0, (%esp)\n"
159     "movaps  %xmm1, 16(%esp)\n"
160     "movaps  %xmm2, 32(%esp)\n"
161     "movaps  %xmm3, 48(%esp)\n"
162     "subl    $16, %esp\n"
163     "movl    4(%ebp), %eax\n" // Pass prev frame and return address
164     "movl    %eax, 4(%esp)\n"
165     "movl    %ebp, (%esp)\n"
166     "call    " ASMPREFIX "X86CompilationCallback2\n"
167     "addl    $16, %esp\n"
168     "movaps  48(%esp), %xmm3\n"
169     "movaps  32(%esp), %xmm2\n"
170     "movaps  16(%esp), %xmm1\n"
171     "movaps  (%esp), %xmm0\n"
172     "movl    %ebp, %esp\n"    // Restore ESP
173 #if FASTCC_NUM_INT_ARGS_INREGS > 0
174     "subl    $8, %esp\n"
175     "popl    %edx\n"
176     "popl    %eax\n"
177 #endif
178     "popl    %ebp\n"
179     "ret\n");
180 #else
181   void X86CompilationCallback2(void);
182
183   _declspec(naked) void X86CompilationCallback(void) {
184     __asm {
185       push  eax
186       push  edx
187       call  X86CompilationCallback2
188       pop   edx
189       pop   eax
190       ret
191     }
192   }
193 #endif // _MSC_VER
194
195 #else // Not an i386 host
196   void X86CompilationCallback() {
197     assert(0 && "Cannot call X86CompilationCallback() on a non-x86 arch!\n");
198     abort();
199   }
200 #endif
201 }
202
203 /// X86CompilationCallback - This is the target-specific function invoked by the
204 /// function stub when we did not know the real target of a call.  This function
205 /// must locate the start of the stub or call site and pass it into the JIT
206 /// compiler function.
207 #ifdef _MSC_VER
208 extern "C" void X86CompilationCallback2() {
209   assert(sizeof(size_t) == 4); // FIXME: handle Win64
210   unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress();
211   RetAddrLoc += 3;  // skip over ret addr, edx, eax
212   unsigned RetAddr = *RetAddrLoc;
213 #else
214 extern "C" void X86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr) {
215   intptr_t *RetAddrLoc = &StackPtr[1];
216 #endif
217   assert(*RetAddrLoc == RetAddr &&
218          "Could not find return address on the stack!");
219
220   // It's a stub if there is an interrupt marker after the call.
221   bool isStub = ((unsigned char*)RetAddr)[0] == 0xCD;
222
223   // The call instruction should have pushed the return value onto the stack...
224   RetAddr -= 4;  // Backtrack to the reference itself...
225
226 #if 0
227   DOUT << "In callback! Addr=" << (void*)RetAddr
228        << " ESP=" << (void*)StackPtr
229        << ": Resolving call to function: "
230        << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n";
231 #endif
232
233   // Sanity check to make sure this really is a call instruction.
234   assert(((unsigned char*)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
235
236   intptr_t NewVal = (intptr_t)JITCompilerFunction((void*)RetAddr);
237
238   // Rewrite the call target... so that we don't end up here every time we
239   // execute the call.
240   *(unsigned *)RetAddr = (unsigned)(NewVal-RetAddr-4);
241
242   if (isStub) {
243     // If this is a stub, rewrite the call into an unconditional branch
244     // instruction so that two return addresses are not pushed onto the stack
245     // when the requested function finally gets called.  This also makes the
246     // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
247     ((unsigned char*)RetAddr)[-1] = 0xE9;
248   }
249
250   // Change the return address to reexecute the call instruction...
251   *RetAddrLoc -= 5;
252 }
253
254 TargetJITInfo::LazyResolverFn
255 X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
256   JITCompilerFunction = F;
257
258 #if (defined(__i386__) || defined(i386) || defined(_M_IX86)) && \
259   !defined(_MSC_VER) && !defined(__x86_64__)
260   unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
261   union {
262     unsigned u[3];
263     char     c[12];
264   } text;
265
266   if (!X86::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1)) {
267     // FIXME: support for AMD family of processors.
268     if (memcmp(text.c, "GenuineIntel", 12) == 0) {
269       X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX);
270       if ((EDX >> 25) & 0x1)
271         return X86CompilationCallback_SSE;
272     }
273   }
274 #endif
275
276   return X86CompilationCallback;
277 }
278
279 void *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {
280   // Note, we cast to intptr_t here to silence a -pedantic warning that 
281   // complains about casting a function pointer to a normal pointer.
282 #if (defined(__i386__) || defined(i386) || defined(_M_IX86)) && \
283   !defined(_MSC_VER) && !defined(__x86_64__)
284   bool NotCC = (Fn != (void*)(intptr_t)X86CompilationCallback &&
285                 Fn != (void*)(intptr_t)X86CompilationCallback_SSE);
286 #else
287   bool NotCC = Fn != (void*)(intptr_t)X86CompilationCallback;
288 #endif
289   if (NotCC) {
290     MCE.startFunctionStub(5, 4);
291     MCE.emitByte(0xE9);
292     MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);
293     return MCE.finishFunctionStub(0);
294   }
295
296   MCE.startFunctionStub(6, 4);
297   MCE.emitByte(0xE8);   // Call with 32 bit pc-rel destination...
298
299   MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);
300
301   MCE.emitByte(0xCD);   // Interrupt - Just a marker identifying the stub!
302   return MCE.finishFunctionStub(0);
303 }
304
305 /// relocate - Before the JIT can run a block of code that has been emitted,
306 /// it must rewrite the code to contain the actual addresses of any
307 /// referenced global symbols.
308 void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
309                           unsigned NumRelocs, unsigned char* GOTBase) {
310   for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
311     void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
312     intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
313     switch ((X86::RelocationType)MR->getRelocationType()) {
314     case X86::reloc_pcrel_word: {
315       // PC relative relocation, add the relocated value to the value already in
316       // memory, after we adjust it for where the PC is.
317       ResultPtr = ResultPtr-(intptr_t)RelocPos-4-MR->getConstantVal();
318       *((unsigned*)RelocPos) += (unsigned)ResultPtr;
319       break;
320     }
321     case X86::reloc_absolute_word:
322       // Absolute relocation, just add the relocated value to the value already
323       // in memory.
324       *((unsigned*)RelocPos) += (unsigned)ResultPtr;
325       break;
326     }
327   }
328 }