1 //===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the abstract interface that implements execution support 11 // for LLVM. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_EXECUTION_ENGINE_H 16 #define LLVM_EXECUTION_ENGINE_H 17 18 #include <vector> 19 #include <map> 20 #include <string> 21 #include "llvm/MC/MCCodeGenInfo.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/ValueMap.h" 25 #include "llvm/ADT/DenseMap.h" 26 #include "llvm/Support/ValueHandle.h" 27 #include "llvm/Support/Mutex.h" 28 #include "llvm/Target/TargetMachine.h" 29 30 namespace llvm { 31 32 struct GenericValue; 33 class Constant; 34 class ExecutionEngine; 35 class Function; 36 class GlobalVariable; 37 class GlobalValue; 38 class JITEventListener; 39 class JITMemoryManager; 40 class MachineCodeInfo; 41 class Module; 42 class MutexGuard; 43 class TargetData; 44 class Type; 45 46 /// \brief Helper class for helping synchronize access to the global address map 47 /// table. 48 class ExecutionEngineState { 49 public: 50 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> { 51 typedef ExecutionEngineState *ExtraData; 52 static sys::Mutex *getMutex(ExecutionEngineState *EES); 53 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old); 54 static void onRAUW(ExecutionEngineState *, const GlobalValue *, 55 const GlobalValue *); 56 }; 57 58 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig> 59 GlobalAddressMapTy; 60 61 private: 62 ExecutionEngine &EE; 63 64 /// GlobalAddressMap - A mapping between LLVM global values and their 65 /// actualized version... 66 GlobalAddressMapTy GlobalAddressMap; 67 68 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap, 69 /// used to convert raw addresses into the LLVM global value that is emitted 70 /// at the address. This map is not computed unless getGlobalValueAtAddress 71 /// is called at some point. 72 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap; 73 74 public: 75 ExecutionEngineState(ExecutionEngine &EE); 76 77 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) { 78 return GlobalAddressMap; 79 } 80 81 std::map<void*, AssertingVH<const GlobalValue> > & 82 getGlobalAddressReverseMap(const MutexGuard &) { 83 return GlobalAddressReverseMap; 84 } 85 86 /// \brief Erase an entry from the mapping table. 87 /// 88 /// \returns The address that \arg ToUnmap was happed to. 89 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap); 90 }; 91 92 /// \brief Abstract interface for implementation execution of LLVM modules, 93 /// designed to support both interpreter and just-in-time (JIT) compiler 94 /// implementations. 95 class ExecutionEngine { 96 /// The state object holding the global address mapping, which must be 97 /// accessed synchronously. 98 // 99 // FIXME: There is no particular need the entire map needs to be 100 // synchronized. Wouldn't a reader-writer design be better here? 101 ExecutionEngineState EEState; 102 103 /// The target data for the platform for which execution is being performed. 104 const TargetData *TD; 105 106 /// Whether lazy JIT compilation is enabled. 107 bool CompilingLazily; 108 109 /// Whether JIT compilation of external global variables is allowed. 110 bool GVCompilationDisabled; 111 112 /// Whether the JIT should perform lookups of external symbols (e.g., 113 /// using dlsym). 114 bool SymbolSearchingDisabled; 115 116 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor. 117 118 protected: 119 /// The list of Modules that we are JIT'ing from. We use a SmallVector to 120 /// optimize for the case where there is only one module. 121 SmallVector<Module*, 1> Modules; 122 123 void setTargetData(const TargetData *td) { 124 TD = td; 125 } 126 127 /// getMemoryforGV - Allocate memory for a global variable. 128 virtual char *getMemoryForGV(const GlobalVariable *GV); 129 130 // To avoid having libexecutionengine depend on the JIT and interpreter 131 // libraries, the execution engine implementations set these functions to ctor 132 // pointers at startup time if they are linked in. 133 static ExecutionEngine *(*JITCtor)( 134 Module *M, 135 std::string *ErrorStr, 136 JITMemoryManager *JMM, 137 CodeGenOpt::Level OptLevel, 138 bool GVsWithCode, 139 TargetMachine *TM); 140 static ExecutionEngine *(*MCJITCtor)( 141 Module *M, 142 std::string *ErrorStr, 143 JITMemoryManager *JMM, 144 CodeGenOpt::Level OptLevel, 145 bool GVsWithCode, 146 TargetMachine *TM); 147 static ExecutionEngine *(*InterpCtor)(Module *M, 148 std::string *ErrorStr); 149 150 /// LazyFunctionCreator - If an unknown function is needed, this function 151 /// pointer is invoked to create it. If this returns null, the JIT will 152 /// abort. 153 void *(*LazyFunctionCreator)(const std::string &); 154 155 /// ExceptionTableRegister - If Exception Handling is set, the JIT will 156 /// register dwarf tables with this function. 157 typedef void (*EERegisterFn)(void*); 158 EERegisterFn ExceptionTableRegister; 159 EERegisterFn ExceptionTableDeregister; 160 /// This maps functions to their exception tables frames. 161 DenseMap<const Function*, void*> AllExceptionTables; 162 163 164 public: 165 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and 166 /// JITEmitter classes. It must be held while changing the internal state of 167 /// any of those classes. 168 sys::Mutex lock; 169 170 //===--------------------------------------------------------------------===// 171 // ExecutionEngine Startup 172 //===--------------------------------------------------------------------===// 173 174 virtual ~ExecutionEngine(); 175 176 /// create - This is the factory method for creating an execution engine which 177 /// is appropriate for the current machine. This takes ownership of the 178 /// module. 179 /// 180 /// \param GVsWithCode - Allocating globals with code breaks 181 /// freeMachineCodeForFunction and is probably unsafe and bad for performance. 182 /// However, we have clients who depend on this behavior, so we must support 183 /// it. Eventually, when we're willing to break some backwards compatibility, 184 /// this flag should be flipped to false, so that by default 185 /// freeMachineCodeForFunction works. 186 static ExecutionEngine *create(Module *M, 187 bool ForceInterpreter = false, 188 std::string *ErrorStr = 0, 189 CodeGenOpt::Level OptLevel = 190 CodeGenOpt::Default, 191 bool GVsWithCode = true); 192 193 /// createJIT - This is the factory method for creating a JIT for the current 194 /// machine, it does not fall back to the interpreter. This takes ownership 195 /// of the Module and JITMemoryManager if successful. 196 /// 197 /// Clients should make sure to initialize targets prior to calling this 198 /// function. 199 static ExecutionEngine *createJIT(Module *M, 200 std::string *ErrorStr = 0, 201 JITMemoryManager *JMM = 0, 202 CodeGenOpt::Level OptLevel = 203 CodeGenOpt::Default, 204 bool GVsWithCode = true, 205 Reloc::Model RM = Reloc::Default, 206 CodeModel::Model CMM = 207 CodeModel::Default); 208 209 /// addModule - Add a Module to the list of modules that we can JIT from. 210 /// Note that this takes ownership of the Module: when the ExecutionEngine is 211 /// destroyed, it destroys the Module as well. 212 virtual void addModule(Module *M) { 213 Modules.push_back(M); 214 } 215 216 //===--------------------------------------------------------------------===// 217 218 const TargetData *getTargetData() const { return TD; } 219 220 /// removeModule - Remove a Module from the list of modules. Returns true if 221 /// M is found. 222 virtual bool removeModule(Module *M); 223 224 /// FindFunctionNamed - Search all of the active modules to find the one that 225 /// defines FnName. This is very slow operation and shouldn't be used for 226 /// general code. 227 Function *FindFunctionNamed(const char *FnName); 228 229 /// runFunction - Execute the specified function with the specified arguments, 230 /// and return the result. 231 virtual GenericValue runFunction(Function *F, 232 const std::vector<GenericValue> &ArgValues) = 0; 233 234 /// runStaticConstructorsDestructors - This method is used to execute all of 235 /// the static constructors or destructors for a program. 236 /// 237 /// \param isDtors - Run the destructors instead of constructors. 238 void runStaticConstructorsDestructors(bool isDtors); 239 240 /// runStaticConstructorsDestructors - This method is used to execute all of 241 /// the static constructors or destructors for a particular module. 242 /// 243 /// \param isDtors - Run the destructors instead of constructors. 244 void runStaticConstructorsDestructors(Module *module, bool isDtors); 245 246 247 /// runFunctionAsMain - This is a helper function which wraps runFunction to 248 /// handle the common task of starting up main with the specified argc, argv, 249 /// and envp parameters. 250 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv, 251 const char * const * envp); 252 253 254 /// addGlobalMapping - Tell the execution engine that the specified global is 255 /// at the specified location. This is used internally as functions are JIT'd 256 /// and as global variables are laid out in memory. It can and should also be 257 /// used by clients of the EE that want to have an LLVM global overlay 258 /// existing data in memory. Mappings are automatically removed when their 259 /// GlobalValue is destroyed. 260 void addGlobalMapping(const GlobalValue *GV, void *Addr); 261 262 /// clearAllGlobalMappings - Clear all global mappings and start over again, 263 /// for use in dynamic compilation scenarios to move globals. 264 void clearAllGlobalMappings(); 265 266 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a 267 /// particular module, because it has been removed from the JIT. 268 void clearGlobalMappingsFromModule(Module *M); 269 270 /// updateGlobalMapping - Replace an existing mapping for GV with a new 271 /// address. This updates both maps as required. If "Addr" is null, the 272 /// entry for the global is removed from the mappings. This returns the old 273 /// value of the pointer, or null if it was not in the map. 274 void *updateGlobalMapping(const GlobalValue *GV, void *Addr); 275 276 /// getPointerToGlobalIfAvailable - This returns the address of the specified 277 /// global value if it is has already been codegen'd, otherwise it returns 278 /// null. 279 void *getPointerToGlobalIfAvailable(const GlobalValue *GV); 280 281 /// getPointerToGlobal - This returns the address of the specified global 282 /// value. This may involve code generation if it's a function. 283 void *getPointerToGlobal(const GlobalValue *GV); 284 285 /// getPointerToFunction - The different EE's represent function bodies in 286 /// different ways. They should each implement this to say what a function 287 /// pointer should look like. When F is destroyed, the ExecutionEngine will 288 /// remove its global mapping and free any machine code. Be sure no threads 289 /// are running inside F when that happens. 290 virtual void *getPointerToFunction(Function *F) = 0; 291 292 /// getPointerToBasicBlock - The different EE's represent basic blocks in 293 /// different ways. Return the representation for a blockaddress of the 294 /// specified block. 295 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0; 296 297 /// getPointerToFunctionOrStub - If the specified function has been 298 /// code-gen'd, return a pointer to the function. If not, compile it, or use 299 /// a stub to implement lazy compilation if available. See 300 /// getPointerToFunction for the requirements on destroying F. 301 virtual void *getPointerToFunctionOrStub(Function *F) { 302 // Default implementation, just codegen the function. 303 return getPointerToFunction(F); 304 } 305 306 // The JIT overrides a version that actually does this. 307 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { } 308 309 /// getGlobalValueAtAddress - Return the LLVM global value object that starts 310 /// at the specified address. 311 /// 312 const GlobalValue *getGlobalValueAtAddress(void *Addr); 313 314 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. 315 /// Ptr is the address of the memory at which to store Val, cast to 316 /// GenericValue *. It is not a pointer to a GenericValue containing the 317 /// address at which to store Val. 318 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr, 319 Type *Ty); 320 321 void InitializeMemory(const Constant *Init, void *Addr); 322 323 /// recompileAndRelinkFunction - This method is used to force a function which 324 /// has already been compiled to be compiled again, possibly after it has been 325 /// modified. Then the entry to the old copy is overwritten with a branch to 326 /// the new copy. If there was no old copy, this acts just like 327 /// VM::getPointerToFunction(). 328 virtual void *recompileAndRelinkFunction(Function *F) = 0; 329 330 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine 331 /// corresponding to the machine code emitted to execute this function, useful 332 /// for garbage-collecting generated code. 333 virtual void freeMachineCodeForFunction(Function *F) = 0; 334 335 /// getOrEmitGlobalVariable - Return the address of the specified global 336 /// variable, possibly emitting it to memory if needed. This is used by the 337 /// Emitter. 338 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) { 339 return getPointerToGlobal((GlobalValue*)GV); 340 } 341 342 /// Registers a listener to be called back on various events within 343 /// the JIT. See JITEventListener.h for more details. Does not 344 /// take ownership of the argument. The argument may be NULL, in 345 /// which case these functions do nothing. 346 virtual void RegisterJITEventListener(JITEventListener *) {} 347 virtual void UnregisterJITEventListener(JITEventListener *) {} 348 349 /// DisableLazyCompilation - When lazy compilation is off (the default), the 350 /// JIT will eagerly compile every function reachable from the argument to 351 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only 352 /// compile the one function and emit stubs to compile the rest when they're 353 /// first called. If lazy compilation is turned off again while some lazy 354 /// stubs are still around, and one of those stubs is called, the program will 355 /// abort. 356 /// 357 /// In order to safely compile lazily in a threaded program, the user must 358 /// ensure that 1) only one thread at a time can call any particular lazy 359 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock 360 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a 361 /// lazy stub. See http://llvm.org/PR5184 for details. 362 void DisableLazyCompilation(bool Disabled = true) { 363 CompilingLazily = !Disabled; 364 } 365 bool isCompilingLazily() const { 366 return CompilingLazily; 367 } 368 // Deprecated in favor of isCompilingLazily (to reduce double-negatives). 369 // Remove this in LLVM 2.8. 370 bool isLazyCompilationDisabled() const { 371 return !CompilingLazily; 372 } 373 374 /// DisableGVCompilation - If called, the JIT will abort if it's asked to 375 /// allocate space and populate a GlobalVariable that is not internal to 376 /// the module. 377 void DisableGVCompilation(bool Disabled = true) { 378 GVCompilationDisabled = Disabled; 379 } 380 bool isGVCompilationDisabled() const { 381 return GVCompilationDisabled; 382 } 383 384 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown 385 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to 386 /// resolve symbols in a custom way. 387 void DisableSymbolSearching(bool Disabled = true) { 388 SymbolSearchingDisabled = Disabled; 389 } 390 bool isSymbolSearchingDisabled() const { 391 return SymbolSearchingDisabled; 392 } 393 394 /// InstallLazyFunctionCreator - If an unknown function is needed, the 395 /// specified function pointer is invoked to create it. If it returns null, 396 /// the JIT will abort. 397 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) { 398 LazyFunctionCreator = P; 399 } 400 401 /// InstallExceptionTableRegister - The JIT will use the given function 402 /// to register the exception tables it generates. 403 void InstallExceptionTableRegister(EERegisterFn F) { 404 ExceptionTableRegister = F; 405 } 406 void InstallExceptionTableDeregister(EERegisterFn F) { 407 ExceptionTableDeregister = F; 408 } 409 410 /// RegisterTable - Registers the given pointer as an exception table. It 411 /// uses the ExceptionTableRegister function. 412 void RegisterTable(const Function *fn, void* res) { 413 if (ExceptionTableRegister) { 414 ExceptionTableRegister(res); 415 AllExceptionTables[fn] = res; 416 } 417 } 418 419 /// DeregisterTable - Deregisters the exception frame previously registered 420 /// for the given function. 421 void DeregisterTable(const Function *Fn) { 422 if (ExceptionTableDeregister) { 423 DenseMap<const Function*, void*>::iterator frame = 424 AllExceptionTables.find(Fn); 425 if(frame != AllExceptionTables.end()) { 426 ExceptionTableDeregister(frame->second); 427 AllExceptionTables.erase(frame); 428 } 429 } 430 } 431 432 /// DeregisterAllTables - Deregisters all previously registered pointers to an 433 /// exception tables. It uses the ExceptionTableoDeregister function. 434 void DeregisterAllTables(); 435 436 protected: 437 explicit ExecutionEngine(Module *M); 438 439 void emitGlobals(); 440 441 void EmitGlobalVariable(const GlobalVariable *GV); 442 443 GenericValue getConstantValue(const Constant *C); 444 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr, 445 Type *Ty); 446 }; 447 448 namespace EngineKind { 449 // These are actually bitmasks that get or-ed together. 450 enum Kind { 451 JIT = 0x1, 452 Interpreter = 0x2 453 }; 454 const static Kind Either = (Kind)(JIT | Interpreter); 455 } 456 457 /// EngineBuilder - Builder class for ExecutionEngines. Use this by 458 /// stack-allocating a builder, chaining the various set* methods, and 459 /// terminating it with a .create() call. 460 class EngineBuilder { 461 private: 462 Module *M; 463 EngineKind::Kind WhichEngine; 464 std::string *ErrorStr; 465 CodeGenOpt::Level OptLevel; 466 JITMemoryManager *JMM; 467 bool AllocateGVsWithCode; 468 Reloc::Model RelocModel; 469 CodeModel::Model CMModel; 470 std::string MArch; 471 std::string MCPU; 472 SmallVector<std::string, 4> MAttrs; 473 bool UseMCJIT; 474 475 /// InitEngine - Does the common initialization of default options. 476 void InitEngine() { 477 WhichEngine = EngineKind::Either; 478 ErrorStr = NULL; 479 OptLevel = CodeGenOpt::Default; 480 JMM = NULL; 481 AllocateGVsWithCode = false; 482 RelocModel = Reloc::Default; 483 CMModel = CodeModel::Default; 484 UseMCJIT = false; 485 } 486 487 public: 488 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and 489 /// is successful, the created engine takes ownership of the module. 490 EngineBuilder(Module *m) : M(m) { 491 InitEngine(); 492 } 493 494 /// setEngineKind - Controls whether the user wants the interpreter, the JIT, 495 /// or whichever engine works. This option defaults to EngineKind::Either. 496 EngineBuilder &setEngineKind(EngineKind::Kind w) { 497 WhichEngine = w; 498 return *this; 499 } 500 501 /// setJITMemoryManager - Sets the memory manager to use. This allows 502 /// clients to customize their memory allocation policies. If create() is 503 /// called and is successful, the created engine takes ownership of the 504 /// memory manager. This option defaults to NULL. 505 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) { 506 JMM = jmm; 507 return *this; 508 } 509 510 /// setErrorStr - Set the error string to write to on error. This option 511 /// defaults to NULL. 512 EngineBuilder &setErrorStr(std::string *e) { 513 ErrorStr = e; 514 return *this; 515 } 516 517 /// setOptLevel - Set the optimization level for the JIT. This option 518 /// defaults to CodeGenOpt::Default. 519 EngineBuilder &setOptLevel(CodeGenOpt::Level l) { 520 OptLevel = l; 521 return *this; 522 } 523 524 /// setRelocationModel - Set the relocation model that the ExecutionEngine 525 /// target is using. Defaults to target specific default "Reloc::Default". 526 EngineBuilder &setRelocationModel(Reloc::Model RM) { 527 RelocModel = RM; 528 return *this; 529 } 530 531 /// setCodeModel - Set the CodeModel that the ExecutionEngine target 532 /// data is using. Defaults to target specific default "CodeModel::Default". 533 EngineBuilder &setCodeModel(CodeModel::Model M) { 534 CMModel = M; 535 return *this; 536 } 537 538 /// setAllocateGVsWithCode - Sets whether global values should be allocated 539 /// into the same buffer as code. For most applications this should be set 540 /// to false. Allocating globals with code breaks freeMachineCodeForFunction 541 /// and is probably unsafe and bad for performance. However, we have clients 542 /// who depend on this behavior, so we must support it. This option defaults 543 /// to false so that users of the new API can safely use the new memory 544 /// manager and free machine code. 545 EngineBuilder &setAllocateGVsWithCode(bool a) { 546 AllocateGVsWithCode = a; 547 return *this; 548 } 549 550 /// setMArch - Override the architecture set by the Module's triple. 551 EngineBuilder &setMArch(StringRef march) { 552 MArch.assign(march.begin(), march.end()); 553 return *this; 554 } 555 556 /// setMCPU - Target a specific cpu type. 557 EngineBuilder &setMCPU(StringRef mcpu) { 558 MCPU.assign(mcpu.begin(), mcpu.end()); 559 return *this; 560 } 561 562 /// setUseMCJIT - Set whether the MC-JIT implementation should be used 563 /// (experimental). 564 EngineBuilder &setUseMCJIT(bool Value) { 565 UseMCJIT = Value; 566 return *this; 567 } 568 569 /// setMAttrs - Set cpu-specific attributes. 570 template<typename StringSequence> 571 EngineBuilder &setMAttrs(const StringSequence &mattrs) { 572 MAttrs.clear(); 573 MAttrs.append(mattrs.begin(), mattrs.end()); 574 return *this; 575 } 576 577 /// selectTarget - Pick a target either via -march or by guessing the native 578 /// arch. Add any CPU features specified via -mcpu or -mattr. 579 static TargetMachine *selectTarget(Module *M, 580 StringRef MArch, 581 StringRef MCPU, 582 const SmallVectorImpl<std::string>& MAttrs, 583 Reloc::Model RM, 584 std::string *Err); 585 586 ExecutionEngine *create(); 587 }; 588 589 } // End llvm namespace 590 591 #endif 592