Update comment to reflect instruction.
[oota-llvm.git] / lib / Target / ARM / ARMJITInfo.cpp
1 //===-- ARMJITInfo.cpp - Implement the JIT interfaces for the ARM target --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the JIT interfaces for the ARM target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "jit"
15 #include "ARMJITInfo.h"
16 #include "ARMInstrInfo.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMRelocations.h"
19 #include "ARMSubtarget.h"
20 #include "llvm/Function.h"
21 #include "llvm/CodeGen/JITCodeEmitter.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/System/Memory.h"
26 #include <cstdlib>
27 using namespace llvm;
28
29 void ARMJITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
30   llvm_report_error("ARMJITInfo::replaceMachineCodeForFunction");
31 }
32
33 /// JITCompilerFunction - This contains the address of the JIT function used to
34 /// compile a function lazily.
35 static TargetJITInfo::JITCompilerFn JITCompilerFunction;
36
37 // Get the ASMPREFIX for the current host.  This is often '_'.
38 #ifndef __USER_LABEL_PREFIX__
39 #define __USER_LABEL_PREFIX__
40 #endif
41 #define GETASMPREFIX2(X) #X
42 #define GETASMPREFIX(X) GETASMPREFIX2(X)
43 #define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__)
44
45 // CompilationCallback stub - We can't use a C function with inline assembly in
46 // it, because we the prolog/epilog inserted by GCC won't work for us (we need
47 // to preserve more context and manipulate the stack directly).  Instead,
48 // write our own wrapper, which does things our way, so we have complete
49 // control over register saving and restoring.
50 extern "C" {
51 #if defined(__arm__)
52   void ARMCompilationCallback();
53   asm(
54     ".text\n"
55     ".align 2\n"
56     ".globl " ASMPREFIX "ARMCompilationCallback\n"
57     ASMPREFIX "ARMCompilationCallback:\n"
58     // Save caller saved registers since they may contain stuff
59     // for the real target function right now. We have to act as if this
60     // whole compilation callback doesn't exist as far as the caller is
61     // concerned, so we can't just preserve the callee saved regs.
62     "stmdb sp!, {r0, r1, r2, r3, lr}\n"
63 #ifndef __SOFTFP__
64     "fstmfdd sp!, {d0, d1, d2, d3, d4, d5, d6, d7}\n"
65 #endif
66     // The LR contains the address of the stub function on entry.
67     // pass it as the argument to the C part of the callback
68     "mov  r0, lr\n"
69     "sub  sp, sp, #4\n"
70     // Call the C portion of the callback
71     "bl   " ASMPREFIX "ARMCompilationCallbackC\n"
72     "add  sp, sp, #4\n"
73     // Restoring the LR to the return address of the function that invoked
74     // the stub and de-allocating the stack space for it requires us to
75     // swap the two saved LR values on the stack, as they're backwards
76     // for what we need since the pop instruction has a pre-determined
77     // order for the registers.
78     //      +--------+
79     //   0  | LR     | Original return address
80     //      +--------+
81     //   1  | LR     | Stub address (start of stub)
82     // 2-5  | R3..R0 | Saved registers (we need to preserve all regs)
83     // 6-20 | D0..D7 | Saved VFP registers
84     //      +--------+
85     //
86 #ifndef __SOFTFP__
87     // Restore VFP caller-saved registers.
88     "fldmfdd sp!, {d0, d1, d2, d3, d4, d5, d6, d7}\n"
89 #endif
90     //
91     //      We need to exchange the values in slots 0 and 1 so we can
92     //      return to the address in slot 1 with the address in slot 0
93     //      restored to the LR.
94     "ldr  r0, [sp,#20]\n"
95     "ldr  r1, [sp,#16]\n"
96     "str  r1, [sp,#20]\n"
97     "str  r0, [sp,#16]\n"
98     // Return to the (newly modified) stub to invoke the real function.
99     // The above twiddling of the saved return addresses allows us to
100     // deallocate everything, including the LR the stub saved, all in one
101     // pop instruction.
102     "ldmia  sp!, {r0, r1, r2, r3, lr, pc}\n"
103       );
104 #else  // Not an ARM host
105   void ARMCompilationCallback() {
106     llvm_unreachable("Cannot call ARMCompilationCallback() on a non-ARM arch!");
107   }
108 #endif
109 }
110
111 /// ARMCompilationCallbackC - This is the target-specific function invoked
112 /// by the function stub when we did not know the real target of a call.
113 /// This function must locate the start of the stub or call site and pass
114 /// it into the JIT compiler function.
115 extern "C" void ARMCompilationCallbackC(intptr_t StubAddr) {
116   // Get the address of the compiled code for this function.
117   intptr_t NewVal = (intptr_t)JITCompilerFunction((void*)StubAddr);
118
119   // Rewrite the call target... so that we don't end up here every time we
120   // execute the call. We're replacing the first two instructions of the
121   // stub with:
122   //   ldr pc, [pc,#-4]
123   //   <addr>
124   if (!sys::Memory::setRangeWritable((void*)StubAddr, 8)) {
125     llvm_unreachable("ERROR: Unable to mark stub writable");
126   }
127   *(intptr_t *)StubAddr = 0xe51ff004;  // ldr pc, [pc, #-4]
128   *(intptr_t *)(StubAddr+4) = NewVal;
129   if (!sys::Memory::setRangeExecutable((void*)StubAddr, 8)) {
130     llvm_unreachable("ERROR: Unable to mark stub executable");
131   }
132 }
133
134 TargetJITInfo::LazyResolverFn
135 ARMJITInfo::getLazyResolverFunction(JITCompilerFn F) {
136   JITCompilerFunction = F;
137   return ARMCompilationCallback;
138 }
139
140 void *ARMJITInfo::emitGlobalValueIndirectSym(const GlobalValue *GV, void *Ptr,
141                                              JITCodeEmitter &JCE) {
142   JCE.startGVStub(GV, 4, 4);
143   intptr_t Addr = (intptr_t)JCE.getCurrentPCValue();
144   if (!sys::Memory::setRangeWritable((void*)Addr, 4)) {
145     llvm_unreachable("ERROR: Unable to mark indirect symbol writable");
146   }
147   JCE.emitWordLE((intptr_t)Ptr);
148   if (!sys::Memory::setRangeExecutable((void*)Addr, 4)) {
149     llvm_unreachable("ERROR: Unable to mark indirect symbol executable");
150   }
151   void *PtrAddr = JCE.finishGVStub(GV);
152   addIndirectSymAddr(Ptr, (intptr_t)PtrAddr);
153   return PtrAddr;
154 }
155
156 void *ARMJITInfo::emitFunctionStub(const Function* F, void *Fn,
157                                    JITCodeEmitter &JCE) {
158   // If this is just a call to an external function, emit a branch instead of a
159   // call.  The code is the same except for one bit of the last instruction.
160   if (Fn != (void*)(intptr_t)ARMCompilationCallback) {
161     // Branch to the corresponding function addr.
162     if (IsPIC) {
163       // The stub is 8-byte size and 4-aligned.
164       intptr_t LazyPtr = getIndirectSymAddr(Fn);
165       if (!LazyPtr) {
166         // In PIC mode, the function stub is loading a lazy-ptr.
167         LazyPtr= (intptr_t)emitGlobalValueIndirectSym((GlobalValue*)F, Fn, JCE);
168         DEBUG(if (F)
169                 errs() << "JIT: Indirect symbol emitted at [" << LazyPtr
170                        << "] for GV '" << F->getName() << "'\n";
171               else
172                 errs() << "JIT: Stub emitted at [" << LazyPtr
173                        << "] for external function at '" << Fn << "'\n");
174       }
175       JCE.startGVStub(F, 16, 4);
176       intptr_t Addr = (intptr_t)JCE.getCurrentPCValue();
177       if (!sys::Memory::setRangeWritable((void*)Addr, 16)) {
178         llvm_unreachable("ERROR: Unable to mark stub writable");
179       }
180       JCE.emitWordLE(0xe59fc004);            // ldr ip, [pc, #+4]
181       JCE.emitWordLE(0xe08fc00c);            // L_func$scv: add ip, pc, ip
182       JCE.emitWordLE(0xe59cf000);            // ldr pc, [ip]
183       JCE.emitWordLE(LazyPtr - (Addr+4+8));  // func - (L_func$scv+8)
184       sys::Memory::InvalidateInstructionCache((void*)Addr, 16);
185       if (!sys::Memory::setRangeExecutable((void*)Addr, 16)) {
186         llvm_unreachable("ERROR: Unable to mark stub executable");
187       }
188     } else {
189       // The stub is 8-byte size and 4-aligned.
190       JCE.startGVStub(F, 8, 4);
191       intptr_t Addr = (intptr_t)JCE.getCurrentPCValue();
192       if (!sys::Memory::setRangeWritable((void*)Addr, 8)) {
193         llvm_unreachable("ERROR: Unable to mark stub writable");
194       }
195       JCE.emitWordLE(0xe51ff004);    // ldr pc, [pc, #-4]
196       JCE.emitWordLE((intptr_t)Fn);  // addr of function
197       sys::Memory::InvalidateInstructionCache((void*)Addr, 8);
198       if (!sys::Memory::setRangeExecutable((void*)Addr, 8)) {
199         llvm_unreachable("ERROR: Unable to mark stub executable");
200       }
201     }
202   } else {
203     // The compilation callback will overwrite the first two words of this
204     // stub with indirect branch instructions targeting the compiled code.
205     // This stub sets the return address to restart the stub, so that
206     // the new branch will be invoked when we come back.
207     //
208     // Branch and link to the compilation callback.
209     // The stub is 16-byte size and 4-byte aligned.
210     JCE.startGVStub(F, 16, 4);
211     intptr_t Addr = (intptr_t)JCE.getCurrentPCValue();
212     if (!sys::Memory::setRangeWritable((void*)Addr, 16)) {
213       llvm_unreachable("ERROR: Unable to mark stub writable");
214     }
215     // Save LR so the callback can determine which stub called it.
216     // The compilation callback is responsible for popping this prior
217     // to returning.
218     JCE.emitWordLE(0xe92d4000); // push {lr}
219     // Set the return address to go back to the start of this stub.
220     JCE.emitWordLE(0xe24fe00c); // sub lr, pc, #12
221     // Invoke the compilation callback.
222     JCE.emitWordLE(0xe51ff004); // ldr pc, [pc, #-4]
223     // The address of the compilation callback.
224     JCE.emitWordLE((intptr_t)ARMCompilationCallback);
225     sys::Memory::InvalidateInstructionCache((void*)Addr, 16);
226     if (!sys::Memory::setRangeExecutable((void*)Addr, 16)) {
227       llvm_unreachable("ERROR: Unable to mark stub executable");
228     }
229   }
230
231   return JCE.finishGVStub(F);
232 }
233
234 intptr_t ARMJITInfo::resolveRelocDestAddr(MachineRelocation *MR) const {
235   ARM::RelocationType RT = (ARM::RelocationType)MR->getRelocationType();
236   switch (RT) {
237   default:
238     return (intptr_t)(MR->getResultPointer());
239   case ARM::reloc_arm_pic_jt:
240     // Destination address - jump table base.
241     return (intptr_t)(MR->getResultPointer()) - MR->getConstantVal();
242   case ARM::reloc_arm_jt_base:
243     // Jump table base address.
244     return getJumpTableBaseAddr(MR->getJumpTableIndex());
245   case ARM::reloc_arm_cp_entry:
246   case ARM::reloc_arm_vfp_cp_entry:
247     // Constant pool entry address.
248     return getConstantPoolEntryAddr(MR->getConstantPoolIndex());
249   case ARM::reloc_arm_machine_cp_entry: {
250     ARMConstantPoolValue *ACPV = (ARMConstantPoolValue*)MR->getConstantVal();
251     assert((!ACPV->hasModifier() && !ACPV->mustAddCurrentAddress()) &&
252            "Can't handle this machine constant pool entry yet!");
253     intptr_t Addr = (intptr_t)(MR->getResultPointer());
254     Addr -= getPCLabelAddr(ACPV->getLabelId()) + ACPV->getPCAdjustment();
255     return Addr;
256   }
257   }
258 }
259
260 /// relocate - Before the JIT can run a block of code that has been emitted,
261 /// it must rewrite the code to contain the actual addresses of any
262 /// referenced global symbols.
263 void ARMJITInfo::relocate(void *Function, MachineRelocation *MR,
264                           unsigned NumRelocs, unsigned char* GOTBase) {
265   for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
266     void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
267     intptr_t ResultPtr = resolveRelocDestAddr(MR);
268     switch ((ARM::RelocationType)MR->getRelocationType()) {
269     case ARM::reloc_arm_cp_entry:
270     case ARM::reloc_arm_vfp_cp_entry:
271     case ARM::reloc_arm_relative: {
272       // It is necessary to calculate the correct PC relative value. We
273       // subtract the base addr from the target addr to form a byte offset.
274       ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
275       // If the result is positive, set bit U(23) to 1.
276       if (ResultPtr >= 0)
277         *((intptr_t*)RelocPos) |= 1 << ARMII::U_BitShift;
278       else {
279         // Otherwise, obtain the absolute value and set bit U(23) to 0.
280         *((intptr_t*)RelocPos) &= ~(1 << ARMII::U_BitShift);
281         ResultPtr = - ResultPtr;
282       }
283       // Set the immed value calculated.
284       // VFP immediate offset is multiplied by 4.
285       if (MR->getRelocationType() == ARM::reloc_arm_vfp_cp_entry)
286         ResultPtr = ResultPtr >> 2;
287       *((intptr_t*)RelocPos) |= ResultPtr;
288       // Set register Rn to PC.
289       *((intptr_t*)RelocPos) |=
290         ARMRegisterInfo::getRegisterNumbering(ARM::PC) << ARMII::RegRnShift;
291       break;
292     }
293     case ARM::reloc_arm_pic_jt:
294     case ARM::reloc_arm_machine_cp_entry:
295     case ARM::reloc_arm_absolute: {
296       // These addresses have already been resolved.
297       *((intptr_t*)RelocPos) |= (intptr_t)ResultPtr;
298       break;
299     }
300     case ARM::reloc_arm_branch: {
301       // It is necessary to calculate the correct value of signed_immed_24
302       // field. We subtract the base addr from the target addr to form a
303       // byte offset, which must be inside the range -33554432 and +33554428.
304       // Then, we set the signed_immed_24 field of the instruction to bits
305       // [25:2] of the byte offset. More details ARM-ARM p. A4-11.
306       ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
307       ResultPtr = (ResultPtr & 0x03FFFFFC) >> 2;
308       assert(ResultPtr >= -33554432 && ResultPtr <= 33554428);
309       *((intptr_t*)RelocPos) |= ResultPtr;
310       break;
311     }
312     case ARM::reloc_arm_jt_base: {
313       // JT base - (instruction addr + 8)
314       ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
315       *((intptr_t*)RelocPos) |= ResultPtr;
316       break;
317     }
318     }
319   }
320 }