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