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