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