LLVM API Documentation

MCJIT.cpp
Go to the documentation of this file.
00001 //===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
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 #include "MCJIT.h"
00011 #include "llvm/ExecutionEngine/GenericValue.h"
00012 #include "llvm/ExecutionEngine/JITEventListener.h"
00013 #include "llvm/ExecutionEngine/JITMemoryManager.h"
00014 #include "llvm/ExecutionEngine/MCJIT.h"
00015 #include "llvm/ExecutionEngine/ObjectBuffer.h"
00016 #include "llvm/ExecutionEngine/ObjectImage.h"
00017 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
00018 #include "llvm/IR/DataLayout.h"
00019 #include "llvm/IR/DerivedTypes.h"
00020 #include "llvm/IR/Function.h"
00021 #include "llvm/MC/MCAsmInfo.h"
00022 #include "llvm/Support/DynamicLibrary.h"
00023 #include "llvm/Support/ErrorHandling.h"
00024 #include "llvm/Support/MemoryBuffer.h"
00025 #include "llvm/Support/MutexGuard.h"
00026 
00027 using namespace llvm;
00028 
00029 namespace {
00030 
00031 static struct RegisterJIT {
00032   RegisterJIT() { MCJIT::Register(); }
00033 } JITRegistrator;
00034 
00035 }
00036 
00037 extern "C" void LLVMLinkInMCJIT() {
00038 }
00039 
00040 ExecutionEngine *MCJIT::createJIT(Module *M,
00041                                   std::string *ErrorStr,
00042                                   RTDyldMemoryManager *MemMgr,
00043                                   bool GVsWithCode,
00044                                   TargetMachine *TM) {
00045   // Try to register the program as a source of symbols to resolve against.
00046   //
00047   // FIXME: Don't do this here.
00048   sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
00049 
00050   return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager(),
00051                    GVsWithCode);
00052 }
00053 
00054 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
00055              bool AllocateGVsWithCode)
00056   : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(MM), Dyld(MM),
00057     IsLoaded(false), M(m), ObjCache(0) {
00058 
00059   setDataLayout(TM->getDataLayout());
00060 }
00061 
00062 MCJIT::~MCJIT() {
00063   if (LoadedObject)
00064     NotifyFreeingObject(*LoadedObject.get());
00065   delete MemMgr;
00066   delete TM;
00067 }
00068 
00069 void MCJIT::setObjectCache(ObjectCache* NewCache) {
00070   ObjCache = NewCache;
00071 }
00072 
00073 ObjectBufferStream* MCJIT::emitObject(Module *m) {
00074   /// Currently, MCJIT only supports a single module and the module passed to
00075   /// this function call is expected to be the contained module.  The module
00076   /// is passed as a parameter here to prepare for multiple module support in
00077   /// the future.
00078   assert(M == m);
00079 
00080   // Get a thread lock to make sure we aren't trying to compile multiple times
00081   MutexGuard locked(lock);
00082 
00083   // FIXME: Track compilation state on a per-module basis when multiple modules
00084   //        are supported.
00085   // Re-compilation is not supported
00086   assert(!IsLoaded);
00087 
00088   PassManager PM;
00089 
00090   PM.add(new DataLayout(*TM->getDataLayout()));
00091 
00092   // The RuntimeDyld will take ownership of this shortly
00093   OwningPtr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
00094 
00095   // Turn the machine code intermediate representation into bytes in memory
00096   // that may be executed.
00097   if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(), false)) {
00098     report_fatal_error("Target does not support MC emission!");
00099   }
00100 
00101   // Initialize passes.
00102   PM.run(*m);
00103   // Flush the output buffer to get the generated code into memory
00104   CompiledObject->flush();
00105 
00106   // If we have an object cache, tell it about the new object.
00107   // Note that we're using the compiled image, not the loaded image (as below).
00108   if (ObjCache) {
00109     // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
00110     // to create a temporary object here and delete it after the call.
00111     OwningPtr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
00112     ObjCache->notifyObjectCompiled(m, MB.get());
00113   }
00114 
00115   return CompiledObject.take();
00116 }
00117 
00118 void MCJIT::loadObject(Module *M) {
00119 
00120   // Get a thread lock to make sure we aren't trying to load multiple times
00121   MutexGuard locked(lock);
00122 
00123   // FIXME: Track compilation state on a per-module basis when multiple modules
00124   //        are supported.
00125   // Re-compilation is not supported
00126   if (IsLoaded)
00127     return;
00128 
00129   OwningPtr<ObjectBuffer> ObjectToLoad;
00130   // Try to load the pre-compiled object from cache if possible
00131   if (0 != ObjCache) {
00132     OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObjectCopy(M));
00133     if (0 != PreCompiledObject.get())
00134       ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
00135   }
00136 
00137   // If the cache did not contain a suitable object, compile the object
00138   if (!ObjectToLoad) {
00139     ObjectToLoad.reset(emitObject(M));
00140     assert(ObjectToLoad.get() && "Compilation did not produce an object.");
00141   }
00142 
00143   // Load the object into the dynamic linker.
00144   // handing off ownership of the buffer
00145   LoadedObject.reset(Dyld.loadObject(ObjectToLoad.take()));
00146   if (!LoadedObject)
00147     report_fatal_error(Dyld.getErrorString());
00148 
00149   // Resolve any relocations.
00150   Dyld.resolveRelocations();
00151 
00152   // FIXME: Make this optional, maybe even move it to a JIT event listener
00153   LoadedObject->registerWithDebugger();
00154 
00155   NotifyObjectEmitted(*LoadedObject);
00156 
00157   // FIXME: Add support for per-module compilation state
00158   IsLoaded = true;
00159 }
00160 
00161 // FIXME: Add a parameter to identify which object is being finalized when
00162 // MCJIT supports multiple modules.
00163 // FIXME: Provide a way to separate code emission, relocations and page 
00164 // protection in the interface.
00165 void MCJIT::finalizeObject() {
00166   // If the module hasn't been compiled, just do that.
00167   if (!IsLoaded) {
00168     // If the call to Dyld.resolveRelocations() is removed from loadObject()
00169     // we'll need to do that here.
00170     loadObject(M);
00171   } else {
00172     // Resolve any relocations.
00173     Dyld.resolveRelocations();
00174   }
00175 
00176   StringRef EHData = Dyld.getEHFrameSection();
00177   if (!EHData.empty())
00178     MemMgr->registerEHFrames(EHData);
00179 
00180   // Set page permissions.
00181   MemMgr->finalizeMemory();
00182 }
00183 
00184 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
00185   report_fatal_error("not yet implemented");
00186 }
00187 
00188 void *MCJIT::getPointerToFunction(Function *F) {
00189   // FIXME: This should really return a uint64_t since it's a pointer in the
00190   // target address space, not our local address space. That's part of the
00191   // ExecutionEngine interface, though. Fix that when the old JIT finally
00192   // dies.
00193 
00194   // FIXME: Add support for per-module compilation state
00195   if (!IsLoaded)
00196     loadObject(M);
00197 
00198   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
00199     bool AbortOnFailure = !F->hasExternalWeakLinkage();
00200     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
00201     addGlobalMapping(F, Addr);
00202     return Addr;
00203   }
00204 
00205   // FIXME: Should the Dyld be retaining module information? Probably not.
00206   // FIXME: Should we be using the mangler for this? Probably.
00207   //
00208   // This is the accessor for the target address, so make sure to check the
00209   // load address of the symbol, not the local address.
00210   StringRef BaseName = F->getName();
00211   if (BaseName[0] == '\1')
00212     return (void*)Dyld.getSymbolLoadAddress(BaseName.substr(1));
00213   return (void*)Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
00214                                        + BaseName).str());
00215 }
00216 
00217 void *MCJIT::recompileAndRelinkFunction(Function *F) {
00218   report_fatal_error("not yet implemented");
00219 }
00220 
00221 void MCJIT::freeMachineCodeForFunction(Function *F) {
00222   report_fatal_error("not yet implemented");
00223 }
00224 
00225 GenericValue MCJIT::runFunction(Function *F,
00226                                 const std::vector<GenericValue> &ArgValues) {
00227   assert(F && "Function *F was null at entry to run()");
00228 
00229   void *FPtr = getPointerToFunction(F);
00230   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
00231   FunctionType *FTy = F->getFunctionType();
00232   Type *RetTy = FTy->getReturnType();
00233 
00234   assert((FTy->getNumParams() == ArgValues.size() ||
00235           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
00236          "Wrong number of arguments passed into function!");
00237   assert(FTy->getNumParams() == ArgValues.size() &&
00238          "This doesn't support passing arguments through varargs (yet)!");
00239 
00240   // Handle some common cases first.  These cases correspond to common `main'
00241   // prototypes.
00242   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
00243     switch (ArgValues.size()) {
00244     case 3:
00245       if (FTy->getParamType(0)->isIntegerTy(32) &&
00246           FTy->getParamType(1)->isPointerTy() &&
00247           FTy->getParamType(2)->isPointerTy()) {
00248         int (*PF)(int, char **, const char **) =
00249           (int(*)(int, char **, const char **))(intptr_t)FPtr;
00250 
00251         // Call the function.
00252         GenericValue rv;
00253         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
00254                                  (char **)GVTOP(ArgValues[1]),
00255                                  (const char **)GVTOP(ArgValues[2])));
00256         return rv;
00257       }
00258       break;
00259     case 2:
00260       if (FTy->getParamType(0)->isIntegerTy(32) &&
00261           FTy->getParamType(1)->isPointerTy()) {
00262         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
00263 
00264         // Call the function.
00265         GenericValue rv;
00266         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
00267                                  (char **)GVTOP(ArgValues[1])));
00268         return rv;
00269       }
00270       break;
00271     case 1:
00272       if (FTy->getNumParams() == 1 &&
00273           FTy->getParamType(0)->isIntegerTy(32)) {
00274         GenericValue rv;
00275         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
00276         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
00277         return rv;
00278       }
00279       break;
00280     }
00281   }
00282 
00283   // Handle cases where no arguments are passed first.
00284   if (ArgValues.empty()) {
00285     GenericValue rv;
00286     switch (RetTy->getTypeID()) {
00287     default: llvm_unreachable("Unknown return type for function call!");
00288     case Type::IntegerTyID: {
00289       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
00290       if (BitWidth == 1)
00291         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
00292       else if (BitWidth <= 8)
00293         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
00294       else if (BitWidth <= 16)
00295         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
00296       else if (BitWidth <= 32)
00297         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
00298       else if (BitWidth <= 64)
00299         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
00300       else
00301         llvm_unreachable("Integer types > 64 bits not supported");
00302       return rv;
00303     }
00304     case Type::VoidTyID:
00305       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
00306       return rv;
00307     case Type::FloatTyID:
00308       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
00309       return rv;
00310     case Type::DoubleTyID:
00311       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
00312       return rv;
00313     case Type::X86_FP80TyID:
00314     case Type::FP128TyID:
00315     case Type::PPC_FP128TyID:
00316       llvm_unreachable("long double not supported yet");
00317     case Type::PointerTyID:
00318       return PTOGV(((void*(*)())(intptr_t)FPtr)());
00319     }
00320   }
00321 
00322   llvm_unreachable("Full-featured argument passing not supported yet!");
00323 }
00324 
00325 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
00326                                        bool AbortOnFailure) {
00327   // FIXME: Add support for per-module compilation state
00328   if (!IsLoaded)
00329     loadObject(M);
00330 
00331   if (!isSymbolSearchingDisabled() && MemMgr) {
00332     void *ptr = MemMgr->getPointerToNamedFunction(Name, false);
00333     if (ptr)
00334       return ptr;
00335   }
00336 
00337   /// If a LazyFunctionCreator is installed, use it to get/create the function.
00338   if (LazyFunctionCreator)
00339     if (void *RP = LazyFunctionCreator(Name))
00340       return RP;
00341 
00342   if (AbortOnFailure) {
00343     report_fatal_error("Program used external function '"+Name+
00344                        "' which could not be resolved!");
00345   }
00346   return 0;
00347 }
00348 
00349 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
00350   if (L == NULL)
00351     return;
00352   MutexGuard locked(lock);
00353   EventListeners.push_back(L);
00354 }
00355 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
00356   if (L == NULL)
00357     return;
00358   MutexGuard locked(lock);
00359   SmallVector<JITEventListener*, 2>::reverse_iterator I=
00360       std::find(EventListeners.rbegin(), EventListeners.rend(), L);
00361   if (I != EventListeners.rend()) {
00362     std::swap(*I, EventListeners.back());
00363     EventListeners.pop_back();
00364   }
00365 }
00366 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
00367   MutexGuard locked(lock);
00368   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
00369     EventListeners[I]->NotifyObjectEmitted(Obj);
00370   }
00371 }
00372 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
00373   MutexGuard locked(lock);
00374   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
00375     EventListeners[I]->NotifyFreeingObject(Obj);
00376   }
00377 }