1 //===- ExecutionEngine.h - Abstract Execution Engine Interface --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the abstract interface that implements execution support
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_EXECUTION_ENGINE_H
16 #define LLVM_EXECUTION_ENGINE_H
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 #include "llvm/Target/TargetOptions.h"
35 class ExecutionEngine;
39 class JITEventListener;
40 class JITMemoryManager;
41 class MachineCodeInfo;
47 /// \brief Helper class for helping synchronize access to the global address map
49 class ExecutionEngineState {
51 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
52 typedef ExecutionEngineState *ExtraData;
53 static sys::Mutex *getMutex(ExecutionEngineState *EES);
54 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
55 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
59 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
65 /// GlobalAddressMap - A mapping between LLVM global values and their
66 /// actualized version...
67 GlobalAddressMapTy GlobalAddressMap;
69 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
70 /// used to convert raw addresses into the LLVM global value that is emitted
71 /// at the address. This map is not computed unless getGlobalValueAtAddress
72 /// is called at some point.
73 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
76 ExecutionEngineState(ExecutionEngine &EE);
78 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
79 return GlobalAddressMap;
82 std::map<void*, AssertingVH<const GlobalValue> > &
83 getGlobalAddressReverseMap(const MutexGuard &) {
84 return GlobalAddressReverseMap;
87 /// \brief Erase an entry from the mapping table.
89 /// \returns The address that \arg ToUnmap was happed to.
90 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
93 /// \brief Abstract interface for implementation execution of LLVM modules,
94 /// designed to support both interpreter and just-in-time (JIT) compiler
96 class ExecutionEngine {
97 /// The state object holding the global address mapping, which must be
98 /// accessed synchronously.
100 // FIXME: There is no particular need the entire map needs to be
101 // synchronized. Wouldn't a reader-writer design be better here?
102 ExecutionEngineState EEState;
104 /// The target data for the platform for which execution is being performed.
105 const TargetData *TD;
107 /// Whether lazy JIT compilation is enabled.
108 bool CompilingLazily;
110 /// Whether JIT compilation of external global variables is allowed.
111 bool GVCompilationDisabled;
113 /// Whether the JIT should perform lookups of external symbols (e.g.,
115 bool SymbolSearchingDisabled;
117 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
120 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
121 /// optimize for the case where there is only one module.
122 SmallVector<Module*, 1> Modules;
124 void setTargetData(const TargetData *td) { TD = td; }
126 /// getMemoryforGV - Allocate memory for a global variable.
127 virtual char *getMemoryForGV(const GlobalVariable *GV);
129 // To avoid having libexecutionengine depend on the JIT and interpreter
130 // libraries, the execution engine implementations set these functions to ctor
131 // pointers at startup time if they are linked in.
132 static ExecutionEngine *(*JITCtor)(
134 std::string *ErrorStr,
135 JITMemoryManager *JMM,
136 CodeGenOpt::Level OptLevel,
139 static ExecutionEngine *(*MCJITCtor)(
141 std::string *ErrorStr,
142 JITMemoryManager *JMM,
143 CodeGenOpt::Level OptLevel,
146 static ExecutionEngine *(*InterpCtor)(Module *M, std::string *ErrorStr);
148 /// LazyFunctionCreator - If an unknown function is needed, this function
149 /// pointer is invoked to create it. If this returns null, the JIT will
151 void *(*LazyFunctionCreator)(const std::string &);
153 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
154 /// register dwarf tables with this function.
155 typedef void (*EERegisterFn)(void*);
156 EERegisterFn ExceptionTableRegister;
157 EERegisterFn ExceptionTableDeregister;
158 /// This maps functions to their exception tables frames.
159 DenseMap<const Function*, void*> AllExceptionTables;
163 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
164 /// JITEmitter classes. It must be held while changing the internal state of
165 /// any of those classes.
168 //===--------------------------------------------------------------------===//
169 // ExecutionEngine Startup
170 //===--------------------------------------------------------------------===//
172 virtual ~ExecutionEngine();
174 /// create - This is the factory method for creating an execution engine which
175 /// is appropriate for the current machine. This takes ownership of the
178 /// \param GVsWithCode - Allocating globals with code breaks
179 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
180 /// However, we have clients who depend on this behavior, so we must support
181 /// it. Eventually, when we're willing to break some backwards compatibility,
182 /// this flag should be flipped to false, so that by default
183 /// freeMachineCodeForFunction works.
184 static ExecutionEngine *create(Module *M,
185 bool ForceInterpreter = false,
186 std::string *ErrorStr = 0,
187 CodeGenOpt::Level OptLevel =
189 bool GVsWithCode = true);
191 /// createJIT - This is the factory method for creating a JIT for the current
192 /// machine, it does not fall back to the interpreter. This takes ownership
193 /// of the Module and JITMemoryManager if successful.
195 /// Clients should make sure to initialize targets prior to calling this
197 static ExecutionEngine *createJIT(Module *M,
198 std::string *ErrorStr = 0,
199 JITMemoryManager *JMM = 0,
200 CodeGenOpt::Level OptLevel =
202 bool GVsWithCode = true,
203 Reloc::Model RM = Reloc::Default,
204 CodeModel::Model CMM =
205 CodeModel::JITDefault);
207 /// addModule - Add a Module to the list of modules that we can JIT from.
208 /// Note that this takes ownership of the Module: when the ExecutionEngine is
209 /// destroyed, it destroys the Module as well.
210 virtual void addModule(Module *M) {
211 Modules.push_back(M);
214 //===--------------------------------------------------------------------===//
216 const TargetData *getTargetData() const { return TD; }
218 /// removeModule - Remove a Module from the list of modules. Returns true if
220 virtual bool removeModule(Module *M);
222 /// FindFunctionNamed - Search all of the active modules to find the one that
223 /// defines FnName. This is very slow operation and shouldn't be used for
225 Function *FindFunctionNamed(const char *FnName);
227 /// runFunction - Execute the specified function with the specified arguments,
228 /// and return the result.
229 virtual GenericValue runFunction(Function *F,
230 const std::vector<GenericValue> &ArgValues) = 0;
232 /// runStaticConstructorsDestructors - This method is used to execute all of
233 /// the static constructors or destructors for a program.
235 /// \param isDtors - Run the destructors instead of constructors.
236 void runStaticConstructorsDestructors(bool isDtors);
238 /// runStaticConstructorsDestructors - This method is used to execute all of
239 /// the static constructors or destructors for a particular module.
241 /// \param isDtors - Run the destructors instead of constructors.
242 void runStaticConstructorsDestructors(Module *module, bool isDtors);
245 /// runFunctionAsMain - This is a helper function which wraps runFunction to
246 /// handle the common task of starting up main with the specified argc, argv,
247 /// and envp parameters.
248 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
249 const char * const * envp);
252 /// addGlobalMapping - Tell the execution engine that the specified global is
253 /// at the specified location. This is used internally as functions are JIT'd
254 /// and as global variables are laid out in memory. It can and should also be
255 /// used by clients of the EE that want to have an LLVM global overlay
256 /// existing data in memory. Mappings are automatically removed when their
257 /// GlobalValue is destroyed.
258 void addGlobalMapping(const GlobalValue *GV, void *Addr);
260 /// clearAllGlobalMappings - Clear all global mappings and start over again,
261 /// for use in dynamic compilation scenarios to move globals.
262 void clearAllGlobalMappings();
264 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
265 /// particular module, because it has been removed from the JIT.
266 void clearGlobalMappingsFromModule(Module *M);
268 /// updateGlobalMapping - Replace an existing mapping for GV with a new
269 /// address. This updates both maps as required. If "Addr" is null, the
270 /// entry for the global is removed from the mappings. This returns the old
271 /// value of the pointer, or null if it was not in the map.
272 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
274 /// getPointerToGlobalIfAvailable - This returns the address of the specified
275 /// global value if it is has already been codegen'd, otherwise it returns
277 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
279 /// getPointerToGlobal - This returns the address of the specified global
280 /// value. This may involve code generation if it's a function.
281 void *getPointerToGlobal(const GlobalValue *GV);
283 /// getPointerToFunction - The different EE's represent function bodies in
284 /// different ways. They should each implement this to say what a function
285 /// pointer should look like. When F is destroyed, the ExecutionEngine will
286 /// remove its global mapping and free any machine code. Be sure no threads
287 /// are running inside F when that happens.
288 virtual void *getPointerToFunction(Function *F) = 0;
290 /// getPointerToBasicBlock - The different EE's represent basic blocks in
291 /// different ways. Return the representation for a blockaddress of the
293 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
295 /// getPointerToFunctionOrStub - If the specified function has been
296 /// code-gen'd, return a pointer to the function. If not, compile it, or use
297 /// a stub to implement lazy compilation if available. See
298 /// getPointerToFunction for the requirements on destroying F.
299 virtual void *getPointerToFunctionOrStub(Function *F) {
300 // Default implementation, just codegen the function.
301 return getPointerToFunction(F);
304 // The JIT overrides a version that actually does this.
305 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
307 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
308 /// at the specified address.
310 const GlobalValue *getGlobalValueAtAddress(void *Addr);
312 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
313 /// Ptr is the address of the memory at which to store Val, cast to
314 /// GenericValue *. It is not a pointer to a GenericValue containing the
315 /// address at which to store Val.
316 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
319 void InitializeMemory(const Constant *Init, void *Addr);
321 /// recompileAndRelinkFunction - This method is used to force a function which
322 /// has already been compiled to be compiled again, possibly after it has been
323 /// modified. Then the entry to the old copy is overwritten with a branch to
324 /// the new copy. If there was no old copy, this acts just like
325 /// VM::getPointerToFunction().
326 virtual void *recompileAndRelinkFunction(Function *F) = 0;
328 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
329 /// corresponding to the machine code emitted to execute this function, useful
330 /// for garbage-collecting generated code.
331 virtual void freeMachineCodeForFunction(Function *F) = 0;
333 /// getOrEmitGlobalVariable - Return the address of the specified global
334 /// variable, possibly emitting it to memory if needed. This is used by the
336 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
337 return getPointerToGlobal((GlobalValue*)GV);
340 /// Registers a listener to be called back on various events within
341 /// the JIT. See JITEventListener.h for more details. Does not
342 /// take ownership of the argument. The argument may be NULL, in
343 /// which case these functions do nothing.
344 virtual void RegisterJITEventListener(JITEventListener *) {}
345 virtual void UnregisterJITEventListener(JITEventListener *) {}
347 /// DisableLazyCompilation - When lazy compilation is off (the default), the
348 /// JIT will eagerly compile every function reachable from the argument to
349 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
350 /// compile the one function and emit stubs to compile the rest when they're
351 /// first called. If lazy compilation is turned off again while some lazy
352 /// stubs are still around, and one of those stubs is called, the program will
355 /// In order to safely compile lazily in a threaded program, the user must
356 /// ensure that 1) only one thread at a time can call any particular lazy
357 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
358 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
359 /// lazy stub. See http://llvm.org/PR5184 for details.
360 void DisableLazyCompilation(bool Disabled = true) {
361 CompilingLazily = !Disabled;
363 bool isCompilingLazily() const {
364 return CompilingLazily;
366 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
367 // Remove this in LLVM 2.8.
368 bool isLazyCompilationDisabled() const {
369 return !CompilingLazily;
372 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
373 /// allocate space and populate a GlobalVariable that is not internal to
375 void DisableGVCompilation(bool Disabled = true) {
376 GVCompilationDisabled = Disabled;
378 bool isGVCompilationDisabled() const {
379 return GVCompilationDisabled;
382 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
383 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
384 /// resolve symbols in a custom way.
385 void DisableSymbolSearching(bool Disabled = true) {
386 SymbolSearchingDisabled = Disabled;
388 bool isSymbolSearchingDisabled() const {
389 return SymbolSearchingDisabled;
392 /// InstallLazyFunctionCreator - If an unknown function is needed, the
393 /// specified function pointer is invoked to create it. If it returns null,
394 /// the JIT will abort.
395 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
396 LazyFunctionCreator = P;
399 /// InstallExceptionTableRegister - The JIT will use the given function
400 /// to register the exception tables it generates.
401 void InstallExceptionTableRegister(EERegisterFn F) {
402 ExceptionTableRegister = F;
404 void InstallExceptionTableDeregister(EERegisterFn F) {
405 ExceptionTableDeregister = F;
408 /// RegisterTable - Registers the given pointer as an exception table. It
409 /// uses the ExceptionTableRegister function.
410 void RegisterTable(const Function *fn, void* res) {
411 if (ExceptionTableRegister) {
412 ExceptionTableRegister(res);
413 AllExceptionTables[fn] = res;
417 /// DeregisterTable - Deregisters the exception frame previously registered
418 /// for the given function.
419 void DeregisterTable(const Function *Fn) {
420 if (ExceptionTableDeregister) {
421 DenseMap<const Function*, void*>::iterator frame =
422 AllExceptionTables.find(Fn);
423 if(frame != AllExceptionTables.end()) {
424 ExceptionTableDeregister(frame->second);
425 AllExceptionTables.erase(frame);
430 /// DeregisterAllTables - Deregisters all previously registered pointers to an
431 /// exception tables. It uses the ExceptionTableoDeregister function.
432 void DeregisterAllTables();
435 explicit ExecutionEngine(Module *M);
439 void EmitGlobalVariable(const GlobalVariable *GV);
441 GenericValue getConstantValue(const Constant *C);
442 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
446 namespace EngineKind {
447 // These are actually bitmasks that get or-ed together.
452 const static Kind Either = (Kind)(JIT | Interpreter);
455 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
456 /// stack-allocating a builder, chaining the various set* methods, and
457 /// terminating it with a .create() call.
458 class EngineBuilder {
461 EngineKind::Kind WhichEngine;
462 std::string *ErrorStr;
463 CodeGenOpt::Level OptLevel;
464 JITMemoryManager *JMM;
465 bool AllocateGVsWithCode;
466 TargetOptions Options;
467 Reloc::Model RelocModel;
468 CodeModel::Model CMModel;
471 SmallVector<std::string, 4> MAttrs;
474 /// InitEngine - Does the common initialization of default options.
476 WhichEngine = EngineKind::Either;
478 OptLevel = CodeGenOpt::Default;
480 Options = TargetOptions();
481 AllocateGVsWithCode = false;
482 RelocModel = Reloc::Default;
483 CMModel = CodeModel::JITDefault;
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) {
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) {
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) {
510 /// setErrorStr - Set the error string to write to on error. This option
511 /// defaults to NULL.
512 EngineBuilder &setErrorStr(std::string *e) {
517 /// setOptLevel - Set the optimization level for the JIT. This option
518 /// defaults to CodeGenOpt::Default.
519 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
524 /// setTargetOptions - Set the target options that the ExecutionEngine
525 /// target is using. Defaults to TargetOptions().
526 EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
531 /// setRelocationModel - Set the relocation model that the ExecutionEngine
532 /// target is using. Defaults to target specific default "Reloc::Default".
533 EngineBuilder &setRelocationModel(Reloc::Model RM) {
538 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
539 /// data is using. Defaults to target specific default
540 /// "CodeModel::JITDefault".
541 EngineBuilder &setCodeModel(CodeModel::Model M) {
546 /// setAllocateGVsWithCode - Sets whether global values should be allocated
547 /// into the same buffer as code. For most applications this should be set
548 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
549 /// and is probably unsafe and bad for performance. However, we have clients
550 /// who depend on this behavior, so we must support it. This option defaults
551 /// to false so that users of the new API can safely use the new memory
552 /// manager and free machine code.
553 EngineBuilder &setAllocateGVsWithCode(bool a) {
554 AllocateGVsWithCode = a;
558 /// setMArch - Override the architecture set by the Module's triple.
559 EngineBuilder &setMArch(StringRef march) {
560 MArch.assign(march.begin(), march.end());
564 /// setMCPU - Target a specific cpu type.
565 EngineBuilder &setMCPU(StringRef mcpu) {
566 MCPU.assign(mcpu.begin(), mcpu.end());
570 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
572 EngineBuilder &setUseMCJIT(bool Value) {
577 /// setMAttrs - Set cpu-specific attributes.
578 template<typename StringSequence>
579 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
581 MAttrs.append(mattrs.begin(), mattrs.end());
585 /// selectTarget - Pick a target either via -march or by guessing the native
586 /// arch. Add any CPU features specified via -mcpu or -mattr.
587 static TargetMachine *selectTarget(Module *M,
590 const SmallVectorImpl<std::string>& MAttrs,
591 const TargetOptions &Options,
594 CodeGenOpt::Level OL,
597 ExecutionEngine *create();
600 } // End llvm namespace