LLVM API Documentation

ARMJITInfo.cpp
Go to the documentation of this file.
00001 //===-- ARMJITInfo.cpp - Implement the JIT interfaces for the ARM target --===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the JIT interfaces for the ARM target.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "ARMJITInfo.h"
00015 #include "ARMConstantPoolValue.h"
00016 #include "ARMMachineFunctionInfo.h"
00017 #include "ARMRelocations.h"
00018 #include "MCTargetDesc/ARMBaseInfo.h"
00019 #include "llvm/CodeGen/JITCodeEmitter.h"
00020 #include "llvm/IR/Function.h"
00021 #include "llvm/Support/Debug.h"
00022 #include "llvm/Support/ErrorHandling.h"
00023 #include "llvm/Support/Memory.h"
00024 #include "llvm/Support/raw_ostream.h"
00025 #include <cstdlib>
00026 using namespace llvm;
00027 
00028 #define DEBUG_TYPE "jit"
00029 
00030 void ARMJITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
00031   report_fatal_error("ARMJITInfo::replaceMachineCodeForFunction");
00032 }
00033 
00034 /// JITCompilerFunction - This contains the address of the JIT function used to
00035 /// compile a function lazily.
00036 static TargetJITInfo::JITCompilerFn JITCompilerFunction;
00037 
00038 // Get the ASMPREFIX for the current host.  This is often '_'.
00039 #ifndef __USER_LABEL_PREFIX__
00040 #define __USER_LABEL_PREFIX__
00041 #endif
00042 #define GETASMPREFIX2(X) #X
00043 #define GETASMPREFIX(X) GETASMPREFIX2(X)
00044 #define ASMPREFIX GETASMPREFIX(__USER_LABEL_PREFIX__)
00045 
00046 // CompilationCallback stub - We can't use a C function with inline assembly in
00047 // it, because the prolog/epilog inserted by GCC won't work for us. (We need
00048 // to preserve more context and manipulate the stack directly).  Instead,
00049 // write our own wrapper, which does things our way, so we have complete
00050 // control over register saving and restoring.
00051 extern "C" {
00052 #if defined(__arm__)
00053   void ARMCompilationCallback();
00054   asm(
00055     ".text\n"
00056     ".align 2\n"
00057     ".globl " ASMPREFIX "ARMCompilationCallback\n"
00058     ASMPREFIX "ARMCompilationCallback:\n"
00059     // Save caller saved registers since they may contain stuff
00060     // for the real target function right now. We have to act as if this
00061     // whole compilation callback doesn't exist as far as the caller is
00062     // concerned, so we can't just preserve the callee saved regs.
00063     "stmdb sp!, {r0, r1, r2, r3, lr}\n"
00064 #if (defined(__VFP_FP__) && !defined(__SOFTFP__))
00065     "vstmdb sp!, {d0, d1, d2, d3, d4, d5, d6, d7}\n"
00066 #endif
00067     // The LR contains the address of the stub function on entry.
00068     // pass it as the argument to the C part of the callback
00069     "mov  r0, lr\n"
00070     "sub  sp, sp, #4\n"
00071     // Call the C portion of the callback
00072     "bl   " ASMPREFIX "ARMCompilationCallbackC\n"
00073     "add  sp, sp, #4\n"
00074     // Restoring the LR to the return address of the function that invoked
00075     // the stub and de-allocating the stack space for it requires us to
00076     // swap the two saved LR values on the stack, as they're backwards
00077     // for what we need since the pop instruction has a pre-determined
00078     // order for the registers.
00079     //      +--------+
00080     //   0  | LR     | Original return address
00081     //      +--------+
00082     //   1  | LR     | Stub address (start of stub)
00083     // 2-5  | R3..R0 | Saved registers (we need to preserve all regs)
00084     // 6-20 | D0..D7 | Saved VFP registers
00085     //      +--------+
00086     //
00087 #if (defined(__VFP_FP__) && !defined(__SOFTFP__))
00088     // Restore VFP caller-saved registers.
00089     "vldmia sp!, {d0, d1, d2, d3, d4, d5, d6, d7}\n"
00090 #endif
00091     //
00092     //      We need to exchange the values in slots 0 and 1 so we can
00093     //      return to the address in slot 1 with the address in slot 0
00094     //      restored to the LR.
00095     "ldr  r0, [sp,#20]\n"
00096     "ldr  r1, [sp,#16]\n"
00097     "str  r1, [sp,#20]\n"
00098     "str  r0, [sp,#16]\n"
00099     // Return to the (newly modified) stub to invoke the real function.
00100     // The above twiddling of the saved return addresses allows us to
00101     // deallocate everything, including the LR the stub saved, with two
00102     // updating load instructions.
00103     "ldmia  sp!, {r0, r1, r2, r3, lr}\n"
00104     "ldr    pc, [sp], #4\n"
00105       );
00106 #else  // Not an ARM host
00107   void ARMCompilationCallback() {
00108     llvm_unreachable("Cannot call ARMCompilationCallback() on a non-ARM arch!");
00109   }
00110 #endif
00111 }
00112 
00113 /// ARMCompilationCallbackC - This is the target-specific function invoked
00114 /// by the function stub when we did not know the real target of a call.
00115 /// This function must locate the start of the stub or call site and pass
00116 /// it into the JIT compiler function.
00117 extern "C" void ARMCompilationCallbackC(intptr_t StubAddr) {
00118   // Get the address of the compiled code for this function.
00119   intptr_t NewVal = (intptr_t)JITCompilerFunction((void*)StubAddr);
00120 
00121   // Rewrite the call target... so that we don't end up here every time we
00122   // execute the call. We're replacing the first two instructions of the
00123   // stub with:
00124   //   ldr pc, [pc,#-4]
00125   //   <addr>
00126   if (!sys::Memory::setRangeWritable((void*)StubAddr, 8)) {
00127     llvm_unreachable("ERROR: Unable to mark stub writable");
00128   }
00129   *(intptr_t *)StubAddr = 0xe51ff004;  // ldr pc, [pc, #-4]
00130   *(intptr_t *)(StubAddr+4) = NewVal;
00131   if (!sys::Memory::setRangeExecutable((void*)StubAddr, 8)) {
00132     llvm_unreachable("ERROR: Unable to mark stub executable");
00133   }
00134 }
00135 
00136 TargetJITInfo::LazyResolverFn
00137 ARMJITInfo::getLazyResolverFunction(JITCompilerFn F) {
00138   JITCompilerFunction = F;
00139   return ARMCompilationCallback;
00140 }
00141 
00142 void *ARMJITInfo::emitGlobalValueIndirectSym(const GlobalValue *GV, void *Ptr,
00143                                              JITCodeEmitter &JCE) {
00144   uint8_t Buffer[4];
00145   uint8_t *Cur = Buffer;
00146   MachineCodeEmitter::emitWordLEInto(Cur, (intptr_t)Ptr);
00147   void *PtrAddr = JCE.allocIndirectGV(
00148       GV, Buffer, sizeof(Buffer), /*Alignment=*/4);
00149   addIndirectSymAddr(Ptr, (intptr_t)PtrAddr);
00150   return PtrAddr;
00151 }
00152 
00153 TargetJITInfo::StubLayout ARMJITInfo::getStubLayout() {
00154   // The stub contains up to 3 4-byte instructions, aligned at 4 bytes, and a
00155   // 4-byte address.  See emitFunctionStub for details.
00156   StubLayout Result = {16, 4};
00157   return Result;
00158 }
00159 
00160 void *ARMJITInfo::emitFunctionStub(const Function* F, void *Fn,
00161                                    JITCodeEmitter &JCE) {
00162   void *Addr;
00163   // If this is just a call to an external function, emit a branch instead of a
00164   // call.  The code is the same except for one bit of the last instruction.
00165   if (Fn != (void*)(intptr_t)ARMCompilationCallback) {
00166     // Branch to the corresponding function addr.
00167     if (IsPIC) {
00168       // The stub is 16-byte size and 4-aligned.
00169       intptr_t LazyPtr = getIndirectSymAddr(Fn);
00170       if (!LazyPtr) {
00171         // In PIC mode, the function stub is loading a lazy-ptr.
00172         LazyPtr= (intptr_t)emitGlobalValueIndirectSym((const GlobalValue*)F, Fn, JCE);
00173         DEBUG(if (F)
00174                 errs() << "JIT: Indirect symbol emitted at [" << LazyPtr
00175                        << "] for GV '" << F->getName() << "'\n";
00176               else
00177                 errs() << "JIT: Stub emitted at [" << LazyPtr
00178                        << "] for external function at '" << Fn << "'\n");
00179       }
00180       JCE.emitAlignment(4);
00181       Addr = (void*)JCE.getCurrentPCValue();
00182       if (!sys::Memory::setRangeWritable(Addr, 16)) {
00183         llvm_unreachable("ERROR: Unable to mark stub writable");
00184       }
00185       JCE.emitWordLE(0xe59fc004);            // ldr ip, [pc, #+4]
00186       JCE.emitWordLE(0xe08fc00c);            // L_func$scv: add ip, pc, ip
00187       JCE.emitWordLE(0xe59cf000);            // ldr pc, [ip]
00188       JCE.emitWordLE(LazyPtr - (intptr_t(Addr)+4+8));  // func - (L_func$scv+8)
00189       sys::Memory::InvalidateInstructionCache(Addr, 16);
00190       if (!sys::Memory::setRangeExecutable(Addr, 16)) {
00191         llvm_unreachable("ERROR: Unable to mark stub executable");
00192       }
00193     } else {
00194       // The stub is 8-byte size and 4-aligned.
00195       JCE.emitAlignment(4);
00196       Addr = (void*)JCE.getCurrentPCValue();
00197       if (!sys::Memory::setRangeWritable(Addr, 8)) {
00198         llvm_unreachable("ERROR: Unable to mark stub writable");
00199       }
00200       JCE.emitWordLE(0xe51ff004);    // ldr pc, [pc, #-4]
00201       JCE.emitWordLE((intptr_t)Fn);  // addr of function
00202       sys::Memory::InvalidateInstructionCache(Addr, 8);
00203       if (!sys::Memory::setRangeExecutable(Addr, 8)) {
00204         llvm_unreachable("ERROR: Unable to mark stub executable");
00205       }
00206     }
00207   } else {
00208     // The compilation callback will overwrite the first two words of this
00209     // stub with indirect branch instructions targeting the compiled code.
00210     // This stub sets the return address to restart the stub, so that
00211     // the new branch will be invoked when we come back.
00212     //
00213     // Branch and link to the compilation callback.
00214     // The stub is 16-byte size and 4-byte aligned.
00215     JCE.emitAlignment(4);
00216     Addr = (void*)JCE.getCurrentPCValue();
00217     if (!sys::Memory::setRangeWritable(Addr, 16)) {
00218       llvm_unreachable("ERROR: Unable to mark stub writable");
00219     }
00220     // Save LR so the callback can determine which stub called it.
00221     // The compilation callback is responsible for popping this prior
00222     // to returning.
00223     JCE.emitWordLE(0xe92d4000); // push {lr}
00224     // Set the return address to go back to the start of this stub.
00225     JCE.emitWordLE(0xe24fe00c); // sub lr, pc, #12
00226     // Invoke the compilation callback.
00227     JCE.emitWordLE(0xe51ff004); // ldr pc, [pc, #-4]
00228     // The address of the compilation callback.
00229     JCE.emitWordLE((intptr_t)ARMCompilationCallback);
00230     sys::Memory::InvalidateInstructionCache(Addr, 16);
00231     if (!sys::Memory::setRangeExecutable(Addr, 16)) {
00232       llvm_unreachable("ERROR: Unable to mark stub executable");
00233     }
00234   }
00235 
00236   return Addr;
00237 }
00238 
00239 intptr_t ARMJITInfo::resolveRelocDestAddr(MachineRelocation *MR) const {
00240   ARM::RelocationType RT = (ARM::RelocationType)MR->getRelocationType();
00241   switch (RT) {
00242   default:
00243     return (intptr_t)(MR->getResultPointer());
00244   case ARM::reloc_arm_pic_jt:
00245     // Destination address - jump table base.
00246     return (intptr_t)(MR->getResultPointer()) - MR->getConstantVal();
00247   case ARM::reloc_arm_jt_base:
00248     // Jump table base address.
00249     return getJumpTableBaseAddr(MR->getJumpTableIndex());
00250   case ARM::reloc_arm_cp_entry:
00251   case ARM::reloc_arm_vfp_cp_entry:
00252     // Constant pool entry address.
00253     return getConstantPoolEntryAddr(MR->getConstantPoolIndex());
00254   case ARM::reloc_arm_machine_cp_entry: {
00255     ARMConstantPoolValue *ACPV = (ARMConstantPoolValue*)MR->getConstantVal();
00256     assert((!ACPV->hasModifier() && !ACPV->mustAddCurrentAddress()) &&
00257            "Can't handle this machine constant pool entry yet!");
00258     intptr_t Addr = (intptr_t)(MR->getResultPointer());
00259     Addr -= getPCLabelAddr(ACPV->getLabelId()) + ACPV->getPCAdjustment();
00260     return Addr;
00261   }
00262   }
00263 }
00264 
00265 /// relocate - Before the JIT can run a block of code that has been emitted,
00266 /// it must rewrite the code to contain the actual addresses of any
00267 /// referenced global symbols.
00268 void ARMJITInfo::relocate(void *Function, MachineRelocation *MR,
00269                           unsigned NumRelocs, unsigned char* GOTBase) {
00270   for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
00271     void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
00272     intptr_t ResultPtr = resolveRelocDestAddr(MR);
00273     switch ((ARM::RelocationType)MR->getRelocationType()) {
00274     case ARM::reloc_arm_cp_entry:
00275     case ARM::reloc_arm_vfp_cp_entry:
00276     case ARM::reloc_arm_relative: {
00277       // It is necessary to calculate the correct PC relative value. We
00278       // subtract the base addr from the target addr to form a byte offset.
00279       ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
00280       // If the result is positive, set bit U(23) to 1.
00281       if (ResultPtr >= 0)
00282         *((intptr_t*)RelocPos) |= 1 << ARMII::U_BitShift;
00283       else {
00284         // Otherwise, obtain the absolute value and set bit U(23) to 0.
00285         *((intptr_t*)RelocPos) &= ~(1 << ARMII::U_BitShift);
00286         ResultPtr = - ResultPtr;
00287       }
00288       // Set the immed value calculated.
00289       // VFP immediate offset is multiplied by 4.
00290       if (MR->getRelocationType() == ARM::reloc_arm_vfp_cp_entry)
00291         ResultPtr = ResultPtr >> 2;
00292       *((intptr_t*)RelocPos) |= ResultPtr;
00293       // Set register Rn to PC (which is register 15 on all architectures).
00294       // FIXME: This avoids the need for register info in the JIT class.
00295       *((intptr_t*)RelocPos) |= 15 << ARMII::RegRnShift;
00296       break;
00297     }
00298     case ARM::reloc_arm_pic_jt:
00299     case ARM::reloc_arm_machine_cp_entry:
00300     case ARM::reloc_arm_absolute: {
00301       // These addresses have already been resolved.
00302       *((intptr_t*)RelocPos) |= (intptr_t)ResultPtr;
00303       break;
00304     }
00305     case ARM::reloc_arm_branch: {
00306       // It is necessary to calculate the correct value of signed_immed_24
00307       // field. We subtract the base addr from the target addr to form a
00308       // byte offset, which must be inside the range -33554432 and +33554428.
00309       // Then, we set the signed_immed_24 field of the instruction to bits
00310       // [25:2] of the byte offset. More details ARM-ARM p. A4-11.
00311       ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
00312       ResultPtr = (ResultPtr & 0x03FFFFFC) >> 2;
00313       assert(ResultPtr >= -33554432 && ResultPtr <= 33554428);
00314       *((intptr_t*)RelocPos) |= ResultPtr;
00315       break;
00316     }
00317     case ARM::reloc_arm_jt_base: {
00318       // JT base - (instruction addr + 8)
00319       ResultPtr = ResultPtr - (intptr_t)RelocPos - 8;
00320       *((intptr_t*)RelocPos) |= ResultPtr;
00321       break;
00322     }
00323     case ARM::reloc_arm_movw: {
00324       ResultPtr = ResultPtr & 0xFFFF;
00325       *((intptr_t*)RelocPos) |= ResultPtr & 0xFFF;
00326       *((intptr_t*)RelocPos) |= ((ResultPtr >> 12) & 0xF) << 16;
00327       break;
00328     }
00329     case ARM::reloc_arm_movt: {
00330       ResultPtr = (ResultPtr >> 16) & 0xFFFF;
00331       *((intptr_t*)RelocPos) |= ResultPtr & 0xFFF;
00332       *((intptr_t*)RelocPos) |= ((ResultPtr >> 12) & 0xF) << 16;
00333       break;
00334     }
00335     }
00336   }
00337 }
00338 
00339 void ARMJITInfo::Initialize(const MachineFunction &MF, bool isPIC) {
00340   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
00341   ConstPoolId2AddrMap.resize(AFI->getNumPICLabels());
00342   JumpTableId2AddrMap.resize(AFI->getNumJumpTables());
00343   IsPIC = isPIC;
00344 }