1193323Sed//===-- ARMJITInfo.cpp - Implement the JIT interfaces for the ARM target --===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file implements the JIT interfaces for the ARM target.
11193323Sed//
12193323Sed//===----------------------------------------------------------------------===//
13193323Sed
14193323Sed#define DEBUG_TYPE "jit"
15193323Sed#include "ARMJITInfo.h"
16235633Sdim#include "ARM.h"
17193323Sed#include "ARMConstantPoolValue.h"
18193323Sed#include "ARMRelocations.h"
19193323Sed#include "ARMSubtarget.h"
20193323Sed#include "llvm/CodeGen/JITCodeEmitter.h"
21252723Sdim#include "llvm/IR/Function.h"
22193323Sed#include "llvm/Support/Debug.h"
23198090Srdivacky#include "llvm/Support/ErrorHandling.h"
24252723Sdim#include "llvm/Support/Memory.h"
25198090Srdivacky#include "llvm/Support/raw_ostream.h"
26193323Sed#include <cstdlib>
27193323Sedusing namespace llvm;
28193323Sed
29193323Sedvoid ARMJITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
30207618Srdivacky  report_fatal_error("ARMJITInfo::replaceMachineCodeForFunction");
31193323Sed}
32193323Sed
33193323Sed/// JITCompilerFunction - This contains the address of the JIT function used to
34193323Sed/// compile a function lazily.
35193323Sedstatic TargetJITInfo::JITCompilerFn JITCompilerFunction;
36193323Sed
37193323Sed// Get the ASMPREFIX for the current host.  This is often '_'.
38193323Sed#ifndef __USER_LABEL_PREFIX__
39193323Sed#define __USER_LABEL_PREFIX__
40193323Sed#endif
41193323Sed#define GETASMPREFIX2(X) #X
42193323Sed#define GETASMPREFIX(X) GETASMPREFIX2(X)
43193323Sed#define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__)
44193323Sed
45193323Sed// CompilationCallback stub - We can't use a C function with inline assembly in
46218893Sdim// it, because the prolog/epilog inserted by GCC won't work for us. (We need
47193323Sed// to preserve more context and manipulate the stack directly).  Instead,
48198090Srdivacky// write our own wrapper, which does things our way, so we have complete
49193323Sed// control over register saving and restoring.
50193323Sedextern "C" {
51193323Sed#if defined(__arm__)
52198090Srdivacky  void ARMCompilationCallback();
53193323Sed  asm(
54193323Sed    ".text\n"
55193323Sed    ".align 2\n"
56193323Sed    ".globl " ASMPREFIX "ARMCompilationCallback\n"
57193323Sed    ASMPREFIX "ARMCompilationCallback:\n"
58193323Sed    // Save caller saved registers since they may contain stuff
59193323Sed    // for the real target function right now. We have to act as if this
60193323Sed    // whole compilation callback doesn't exist as far as the caller is
61193323Sed    // concerned, so we can't just preserve the callee saved regs.
62193323Sed    "stmdb sp!, {r0, r1, r2, r3, lr}\n"
63204642Srdivacky#if (defined(__VFP_FP__) && !defined(__SOFTFP__))
64235633Sdim    "vstmdb sp!, {d0, d1, d2, d3, d4, d5, d6, d7}\n"
65193323Sed#endif
66193323Sed    // The LR contains the address of the stub function on entry.
67193323Sed    // pass it as the argument to the C part of the callback
68193323Sed    "mov  r0, lr\n"
69193323Sed    "sub  sp, sp, #4\n"
70193323Sed    // Call the C portion of the callback
71193323Sed    "bl   " ASMPREFIX "ARMCompilationCallbackC\n"
72193323Sed    "add  sp, sp, #4\n"
73193323Sed    // Restoring the LR to the return address of the function that invoked
74193323Sed    // the stub and de-allocating the stack space for it requires us to
75193323Sed    // swap the two saved LR values on the stack, as they're backwards
76193323Sed    // for what we need since the pop instruction has a pre-determined
77193323Sed    // order for the registers.
78193323Sed    //      +--------+
79193323Sed    //   0  | LR     | Original return address
80198090Srdivacky    //      +--------+
81193323Sed    //   1  | LR     | Stub address (start of stub)
82193323Sed    // 2-5  | R3..R0 | Saved registers (we need to preserve all regs)
83193323Sed    // 6-20 | D0..D7 | Saved VFP registers
84198090Srdivacky    //      +--------+
85193323Sed    //
86204642Srdivacky#if (defined(__VFP_FP__) && !defined(__SOFTFP__))
87193323Sed    // Restore VFP caller-saved registers.
88235633Sdim    "vldmia sp!, {d0, d1, d2, d3, d4, d5, d6, d7}\n"
89193323Sed#endif
90193323Sed    //
91193323Sed    //      We need to exchange the values in slots 0 and 1 so we can
92193323Sed    //      return to the address in slot 1 with the address in slot 0
93193323Sed    //      restored to the LR.
94193323Sed    "ldr  r0, [sp,#20]\n"
95193323Sed    "ldr  r1, [sp,#16]\n"
96193323Sed    "str  r1, [sp,#20]\n"
97193323Sed    "str  r0, [sp,#16]\n"
98193323Sed    // Return to the (newly modified) stub to invoke the real function.
99193323Sed    // The above twiddling of the saved return addresses allows us to
100218893Sdim    // deallocate everything, including the LR the stub saved, with two
101218893Sdim    // updating load instructions.
102218893Sdim    "ldmia  sp!, {r0, r1, r2, r3, lr}\n"
103218893Sdim    "ldr    pc, [sp], #4\n"
104193323Sed      );
105193323Sed#else  // Not an ARM host
106193323Sed  void ARMCompilationCallback() {
107198090Srdivacky    llvm_unreachable("Cannot call ARMCompilationCallback() on a non-ARM arch!");
108193323Sed  }
109193323Sed#endif
110193323Sed}
111193323Sed
112198090Srdivacky/// ARMCompilationCallbackC - This is the target-specific function invoked
113198090Srdivacky/// by the function stub when we did not know the real target of a call.
114198090Srdivacky/// This function must locate the start of the stub or call site and pass
115193323Sed/// it into the JIT compiler function.
116193323Sedextern "C" void ARMCompilationCallbackC(intptr_t StubAddr) {
117193323Sed  // Get the address of the compiled code for this function.
118193323Sed  intptr_t NewVal = (intptr_t)JITCompilerFunction((void*)StubAddr);
119193323Sed
120193323Sed  // Rewrite the call target... so that we don't end up here every time we
121193323Sed  // execute the call. We're replacing the first two instructions of the
122193323Sed  // stub with:
123193323Sed  //   ldr pc, [pc,#-4]
124193323Sed  //   <addr>
125193323Sed  if (!sys::Memory::setRangeWritable((void*)StubAddr, 8)) {
126198090Srdivacky    llvm_unreachable("ERROR: Unable to mark stub writable");
127193323Sed  }
128193323Sed  *(intptr_t *)StubAddr = 0xe51ff004;  // ldr pc, [pc, #-4]
129193323Sed  *(intptr_t *)(StubAddr+4) = NewVal;
130193323Sed  if (!sys::Memory::setRangeExecutable((void*)StubAddr, 8)) {
131198090Srdivacky    llvm_unreachable("ERROR: Unable to mark stub executable");
132193323Sed  }
133193323Sed}
134193323Sed
135193323SedTargetJITInfo::LazyResolverFn
136193323SedARMJITInfo::getLazyResolverFunction(JITCompilerFn F) {
137193323Sed  JITCompilerFunction = F;
138193323Sed  return ARMCompilationCallback;
139193323Sed}
140193323Sed
141193323Sedvoid *ARMJITInfo::emitGlobalValueIndirectSym(const GlobalValue *GV, void *Ptr,
142193323Sed                                             JITCodeEmitter &JCE) {
143201360Srdivacky  uint8_t Buffer[4];
144201360Srdivacky  uint8_t *Cur = Buffer;
145201360Srdivacky  MachineCodeEmitter::emitWordLEInto(Cur, (intptr_t)Ptr);
146201360Srdivacky  void *PtrAddr = JCE.allocIndirectGV(
147201360Srdivacky      GV, Buffer, sizeof(Buffer), /*Alignment=*/4);
148193323Sed  addIndirectSymAddr(Ptr, (intptr_t)PtrAddr);
149193323Sed  return PtrAddr;
150193323Sed}
151193323Sed
152199989SrdivackyTargetJITInfo::StubLayout ARMJITInfo::getStubLayout() {
153199989Srdivacky  // The stub contains up to 3 4-byte instructions, aligned at 4 bytes, and a
154199989Srdivacky  // 4-byte address.  See emitFunctionStub for details.
155199989Srdivacky  StubLayout Result = {16, 4};
156199989Srdivacky  return Result;
157199989Srdivacky}
158199989Srdivacky
159193323Sedvoid *ARMJITInfo::emitFunctionStub(const Function* F, void *Fn,
160193323Sed                                   JITCodeEmitter &JCE) {
161199989Srdivacky  void *Addr;
162193323Sed  // If this is just a call to an external function, emit a branch instead of a
163193323Sed  // call.  The code is the same except for one bit of the last instruction.
164193323Sed  if (Fn != (void*)(intptr_t)ARMCompilationCallback) {
165193323Sed    // Branch to the corresponding function addr.
166193323Sed    if (IsPIC) {
167199989Srdivacky      // The stub is 16-byte size and 4-aligned.
168193323Sed      intptr_t LazyPtr = getIndirectSymAddr(Fn);
169193323Sed      if (!LazyPtr) {
170193323Sed        // In PIC mode, the function stub is loading a lazy-ptr.
171245431Sdim        LazyPtr= (intptr_t)emitGlobalValueIndirectSym((const GlobalValue*)F, Fn, JCE);
172198090Srdivacky        DEBUG(if (F)
173198090Srdivacky                errs() << "JIT: Indirect symbol emitted at [" << LazyPtr
174198090Srdivacky                       << "] for GV '" << F->getName() << "'\n";
175198090Srdivacky              else
176198090Srdivacky                errs() << "JIT: Stub emitted at [" << LazyPtr
177198090Srdivacky                       << "] for external function at '" << Fn << "'\n");
178193323Sed      }
179199989Srdivacky      JCE.emitAlignment(4);
180199989Srdivacky      Addr = (void*)JCE.getCurrentPCValue();
181199989Srdivacky      if (!sys::Memory::setRangeWritable(Addr, 16)) {
182198090Srdivacky        llvm_unreachable("ERROR: Unable to mark stub writable");
183198090Srdivacky      }
184199989Srdivacky      JCE.emitWordLE(0xe59fc004);            // ldr ip, [pc, #+4]
185193323Sed      JCE.emitWordLE(0xe08fc00c);            // L_func$scv: add ip, pc, ip
186193323Sed      JCE.emitWordLE(0xe59cf000);            // ldr pc, [ip]
187199989Srdivacky      JCE.emitWordLE(LazyPtr - (intptr_t(Addr)+4+8));  // func - (L_func$scv+8)
188199989Srdivacky      sys::Memory::InvalidateInstructionCache(Addr, 16);
189199989Srdivacky      if (!sys::Memory::setRangeExecutable(Addr, 16)) {
190198090Srdivacky        llvm_unreachable("ERROR: Unable to mark stub executable");
191198090Srdivacky      }
192193323Sed    } else {
193193323Sed      // The stub is 8-byte size and 4-aligned.
194199989Srdivacky      JCE.emitAlignment(4);
195199989Srdivacky      Addr = (void*)JCE.getCurrentPCValue();
196199989Srdivacky      if (!sys::Memory::setRangeWritable(Addr, 8)) {
197198090Srdivacky        llvm_unreachable("ERROR: Unable to mark stub writable");
198198090Srdivacky      }
199193323Sed      JCE.emitWordLE(0xe51ff004);    // ldr pc, [pc, #-4]
200193323Sed      JCE.emitWordLE((intptr_t)Fn);  // addr of function
201199989Srdivacky      sys::Memory::InvalidateInstructionCache(Addr, 8);
202199989Srdivacky      if (!sys::Memory::setRangeExecutable(Addr, 8)) {
203198090Srdivacky        llvm_unreachable("ERROR: Unable to mark stub executable");
204198090Srdivacky      }
205193323Sed    }
206193323Sed  } else {
207193323Sed    // The compilation callback will overwrite the first two words of this
208198090Srdivacky    // stub with indirect branch instructions targeting the compiled code.
209193323Sed    // This stub sets the return address to restart the stub, so that
210193323Sed    // the new branch will be invoked when we come back.
211193323Sed    //
212193323Sed    // Branch and link to the compilation callback.
213193323Sed    // The stub is 16-byte size and 4-byte aligned.
214199989Srdivacky    JCE.emitAlignment(4);
215199989Srdivacky    Addr = (void*)JCE.getCurrentPCValue();
216199989Srdivacky    if (!sys::Memory::setRangeWritable(Addr, 16)) {
217198090Srdivacky      llvm_unreachable("ERROR: Unable to mark stub writable");
218198090Srdivacky    }
219193323Sed    // Save LR so the callback can determine which stub called it.
220193323Sed    // The compilation callback is responsible for popping this prior
221193323Sed    // to returning.
222193323Sed    JCE.emitWordLE(0xe92d4000); // push {lr}
223193323Sed    // Set the return address to go back to the start of this stub.
224193323Sed    JCE.emitWordLE(0xe24fe00c); // sub lr, pc, #12
225193323Sed    // Invoke the compilation callback.
226193323Sed    JCE.emitWordLE(0xe51ff004); // ldr pc, [pc, #-4]
227193323Sed    // The address of the compilation callback.
228193323Sed    JCE.emitWordLE((intptr_t)ARMCompilationCallback);
229199989Srdivacky    sys::Memory::InvalidateInstructionCache(Addr, 16);
230199989Srdivacky    if (!sys::Memory::setRangeExecutable(Addr, 16)) {
231198090Srdivacky      llvm_unreachable("ERROR: Unable to mark stub executable");
232198090Srdivacky    }
233193323Sed  }
234193323Sed
235199989Srdivacky  return Addr;
236193323Sed}
237193323Sed
238193323Sedintptr_t ARMJITInfo::resolveRelocDestAddr(MachineRelocation *MR) const {
239193323Sed  ARM::RelocationType RT = (ARM::RelocationType)MR->getRelocationType();
240193323Sed  switch (RT) {
241193323Sed  default:
242193323Sed    return (intptr_t)(MR->getResultPointer());
243193323Sed  case ARM::reloc_arm_pic_jt:
244193323Sed    // Destination address - jump table base.
245193323Sed    return (intptr_t)(MR->getResultPointer()) - MR->getConstantVal();
246193323Sed  case ARM::reloc_arm_jt_base:
247193323Sed    // Jump table base address.
248193323Sed    return getJumpTableBaseAddr(MR->getJumpTableIndex());
249193323Sed  case ARM::reloc_arm_cp_entry:
250193323Sed  case ARM::reloc_arm_vfp_cp_entry:
251193323Sed    // Constant pool entry address.
252193323Sed    return getConstantPoolEntryAddr(MR->getConstantPoolIndex());
253193323Sed  case ARM::reloc_arm_machine_cp_entry: {
254193323Sed    ARMConstantPoolValue *ACPV = (ARMConstantPoolValue*)MR->getConstantVal();
255193323Sed    assert((!ACPV->hasModifier() && !ACPV->mustAddCurrentAddress()) &&
256193323Sed           "Can't handle this machine constant pool entry yet!");
257193323Sed    intptr_t Addr = (intptr_t)(MR->getResultPointer());
258193323Sed    Addr -= getPCLabelAddr(ACPV->getLabelId()) + ACPV->getPCAdjustment();
259193323Sed    return Addr;
260193323Sed  }
261193323Sed  }
262193323Sed}
263193323Sed
264193323Sed/// relocate - Before the JIT can run a block of code that has been emitted,
265193323Sed/// it must rewrite the code to contain the actual addresses of any
266193323Sed/// referenced global symbols.
267193323Sedvoid ARMJITInfo::relocate(void *Function, MachineRelocation *MR,
268193323Sed                          unsigned NumRelocs, unsigned char* GOTBase) {
269193323Sed  for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
270193323Sed    void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
271193323Sed    intptr_t ResultPtr = resolveRelocDestAddr(MR);
272193323Sed    switch ((ARM::RelocationType)MR->getRelocationType()) {
273193323Sed    case ARM::reloc_arm_cp_entry:
274193323Sed    case ARM::reloc_arm_vfp_cp_entry:
275193323Sed    case ARM::reloc_arm_relative: {
276193323Sed      // It is necessary to calculate the correct PC relative value. We
277193323Sed      // subtract the base addr from the target addr to form a byte offset.
278193323Sed      ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
279193323Sed      // If the result is positive, set bit U(23) to 1.
280193323Sed      if (ResultPtr >= 0)
281193323Sed        *((intptr_t*)RelocPos) |= 1 << ARMII::U_BitShift;
282193323Sed      else {
283193323Sed        // Otherwise, obtain the absolute value and set bit U(23) to 0.
284193323Sed        *((intptr_t*)RelocPos) &= ~(1 << ARMII::U_BitShift);
285193323Sed        ResultPtr = - ResultPtr;
286193323Sed      }
287193323Sed      // Set the immed value calculated.
288193323Sed      // VFP immediate offset is multiplied by 4.
289193323Sed      if (MR->getRelocationType() == ARM::reloc_arm_vfp_cp_entry)
290193323Sed        ResultPtr = ResultPtr >> 2;
291193323Sed      *((intptr_t*)RelocPos) |= ResultPtr;
292245431Sdim      // Set register Rn to PC (which is register 15 on all architectures).
293245431Sdim      // FIXME: This avoids the need for register info in the JIT class.
294245431Sdim      *((intptr_t*)RelocPos) |= 15 << ARMII::RegRnShift;
295193323Sed      break;
296193323Sed    }
297193323Sed    case ARM::reloc_arm_pic_jt:
298193323Sed    case ARM::reloc_arm_machine_cp_entry:
299193323Sed    case ARM::reloc_arm_absolute: {
300193323Sed      // These addresses have already been resolved.
301193323Sed      *((intptr_t*)RelocPos) |= (intptr_t)ResultPtr;
302193323Sed      break;
303193323Sed    }
304193323Sed    case ARM::reloc_arm_branch: {
305193323Sed      // It is necessary to calculate the correct value of signed_immed_24
306193323Sed      // field. We subtract the base addr from the target addr to form a
307193323Sed      // byte offset, which must be inside the range -33554432 and +33554428.
308193323Sed      // Then, we set the signed_immed_24 field of the instruction to bits
309193323Sed      // [25:2] of the byte offset. More details ARM-ARM p. A4-11.
310193323Sed      ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
311193323Sed      ResultPtr = (ResultPtr & 0x03FFFFFC) >> 2;
312193323Sed      assert(ResultPtr >= -33554432 && ResultPtr <= 33554428);
313193323Sed      *((intptr_t*)RelocPos) |= ResultPtr;
314193323Sed      break;
315193323Sed    }
316193323Sed    case ARM::reloc_arm_jt_base: {
317193323Sed      // JT base - (instruction addr + 8)
318193323Sed      ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
319193323Sed      *((intptr_t*)RelocPos) |= ResultPtr;
320193323Sed      break;
321193323Sed    }
322208599Srdivacky    case ARM::reloc_arm_movw: {
323208599Srdivacky      ResultPtr = ResultPtr & 0xFFFF;
324208599Srdivacky      *((intptr_t*)RelocPos) |= ResultPtr & 0xFFF;
325208599Srdivacky      *((intptr_t*)RelocPos) |= ((ResultPtr >> 12) & 0xF) << 16;
326208599Srdivacky      break;
327193323Sed    }
328208599Srdivacky    case ARM::reloc_arm_movt: {
329208599Srdivacky      ResultPtr = (ResultPtr >> 16) & 0xFFFF;
330208599Srdivacky      *((intptr_t*)RelocPos) |= ResultPtr & 0xFFF;
331208599Srdivacky      *((intptr_t*)RelocPos) |= ((ResultPtr >> 12) & 0xF) << 16;
332208599Srdivacky      break;
333208599Srdivacky    }
334208599Srdivacky    }
335193323Sed  }
336193323Sed}
337