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/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/ValueMap.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/Support/ValueHandle.h"
26 #include "llvm/Support/Mutex.h"
27 #include "llvm/Target/TargetMachine.h"
33 class ExecutionEngine;
37 class JITEventListener;
38 class JITMemoryManager;
39 class MachineCodeInfo;
45 /// \brief Helper class for helping synchronize access to the global address map
47 class ExecutionEngineState {
49 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
50 typedef ExecutionEngineState *ExtraData;
51 static sys::Mutex *getMutex(ExecutionEngineState *EES);
52 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
53 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
57 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
63 /// GlobalAddressMap - A mapping between LLVM global values and their
64 /// actualized version...
65 GlobalAddressMapTy GlobalAddressMap;
67 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
68 /// used to convert raw addresses into the LLVM global value that is emitted
69 /// at the address. This map is not computed unless getGlobalValueAtAddress
70 /// is called at some point.
71 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
74 ExecutionEngineState(ExecutionEngine &EE);
76 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
77 return GlobalAddressMap;
80 std::map<void*, AssertingVH<const GlobalValue> > &
81 getGlobalAddressReverseMap(const MutexGuard &) {
82 return GlobalAddressReverseMap;
85 /// \brief Erase an entry from the mapping table.
87 /// \returns The address that \arg ToUnmap was happed to.
88 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
91 /// \brief Abstract interface for implementation execution of LLVM modules,
92 /// designed to support both interpreter and just-in-time (JIT) compiler
94 class ExecutionEngine {
95 /// The state object holding the global address mapping, which must be
96 /// accessed synchronously.
98 // FIXME: There is no particular need the entire map needs to be
99 // synchronized. Wouldn't a reader-writer design be better here?
100 ExecutionEngineState EEState;
102 /// The target data for the platform for which execution is being performed.
103 const TargetData *TD;
105 /// Whether lazy JIT compilation is enabled.
106 bool CompilingLazily;
108 /// Whether JIT compilation of external global variables is allowed.
109 bool GVCompilationDisabled;
111 /// Whether the JIT should perform lookups of external symbols (e.g.,
113 bool SymbolSearchingDisabled;
115 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
118 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
119 /// optimize for the case where there is only one module.
120 SmallVector<Module*, 1> Modules;
122 void setTargetData(const TargetData *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,
138 CodeModel::Model CMM,
141 const SmallVectorImpl<std::string>& MAttrs);
142 static ExecutionEngine *(*MCJITCtor)(
144 std::string *ErrorStr,
145 JITMemoryManager *JMM,
146 CodeGenOpt::Level OptLevel,
148 CodeModel::Model CMM,
151 const SmallVectorImpl<std::string>& MAttrs);
152 static ExecutionEngine *(*InterpCtor)(Module *M,
153 std::string *ErrorStr);
155 /// LazyFunctionCreator - If an unknown function is needed, this function
156 /// pointer is invoked to create it. If this returns null, the JIT will
158 void *(*LazyFunctionCreator)(const std::string &);
160 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
161 /// register dwarf tables with this function.
162 typedef void (*EERegisterFn)(void*);
163 EERegisterFn ExceptionTableRegister;
164 EERegisterFn ExceptionTableDeregister;
165 /// This maps functions to their exception tables frames.
166 DenseMap<const Function*, void*> AllExceptionTables;
170 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
171 /// JITEmitter classes. It must be held while changing the internal state of
172 /// any of those classes.
175 //===--------------------------------------------------------------------===//
176 // ExecutionEngine Startup
177 //===--------------------------------------------------------------------===//
179 virtual ~ExecutionEngine();
181 /// create - This is the factory method for creating an execution engine which
182 /// is appropriate for the current machine. This takes ownership of the
185 /// \param GVsWithCode - Allocating globals with code breaks
186 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
187 /// However, we have clients who depend on this behavior, so we must support
188 /// it. Eventually, when we're willing to break some backwards compatability,
189 /// this flag should be flipped to false, so that by default
190 /// freeMachineCodeForFunction works.
191 static ExecutionEngine *create(Module *M,
192 bool ForceInterpreter = false,
193 std::string *ErrorStr = 0,
194 CodeGenOpt::Level OptLevel =
196 bool GVsWithCode = true);
198 /// createJIT - This is the factory method for creating a JIT for the current
199 /// machine, it does not fall back to the interpreter. This takes ownership
200 /// of the Module and JITMemoryManager if successful.
202 /// Clients should make sure to initialize targets prior to calling this
204 static ExecutionEngine *createJIT(Module *M,
205 std::string *ErrorStr = 0,
206 JITMemoryManager *JMM = 0,
207 CodeGenOpt::Level OptLevel =
209 bool GVsWithCode = true,
210 CodeModel::Model CMM =
213 /// addModule - Add a Module to the list of modules that we can JIT from.
214 /// Note that this takes ownership of the Module: when the ExecutionEngine is
215 /// destroyed, it destroys the Module as well.
216 virtual void addModule(Module *M) {
217 Modules.push_back(M);
220 //===--------------------------------------------------------------------===//
222 const TargetData *getTargetData() const { return TD; }
224 /// removeModule - Remove a Module from the list of modules. Returns true if
226 virtual bool removeModule(Module *M);
228 /// FindFunctionNamed - Search all of the active modules to find the one that
229 /// defines FnName. This is very slow operation and shouldn't be used for
231 Function *FindFunctionNamed(const char *FnName);
233 /// runFunction - Execute the specified function with the specified arguments,
234 /// and return the result.
235 virtual GenericValue runFunction(Function *F,
236 const std::vector<GenericValue> &ArgValues) = 0;
238 /// runStaticConstructorsDestructors - This method is used to execute all of
239 /// the static constructors or destructors for a program.
241 /// \param isDtors - Run the destructors instead of constructors.
242 void runStaticConstructorsDestructors(bool isDtors);
244 /// runStaticConstructorsDestructors - This method is used to execute all of
245 /// the static constructors or destructors for a particular module.
247 /// \param isDtors - Run the destructors instead of constructors.
248 void runStaticConstructorsDestructors(Module *module, bool isDtors);
251 /// runFunctionAsMain - This is a helper function which wraps runFunction to
252 /// handle the common task of starting up main with the specified argc, argv,
253 /// and envp parameters.
254 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
255 const char * const * envp);
258 /// addGlobalMapping - Tell the execution engine that the specified global is
259 /// at the specified location. This is used internally as functions are JIT'd
260 /// and as global variables are laid out in memory. It can and should also be
261 /// used by clients of the EE that want to have an LLVM global overlay
262 /// existing data in memory. Mappings are automatically removed when their
263 /// GlobalValue is destroyed.
264 void addGlobalMapping(const GlobalValue *GV, void *Addr);
266 /// clearAllGlobalMappings - Clear all global mappings and start over again,
267 /// for use in dynamic compilation scenarios to move globals.
268 void clearAllGlobalMappings();
270 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
271 /// particular module, because it has been removed from the JIT.
272 void clearGlobalMappingsFromModule(Module *M);
274 /// updateGlobalMapping - Replace an existing mapping for GV with a new
275 /// address. This updates both maps as required. If "Addr" is null, the
276 /// entry for the global is removed from the mappings. This returns the old
277 /// value of the pointer, or null if it was not in the map.
278 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
280 /// getPointerToGlobalIfAvailable - This returns the address of the specified
281 /// global value if it is has already been codegen'd, otherwise it returns
283 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
285 /// getPointerToGlobal - This returns the address of the specified global
286 /// value. This may involve code generation if it's a function.
287 void *getPointerToGlobal(const GlobalValue *GV);
289 /// getPointerToFunction - The different EE's represent function bodies in
290 /// different ways. They should each implement this to say what a function
291 /// pointer should look like. When F is destroyed, the ExecutionEngine will
292 /// remove its global mapping and free any machine code. Be sure no threads
293 /// are running inside F when that happens.
294 virtual void *getPointerToFunction(Function *F) = 0;
296 /// getPointerToBasicBlock - The different EE's represent basic blocks in
297 /// different ways. Return the representation for a blockaddress of the
299 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
301 /// getPointerToFunctionOrStub - If the specified function has been
302 /// code-gen'd, return a pointer to the function. If not, compile it, or use
303 /// a stub to implement lazy compilation if available. See
304 /// getPointerToFunction for the requirements on destroying F.
305 virtual void *getPointerToFunctionOrStub(Function *F) {
306 // Default implementation, just codegen the function.
307 return getPointerToFunction(F);
310 // The JIT overrides a version that actually does this.
311 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
313 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
314 /// at the specified address.
316 const GlobalValue *getGlobalValueAtAddress(void *Addr);
318 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
319 /// Ptr is the address of the memory at which to store Val, cast to
320 /// GenericValue *. It is not a pointer to a GenericValue containing the
321 /// address at which to store Val.
322 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
325 void InitializeMemory(const Constant *Init, void *Addr);
327 /// recompileAndRelinkFunction - This method is used to force a function which
328 /// has already been compiled to be compiled again, possibly after it has been
329 /// modified. Then the entry to the old copy is overwritten with a branch to
330 /// the new copy. If there was no old copy, this acts just like
331 /// VM::getPointerToFunction().
332 virtual void *recompileAndRelinkFunction(Function *F) = 0;
334 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
335 /// corresponding to the machine code emitted to execute this function, useful
336 /// for garbage-collecting generated code.
337 virtual void freeMachineCodeForFunction(Function *F) = 0;
339 /// getOrEmitGlobalVariable - Return the address of the specified global
340 /// variable, possibly emitting it to memory if needed. This is used by the
342 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
343 return getPointerToGlobal((GlobalValue*)GV);
346 /// Registers a listener to be called back on various events within
347 /// the JIT. See JITEventListener.h for more details. Does not
348 /// take ownership of the argument. The argument may be NULL, in
349 /// which case these functions do nothing.
350 virtual void RegisterJITEventListener(JITEventListener *) {}
351 virtual void UnregisterJITEventListener(JITEventListener *) {}
353 /// DisableLazyCompilation - When lazy compilation is off (the default), the
354 /// JIT will eagerly compile every function reachable from the argument to
355 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
356 /// compile the one function and emit stubs to compile the rest when they're
357 /// first called. If lazy compilation is turned off again while some lazy
358 /// stubs are still around, and one of those stubs is called, the program will
361 /// In order to safely compile lazily in a threaded program, the user must
362 /// ensure that 1) only one thread at a time can call any particular lazy
363 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
364 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
365 /// lazy stub. See http://llvm.org/PR5184 for details.
366 void DisableLazyCompilation(bool Disabled = true) {
367 CompilingLazily = !Disabled;
369 bool isCompilingLazily() const {
370 return CompilingLazily;
372 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
373 // Remove this in LLVM 2.8.
374 bool isLazyCompilationDisabled() const {
375 return !CompilingLazily;
378 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
379 /// allocate space and populate a GlobalVariable that is not internal to
381 void DisableGVCompilation(bool Disabled = true) {
382 GVCompilationDisabled = Disabled;
384 bool isGVCompilationDisabled() const {
385 return GVCompilationDisabled;
388 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
389 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
390 /// resolve symbols in a custom way.
391 void DisableSymbolSearching(bool Disabled = true) {
392 SymbolSearchingDisabled = Disabled;
394 bool isSymbolSearchingDisabled() const {
395 return SymbolSearchingDisabled;
398 /// InstallLazyFunctionCreator - If an unknown function is needed, the
399 /// specified function pointer is invoked to create it. If it returns null,
400 /// the JIT will abort.
401 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
402 LazyFunctionCreator = P;
405 /// InstallExceptionTableRegister - The JIT will use the given function
406 /// to register the exception tables it generates.
407 void InstallExceptionTableRegister(EERegisterFn F) {
408 ExceptionTableRegister = F;
410 void InstallExceptionTableDeregister(EERegisterFn F) {
411 ExceptionTableDeregister = F;
414 /// RegisterTable - Registers the given pointer as an exception table. It
415 /// uses the ExceptionTableRegister function.
416 void RegisterTable(const Function *fn, void* res) {
417 if (ExceptionTableRegister) {
418 ExceptionTableRegister(res);
419 AllExceptionTables[fn] = res;
423 /// DeregisterTable - Deregisters the exception frame previously registered for the given function.
424 void DeregisterTable(const Function *Fn) {
425 if (ExceptionTableDeregister) {
426 DenseMap<const Function*, void*>::iterator frame = AllExceptionTables.find(Fn);
427 if(frame != AllExceptionTables.end()) {
428 ExceptionTableDeregister(frame->second);
429 AllExceptionTables.erase(frame);
434 /// DeregisterAllTables - Deregisters all previously registered pointers to an
435 /// exception tables. It uses the ExceptionTableoDeregister function.
436 void DeregisterAllTables();
439 explicit ExecutionEngine(Module *M);
443 void EmitGlobalVariable(const GlobalVariable *GV);
445 GenericValue getConstantValue(const Constant *C);
446 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
450 namespace EngineKind {
451 // These are actually bitmasks that get or-ed together.
456 const static Kind Either = (Kind)(JIT | Interpreter);
459 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
460 /// stack-allocating a builder, chaining the various set* methods, and
461 /// terminating it with a .create() call.
462 class EngineBuilder {
465 EngineKind::Kind WhichEngine;
466 std::string *ErrorStr;
467 CodeGenOpt::Level OptLevel;
468 JITMemoryManager *JMM;
469 bool AllocateGVsWithCode;
470 CodeModel::Model CMModel;
473 SmallVector<std::string, 4> MAttrs;
476 /// InitEngine - Does the common initialization of default options.
478 WhichEngine = EngineKind::Either;
480 OptLevel = CodeGenOpt::Default;
482 AllocateGVsWithCode = false;
483 CMModel = CodeModel::Default;
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 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
525 /// data is using. Defaults to target specific default "CodeModel::Default".
526 EngineBuilder &setCodeModel(CodeModel::Model M) {
531 /// setAllocateGVsWithCode - Sets whether global values should be allocated
532 /// into the same buffer as code. For most applications this should be set
533 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
534 /// and is probably unsafe and bad for performance. However, we have clients
535 /// who depend on this behavior, so we must support it. This option defaults
536 /// to false so that users of the new API can safely use the new memory
537 /// manager and free machine code.
538 EngineBuilder &setAllocateGVsWithCode(bool a) {
539 AllocateGVsWithCode = a;
543 /// setMArch - Override the architecture set by the Module's triple.
544 EngineBuilder &setMArch(StringRef march) {
545 MArch.assign(march.begin(), march.end());
549 /// setMCPU - Target a specific cpu type.
550 EngineBuilder &setMCPU(StringRef mcpu) {
551 MCPU.assign(mcpu.begin(), mcpu.end());
555 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
557 void setUseMCJIT(bool Value) {
561 /// setMAttrs - Set cpu-specific attributes.
562 template<typename StringSequence>
563 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
565 MAttrs.append(mattrs.begin(), mattrs.end());
569 ExecutionEngine *create();
572 } // End llvm namespace