LLVM API Documentation
00001 //===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===// 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 defines the abstract interface that implements execution support 00011 // for LLVM. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #ifndef LLVM_EXECUTION_ENGINE_H 00016 #define LLVM_EXECUTION_ENGINE_H 00017 00018 #include <vector> 00019 #include <map> 00020 #include <string> 00021 #include "llvm/ADT/SmallVector.h" 00022 #include "llvm/System/Mutex.h" 00023 #include "llvm/Target/TargetMachine.h" 00024 00025 namespace llvm { 00026 00027 struct GenericValue; 00028 class Constant; 00029 class Function; 00030 class GlobalVariable; 00031 class GlobalValue; 00032 class JITEventListener; 00033 class JITMemoryManager; 00034 class MachineCodeInfo; 00035 class Module; 00036 class ModuleProvider; 00037 class MutexGuard; 00038 class TargetData; 00039 class Type; 00040 template<typename> class AssertingVH; 00041 00042 class ExecutionEngineState { 00043 private: 00044 /// GlobalAddressMap - A mapping between LLVM global values and their 00045 /// actualized version... 00046 std::map<AssertingVH<const GlobalValue>, void *> GlobalAddressMap; 00047 00048 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap, 00049 /// used to convert raw addresses into the LLVM global value that is emitted 00050 /// at the address. This map is not computed unless getGlobalValueAtAddress 00051 /// is called at some point. 00052 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap; 00053 00054 public: 00055 std::map<AssertingVH<const GlobalValue>, void *> & 00056 getGlobalAddressMap(const MutexGuard &) { 00057 return GlobalAddressMap; 00058 } 00059 00060 std::map<void*, AssertingVH<const GlobalValue> > & 00061 getGlobalAddressReverseMap(const MutexGuard &) { 00062 return GlobalAddressReverseMap; 00063 } 00064 }; 00065 00066 00067 class ExecutionEngine { 00068 const TargetData *TD; 00069 ExecutionEngineState state; 00070 bool LazyCompilationDisabled; 00071 bool GVCompilationDisabled; 00072 bool SymbolSearchingDisabled; 00073 bool DlsymStubsEnabled; 00074 00075 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor. 00076 00077 protected: 00078 /// Modules - This is a list of ModuleProvider's that we are JIT'ing from. We 00079 /// use a smallvector to optimize for the case where there is only one module. 00080 SmallVector<ModuleProvider*, 1> Modules; 00081 00082 void setTargetData(const TargetData *td) { 00083 TD = td; 00084 } 00085 00086 /// getMemoryforGV - Allocate memory for a global variable. 00087 virtual char* getMemoryForGV(const GlobalVariable* GV); 00088 00089 // To avoid having libexecutionengine depend on the JIT and interpreter 00090 // libraries, the JIT and Interpreter set these functions to ctor pointers 00091 // at startup time if they are linked in. 00092 static ExecutionEngine *(*JITCtor)(ModuleProvider *MP, 00093 std::string *ErrorStr, 00094 JITMemoryManager *JMM, 00095 CodeGenOpt::Level OptLevel, 00096 bool GVsWithCode); 00097 static ExecutionEngine *(*InterpCtor)(ModuleProvider *MP, 00098 std::string *ErrorStr); 00099 00100 /// LazyFunctionCreator - If an unknown function is needed, this function 00101 /// pointer is invoked to create it. If this returns null, the JIT will abort. 00102 void* (*LazyFunctionCreator)(const std::string &); 00103 00104 /// ExceptionTableRegister - If Exception Handling is set, the JIT will 00105 /// register dwarf tables with this function 00106 typedef void (*EERegisterFn)(void*); 00107 static EERegisterFn ExceptionTableRegister; 00108 00109 public: 00110 /// lock - This lock is protects the ExecutionEngine, JIT, JITResolver and 00111 /// JITEmitter classes. It must be held while changing the internal state of 00112 /// any of those classes. 00113 sys::Mutex lock; // Used to make this class and subclasses thread-safe 00114 00115 //===--------------------------------------------------------------------===// 00116 // ExecutionEngine Startup 00117 //===--------------------------------------------------------------------===// 00118 00119 virtual ~ExecutionEngine(); 00120 00121 /// create - This is the factory method for creating an execution engine which 00122 /// is appropriate for the current machine. This takes ownership of the 00123 /// module provider. 00124 static ExecutionEngine *create(ModuleProvider *MP, 00125 bool ForceInterpreter = false, 00126 std::string *ErrorStr = 0, 00127 CodeGenOpt::Level OptLevel = 00128 CodeGenOpt::Default, 00129 // Allocating globals with code breaks 00130 // freeMachineCodeForFunction and is probably 00131 // unsafe and bad for performance. However, 00132 // we have clients who depend on this 00133 // behavior, so we must support it. 00134 // Eventually, when we're willing to break 00135 // some backwards compatability, this flag 00136 // should be flipped to false, so that by 00137 // default freeMachineCodeForFunction works. 00138 bool GVsWithCode = true); 00139 00140 /// create - This is the factory method for creating an execution engine which 00141 /// is appropriate for the current machine. This takes ownership of the 00142 /// module. 00143 static ExecutionEngine *create(Module *M); 00144 00145 /// createJIT - This is the factory method for creating a JIT for the current 00146 /// machine, it does not fall back to the interpreter. This takes ownership 00147 /// of the ModuleProvider and JITMemoryManager if successful. 00148 /// 00149 /// Clients should make sure to initialize targets prior to calling this 00150 /// function. 00151 static ExecutionEngine *createJIT(ModuleProvider *MP, 00152 std::string *ErrorStr = 0, 00153 JITMemoryManager *JMM = 0, 00154 CodeGenOpt::Level OptLevel = 00155 CodeGenOpt::Default, 00156 bool GVsWithCode = true); 00157 00158 /// addModuleProvider - Add a ModuleProvider to the list of modules that we 00159 /// can JIT from. Note that this takes ownership of the ModuleProvider: when 00160 /// the ExecutionEngine is destroyed, it destroys the MP as well. 00161 virtual void addModuleProvider(ModuleProvider *P) { 00162 Modules.push_back(P); 00163 } 00164 00165 //===----------------------------------------------------------------------===// 00166 00167 const TargetData *getTargetData() const { return TD; } 00168 00169 00170 /// removeModuleProvider - Remove a ModuleProvider from the list of modules. 00171 /// Relases the Module from the ModuleProvider, materializing it in the 00172 /// process, and returns the materialized Module. 00173 virtual Module* removeModuleProvider(ModuleProvider *P, 00174 std::string *ErrInfo = 0); 00175 00176 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules, 00177 /// and deletes the ModuleProvider and owned Module. Avoids materializing 00178 /// the underlying module. 00179 virtual void deleteModuleProvider(ModuleProvider *P,std::string *ErrInfo = 0); 00180 00181 /// FindFunctionNamed - Search all of the active modules to find the one that 00182 /// defines FnName. This is very slow operation and shouldn't be used for 00183 /// general code. 00184 Function *FindFunctionNamed(const char *FnName); 00185 00186 /// runFunction - Execute the specified function with the specified arguments, 00187 /// and return the result. 00188 /// 00189 virtual GenericValue runFunction(Function *F, 00190 const std::vector<GenericValue> &ArgValues) = 0; 00191 00192 /// runStaticConstructorsDestructors - This method is used to execute all of 00193 /// the static constructors or destructors for a program, depending on the 00194 /// value of isDtors. 00195 void runStaticConstructorsDestructors(bool isDtors); 00196 /// runStaticConstructorsDestructors - This method is used to execute all of 00197 /// the static constructors or destructors for a module, depending on the 00198 /// value of isDtors. 00199 void runStaticConstructorsDestructors(Module *module, bool isDtors); 00200 00201 00202 /// runFunctionAsMain - This is a helper function which wraps runFunction to 00203 /// handle the common task of starting up main with the specified argc, argv, 00204 /// and envp parameters. 00205 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv, 00206 const char * const * envp); 00207 00208 00209 /// addGlobalMapping - Tell the execution engine that the specified global is 00210 /// at the specified location. This is used internally as functions are JIT'd 00211 /// and as global variables are laid out in memory. It can and should also be 00212 /// used by clients of the EE that want to have an LLVM global overlay 00213 /// existing data in memory. After adding a mapping for GV, you must not 00214 /// destroy it until you've removed the mapping. 00215 void addGlobalMapping(const GlobalValue *GV, void *Addr); 00216 00217 /// clearAllGlobalMappings - Clear all global mappings and start over again 00218 /// use in dynamic compilation scenarios when you want to move globals 00219 void clearAllGlobalMappings(); 00220 00221 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a 00222 /// particular module, because it has been removed from the JIT. 00223 void clearGlobalMappingsFromModule(Module *M); 00224 00225 /// updateGlobalMapping - Replace an existing mapping for GV with a new 00226 /// address. This updates both maps as required. If "Addr" is null, the 00227 /// entry for the global is removed from the mappings. This returns the old 00228 /// value of the pointer, or null if it was not in the map. 00229 void *updateGlobalMapping(const GlobalValue *GV, void *Addr); 00230 00231 /// getPointerToGlobalIfAvailable - This returns the address of the specified 00232 /// global value if it is has already been codegen'd, otherwise it returns 00233 /// null. 00234 /// 00235 void *getPointerToGlobalIfAvailable(const GlobalValue *GV); 00236 00237 /// getPointerToGlobal - This returns the address of the specified global 00238 /// value. This may involve code generation if it's a function. After 00239 /// getting a pointer to GV, it and all globals it transitively refers to have 00240 /// been passed to addGlobalMapping. You must clear the mapping for each 00241 /// referred-to global before destroying it. If a referred-to global RTG is a 00242 /// function and this ExecutionEngine is a JIT compiler, calling 00243 /// updateGlobalMapping(RTG, 0) will leak the function's machine code, so you 00244 /// should call freeMachineCodeForFunction(RTG) instead. Note that 00245 /// optimizations can move and delete non-external GlobalValues without 00246 /// notifying the ExecutionEngine. 00247 /// 00248 void *getPointerToGlobal(const GlobalValue *GV); 00249 00250 /// getPointerToFunction - The different EE's represent function bodies in 00251 /// different ways. They should each implement this to say what a function 00252 /// pointer should look like. See getPointerToGlobal for the requirements on 00253 /// destroying F and any GlobalValues it refers to. 00254 /// 00255 virtual void *getPointerToFunction(Function *F) = 0; 00256 00257 /// getPointerToFunctionOrStub - If the specified function has been 00258 /// code-gen'd, return a pointer to the function. If not, compile it, or use 00259 /// a stub to implement lazy compilation if available. See getPointerToGlobal 00260 /// for the requirements on destroying F and any GlobalValues it refers to. 00261 /// 00262 virtual void *getPointerToFunctionOrStub(Function *F) { 00263 // Default implementation, just codegen the function. 00264 return getPointerToFunction(F); 00265 } 00266 00267 // The JIT overrides a version that actually does this. 00268 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { } 00269 00270 /// getGlobalValueAtAddress - Return the LLVM global value object that starts 00271 /// at the specified address. 00272 /// 00273 const GlobalValue *getGlobalValueAtAddress(void *Addr); 00274 00275 00276 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr, 00277 const Type *Ty); 00278 void InitializeMemory(const Constant *Init, void *Addr); 00279 00280 /// recompileAndRelinkFunction - This method is used to force a function 00281 /// which has already been compiled to be compiled again, possibly 00282 /// after it has been modified. Then the entry to the old copy is overwritten 00283 /// with a branch to the new copy. If there was no old copy, this acts 00284 /// just like VM::getPointerToFunction(). 00285 /// 00286 virtual void *recompileAndRelinkFunction(Function *F) = 0; 00287 00288 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine 00289 /// corresponding to the machine code emitted to execute this function, useful 00290 /// for garbage-collecting generated code. 00291 /// 00292 virtual void freeMachineCodeForFunction(Function *F) = 0; 00293 00294 /// getOrEmitGlobalVariable - Return the address of the specified global 00295 /// variable, possibly emitting it to memory if needed. This is used by the 00296 /// Emitter. See getPointerToGlobal for the requirements on destroying GV and 00297 /// any GlobalValues it refers to. 00298 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) { 00299 return getPointerToGlobal((GlobalValue*)GV); 00300 } 00301 00302 /// Registers a listener to be called back on various events within 00303 /// the JIT. See JITEventListener.h for more details. Does not 00304 /// take ownership of the argument. The argument may be NULL, in 00305 /// which case these functions do nothing. 00306 virtual void RegisterJITEventListener(JITEventListener *) {} 00307 virtual void UnregisterJITEventListener(JITEventListener *) {} 00308 00309 /// DisableLazyCompilation - If called, the JIT will abort if lazy compilation 00310 /// is ever attempted. 00311 void DisableLazyCompilation(bool Disabled = true) { 00312 LazyCompilationDisabled = Disabled; 00313 } 00314 bool isLazyCompilationDisabled() const { 00315 return LazyCompilationDisabled; 00316 } 00317 00318 /// DisableGVCompilation - If called, the JIT will abort if it's asked to 00319 /// allocate space and populate a GlobalVariable that is not internal to 00320 /// the module. 00321 void DisableGVCompilation(bool Disabled = true) { 00322 GVCompilationDisabled = Disabled; 00323 } 00324 bool isGVCompilationDisabled() const { 00325 return GVCompilationDisabled; 00326 } 00327 00328 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown 00329 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to 00330 /// resolve symbols in a custom way. 00331 void DisableSymbolSearching(bool Disabled = true) { 00332 SymbolSearchingDisabled = Disabled; 00333 } 00334 bool isSymbolSearchingDisabled() const { 00335 return SymbolSearchingDisabled; 00336 } 00337 00338 /// EnableDlsymStubs - 00339 void EnableDlsymStubs(bool Enabled = true) { 00340 DlsymStubsEnabled = Enabled; 00341 } 00342 bool areDlsymStubsEnabled() const { 00343 return DlsymStubsEnabled; 00344 } 00345 00346 /// InstallLazyFunctionCreator - If an unknown function is needed, the 00347 /// specified function pointer is invoked to create it. If it returns null, 00348 /// the JIT will abort. 00349 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) { 00350 LazyFunctionCreator = P; 00351 } 00352 00353 /// InstallExceptionTableRegister - The JIT will use the given function 00354 /// to register the exception tables it generates. 00355 static void InstallExceptionTableRegister(void (*F)(void*)) { 00356 ExceptionTableRegister = F; 00357 } 00358 00359 /// RegisterTable - Registers the given pointer as an exception table. It uses 00360 /// the ExceptionTableRegister function. 00361 static void RegisterTable(void* res) { 00362 if (ExceptionTableRegister) 00363 ExceptionTableRegister(res); 00364 } 00365 00366 protected: 00367 explicit ExecutionEngine(ModuleProvider *P); 00368 00369 void emitGlobals(); 00370 00371 // EmitGlobalVariable - This method emits the specified global variable to the 00372 // address specified in GlobalAddresses, or allocates new memory if it's not 00373 // already in the map. 00374 void EmitGlobalVariable(const GlobalVariable *GV); 00375 00376 GenericValue getConstantValue(const Constant *C); 00377 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr, 00378 const Type *Ty); 00379 }; 00380 00381 namespace EngineKind { 00382 // These are actually bitmasks that get or-ed together. 00383 enum Kind { 00384 JIT = 0x1, 00385 Interpreter = 0x2 00386 }; 00387 const static Kind Either = (Kind)(JIT | Interpreter); 00388 } 00389 00390 /// EngineBuilder - Builder class for ExecutionEngines. Use this by 00391 /// stack-allocating a builder, chaining the various set* methods, and 00392 /// terminating it with a .create() call. 00393 class EngineBuilder { 00394 00395 private: 00396 ModuleProvider *MP; 00397 EngineKind::Kind WhichEngine; 00398 std::string *ErrorStr; 00399 CodeGenOpt::Level OptLevel; 00400 JITMemoryManager *JMM; 00401 bool AllocateGVsWithCode; 00402 00403 /// InitEngine - Does the common initialization of default options. 00404 /// 00405 void InitEngine() { 00406 WhichEngine = EngineKind::Either; 00407 ErrorStr = NULL; 00408 OptLevel = CodeGenOpt::Default; 00409 JMM = NULL; 00410 AllocateGVsWithCode = false; 00411 } 00412 00413 public: 00414 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and 00415 /// is successful, the created engine takes ownership of the module 00416 /// provider. 00417 EngineBuilder(ModuleProvider *mp) : MP(mp) { 00418 InitEngine(); 00419 } 00420 00421 /// EngineBuilder - Overloaded constructor that automatically creates an 00422 /// ExistingModuleProvider for an existing module. 00423 EngineBuilder(Module *m); 00424 00425 /// setEngineKind - Controls whether the user wants the interpreter, the JIT, 00426 /// or whichever engine works. This option defaults to EngineKind::Either. 00427 EngineBuilder &setEngineKind(EngineKind::Kind w) { 00428 WhichEngine = w; 00429 return *this; 00430 } 00431 00432 /// setJITMemoryManager - Sets the memory manager to use. This allows 00433 /// clients to customize their memory allocation policies. If create() is 00434 /// called and is successful, the created engine takes ownership of the 00435 /// memory manager. This option defaults to NULL. 00436 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) { 00437 JMM = jmm; 00438 return *this; 00439 } 00440 00441 /// setErrorStr - Set the error string to write to on error. This option 00442 /// defaults to NULL. 00443 EngineBuilder &setErrorStr(std::string *e) { 00444 ErrorStr = e; 00445 return *this; 00446 } 00447 00448 /// setOptLevel - Set the optimization level for the JIT. This option 00449 /// defaults to CodeGenOpt::Default. 00450 EngineBuilder &setOptLevel(CodeGenOpt::Level l) { 00451 OptLevel = l; 00452 return *this; 00453 } 00454 00455 /// setAllocateGVsWithCode - Sets whether global values should be allocated 00456 /// into the same buffer as code. For most applications this should be set 00457 /// to false. Allocating globals with code breaks freeMachineCodeForFunction 00458 /// and is probably unsafe and bad for performance. However, we have clients 00459 /// who depend on this behavior, so we must support it. This option defaults 00460 /// to false so that users of the new API can safely use the new memory 00461 /// manager and free machine code. 00462 EngineBuilder &setAllocateGVsWithCode(bool a) { 00463 AllocateGVsWithCode = a; 00464 return *this; 00465 } 00466 00467 ExecutionEngine *create(); 00468 00469 }; 00470 00471 } // End llvm namespace 00472 00473 #endif