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/Support/ValueHandle.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Target/TargetMachine.h"
32 class ExecutionEngine;
36 class JITEventListener;
37 class JITMemoryManager;
38 class MachineCodeInfo;
44 /// \brief Helper class for helping synchronize access to the global address map
46 class ExecutionEngineState {
48 struct AddressMapConfig : public ValueMapConfig<const GlobalValue*> {
49 typedef ExecutionEngineState *ExtraData;
50 static sys::Mutex *getMutex(ExecutionEngineState *EES);
51 static void onDelete(ExecutionEngineState *EES, const GlobalValue *Old);
52 static void onRAUW(ExecutionEngineState *, const GlobalValue *,
56 typedef ValueMap<const GlobalValue *, void *, AddressMapConfig>
62 /// GlobalAddressMap - A mapping between LLVM global values and their
63 /// actualized version...
64 GlobalAddressMapTy GlobalAddressMap;
66 /// GlobalAddressReverseMap - This is the reverse mapping of GlobalAddressMap,
67 /// used to convert raw addresses into the LLVM global value that is emitted
68 /// at the address. This map is not computed unless getGlobalValueAtAddress
69 /// is called at some point.
70 std::map<void *, AssertingVH<const GlobalValue> > GlobalAddressReverseMap;
73 ExecutionEngineState(ExecutionEngine &EE);
75 GlobalAddressMapTy &getGlobalAddressMap(const MutexGuard &) {
76 return GlobalAddressMap;
79 std::map<void*, AssertingVH<const GlobalValue> > &
80 getGlobalAddressReverseMap(const MutexGuard &) {
81 return GlobalAddressReverseMap;
84 /// \brief Erase an entry from the mapping table.
86 /// \returns The address that \arg ToUnmap was happed to.
87 void *RemoveMapping(const MutexGuard &, const GlobalValue *ToUnmap);
90 /// \brief Abstract interface for implementation execution of LLVM modules,
91 /// designed to support both interpreter and just-in-time (JIT) compiler
93 class ExecutionEngine {
94 /// The state object holding the global address mapping, which must be
95 /// accessed synchronously.
97 // FIXME: There is no particular need the entire map needs to be
98 // synchronized. Wouldn't a reader-writer design be better here?
99 ExecutionEngineState EEState;
101 /// The target data for the platform for which execution is being performed.
102 const TargetData *TD;
104 /// Whether lazy JIT compilation is enabled.
105 bool CompilingLazily;
107 /// Whether JIT compilation of external global variables is allowed.
108 bool GVCompilationDisabled;
110 /// Whether the JIT should perform lookups of external symbols (e.g.,
112 bool SymbolSearchingDisabled;
114 friend class EngineBuilder; // To allow access to JITCtor and InterpCtor.
117 /// The list of Modules that we are JIT'ing from. We use a SmallVector to
118 /// optimize for the case where there is only one module.
119 SmallVector<Module*, 1> Modules;
121 void setTargetData(const TargetData *td) {
125 /// getMemoryforGV - Allocate memory for a global variable.
126 virtual char *getMemoryForGV(const GlobalVariable *GV);
128 // To avoid having libexecutionengine depend on the JIT and interpreter
129 // libraries, the execution engine implementations set these functions to ctor
130 // pointers at startup time if they are linked in.
131 static ExecutionEngine *(*JITCtor)(
133 std::string *ErrorStr,
134 JITMemoryManager *JMM,
135 CodeGenOpt::Level OptLevel,
137 CodeModel::Model CMM,
140 const SmallVectorImpl<std::string>& MAttrs);
141 static ExecutionEngine *(*MCJITCtor)(
143 std::string *ErrorStr,
144 JITMemoryManager *JMM,
145 CodeGenOpt::Level OptLevel,
147 CodeModel::Model CMM,
150 const SmallVectorImpl<std::string>& MAttrs);
151 static ExecutionEngine *(*InterpCtor)(Module *M,
152 std::string *ErrorStr);
154 /// LazyFunctionCreator - If an unknown function is needed, this function
155 /// pointer is invoked to create it. If this returns null, the JIT will
157 void *(*LazyFunctionCreator)(const std::string &);
159 /// ExceptionTableRegister - If Exception Handling is set, the JIT will
160 /// register dwarf tables with this function.
161 typedef void (*EERegisterFn)(void*);
162 EERegisterFn ExceptionTableRegister;
163 EERegisterFn ExceptionTableDeregister;
164 std::vector<void*> AllExceptionTables;
167 /// lock - This lock protects the ExecutionEngine, JIT, JITResolver and
168 /// JITEmitter classes. It must be held while changing the internal state of
169 /// any of those classes.
172 //===--------------------------------------------------------------------===//
173 // ExecutionEngine Startup
174 //===--------------------------------------------------------------------===//
176 virtual ~ExecutionEngine();
178 /// create - This is the factory method for creating an execution engine which
179 /// is appropriate for the current machine. This takes ownership of the
182 /// \param GVsWithCode - Allocating globals with code breaks
183 /// freeMachineCodeForFunction and is probably unsafe and bad for performance.
184 /// However, we have clients who depend on this behavior, so we must support
185 /// it. Eventually, when we're willing to break some backwards compatability,
186 /// this flag should be flipped to false, so that by default
187 /// freeMachineCodeForFunction works.
188 static ExecutionEngine *create(Module *M,
189 bool ForceInterpreter = false,
190 std::string *ErrorStr = 0,
191 CodeGenOpt::Level OptLevel =
193 bool GVsWithCode = true);
195 /// createJIT - This is the factory method for creating a JIT for the current
196 /// machine, it does not fall back to the interpreter. This takes ownership
197 /// of the Module and JITMemoryManager if successful.
199 /// Clients should make sure to initialize targets prior to calling this
201 static ExecutionEngine *createJIT(Module *M,
202 std::string *ErrorStr = 0,
203 JITMemoryManager *JMM = 0,
204 CodeGenOpt::Level OptLevel =
206 bool GVsWithCode = true,
207 CodeModel::Model CMM =
210 /// addModule - Add a Module to the list of modules that we can JIT from.
211 /// Note that this takes ownership of the Module: when the ExecutionEngine is
212 /// destroyed, it destroys the Module as well.
213 virtual void addModule(Module *M) {
214 Modules.push_back(M);
217 //===--------------------------------------------------------------------===//
219 const TargetData *getTargetData() const { return TD; }
221 /// removeModule - Remove a Module from the list of modules. Returns true if
223 virtual bool removeModule(Module *M);
225 /// FindFunctionNamed - Search all of the active modules to find the one that
226 /// defines FnName. This is very slow operation and shouldn't be used for
228 Function *FindFunctionNamed(const char *FnName);
230 /// runFunction - Execute the specified function with the specified arguments,
231 /// and return the result.
232 virtual GenericValue runFunction(Function *F,
233 const std::vector<GenericValue> &ArgValues) = 0;
235 /// runStaticConstructorsDestructors - This method is used to execute all of
236 /// the static constructors or destructors for a program.
238 /// \param isDtors - Run the destructors instead of constructors.
239 void runStaticConstructorsDestructors(bool isDtors);
241 /// runStaticConstructorsDestructors - This method is used to execute all of
242 /// the static constructors or destructors for a particular module.
244 /// \param isDtors - Run the destructors instead of constructors.
245 void runStaticConstructorsDestructors(Module *module, bool isDtors);
248 /// runFunctionAsMain - This is a helper function which wraps runFunction to
249 /// handle the common task of starting up main with the specified argc, argv,
250 /// and envp parameters.
251 int runFunctionAsMain(Function *Fn, const std::vector<std::string> &argv,
252 const char * const * envp);
255 /// addGlobalMapping - Tell the execution engine that the specified global is
256 /// at the specified location. This is used internally as functions are JIT'd
257 /// and as global variables are laid out in memory. It can and should also be
258 /// used by clients of the EE that want to have an LLVM global overlay
259 /// existing data in memory. Mappings are automatically removed when their
260 /// GlobalValue is destroyed.
261 void addGlobalMapping(const GlobalValue *GV, void *Addr);
263 /// clearAllGlobalMappings - Clear all global mappings and start over again,
264 /// for use in dynamic compilation scenarios to move globals.
265 void clearAllGlobalMappings();
267 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
268 /// particular module, because it has been removed from the JIT.
269 void clearGlobalMappingsFromModule(Module *M);
271 /// updateGlobalMapping - Replace an existing mapping for GV with a new
272 /// address. This updates both maps as required. If "Addr" is null, the
273 /// entry for the global is removed from the mappings. This returns the old
274 /// value of the pointer, or null if it was not in the map.
275 void *updateGlobalMapping(const GlobalValue *GV, void *Addr);
277 /// getPointerToGlobalIfAvailable - This returns the address of the specified
278 /// global value if it is has already been codegen'd, otherwise it returns
280 void *getPointerToGlobalIfAvailable(const GlobalValue *GV);
282 /// getPointerToGlobal - This returns the address of the specified global
283 /// value. This may involve code generation if it's a function.
284 void *getPointerToGlobal(const GlobalValue *GV);
286 /// getPointerToFunction - The different EE's represent function bodies in
287 /// different ways. They should each implement this to say what a function
288 /// pointer should look like. When F is destroyed, the ExecutionEngine will
289 /// remove its global mapping and free any machine code. Be sure no threads
290 /// are running inside F when that happens.
291 virtual void *getPointerToFunction(Function *F) = 0;
293 /// getPointerToBasicBlock - The different EE's represent basic blocks in
294 /// different ways. Return the representation for a blockaddress of the
296 virtual void *getPointerToBasicBlock(BasicBlock *BB) = 0;
298 /// getPointerToFunctionOrStub - If the specified function has been
299 /// code-gen'd, return a pointer to the function. If not, compile it, or use
300 /// a stub to implement lazy compilation if available. See
301 /// getPointerToFunction for the requirements on destroying F.
302 virtual void *getPointerToFunctionOrStub(Function *F) {
303 // Default implementation, just codegen the function.
304 return getPointerToFunction(F);
307 // The JIT overrides a version that actually does this.
308 virtual void runJITOnFunction(Function *, MachineCodeInfo * = 0) { }
310 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
311 /// at the specified address.
313 const GlobalValue *getGlobalValueAtAddress(void *Addr);
315 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.
316 /// Ptr is the address of the memory at which to store Val, cast to
317 /// GenericValue *. It is not a pointer to a GenericValue containing the
318 /// address at which to store Val.
319 void StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
322 void InitializeMemory(const Constant *Init, void *Addr);
324 /// recompileAndRelinkFunction - This method is used to force a function which
325 /// has already been compiled to be compiled again, possibly after it has been
326 /// modified. Then the entry to the old copy is overwritten with a branch to
327 /// the new copy. If there was no old copy, this acts just like
328 /// VM::getPointerToFunction().
329 virtual void *recompileAndRelinkFunction(Function *F) = 0;
331 /// freeMachineCodeForFunction - Release memory in the ExecutionEngine
332 /// corresponding to the machine code emitted to execute this function, useful
333 /// for garbage-collecting generated code.
334 virtual void freeMachineCodeForFunction(Function *F) = 0;
336 /// getOrEmitGlobalVariable - Return the address of the specified global
337 /// variable, possibly emitting it to memory if needed. This is used by the
339 virtual void *getOrEmitGlobalVariable(const GlobalVariable *GV) {
340 return getPointerToGlobal((GlobalValue*)GV);
343 /// Registers a listener to be called back on various events within
344 /// the JIT. See JITEventListener.h for more details. Does not
345 /// take ownership of the argument. The argument may be NULL, in
346 /// which case these functions do nothing.
347 virtual void RegisterJITEventListener(JITEventListener *) {}
348 virtual void UnregisterJITEventListener(JITEventListener *) {}
350 /// DisableLazyCompilation - When lazy compilation is off (the default), the
351 /// JIT will eagerly compile every function reachable from the argument to
352 /// getPointerToFunction. If lazy compilation is turned on, the JIT will only
353 /// compile the one function and emit stubs to compile the rest when they're
354 /// first called. If lazy compilation is turned off again while some lazy
355 /// stubs are still around, and one of those stubs is called, the program will
358 /// In order to safely compile lazily in a threaded program, the user must
359 /// ensure that 1) only one thread at a time can call any particular lazy
360 /// stub, and 2) any thread modifying LLVM IR must hold the JIT's lock
361 /// (ExecutionEngine::lock) or otherwise ensure that no other thread calls a
362 /// lazy stub. See http://llvm.org/PR5184 for details.
363 void DisableLazyCompilation(bool Disabled = true) {
364 CompilingLazily = !Disabled;
366 bool isCompilingLazily() const {
367 return CompilingLazily;
369 // Deprecated in favor of isCompilingLazily (to reduce double-negatives).
370 // Remove this in LLVM 2.8.
371 bool isLazyCompilationDisabled() const {
372 return !CompilingLazily;
375 /// DisableGVCompilation - If called, the JIT will abort if it's asked to
376 /// allocate space and populate a GlobalVariable that is not internal to
378 void DisableGVCompilation(bool Disabled = true) {
379 GVCompilationDisabled = Disabled;
381 bool isGVCompilationDisabled() const {
382 return GVCompilationDisabled;
385 /// DisableSymbolSearching - If called, the JIT will not try to lookup unknown
386 /// symbols with dlsym. A client can still use InstallLazyFunctionCreator to
387 /// resolve symbols in a custom way.
388 void DisableSymbolSearching(bool Disabled = true) {
389 SymbolSearchingDisabled = Disabled;
391 bool isSymbolSearchingDisabled() const {
392 return SymbolSearchingDisabled;
395 /// InstallLazyFunctionCreator - If an unknown function is needed, the
396 /// specified function pointer is invoked to create it. If it returns null,
397 /// the JIT will abort.
398 void InstallLazyFunctionCreator(void* (*P)(const std::string &)) {
399 LazyFunctionCreator = P;
402 /// InstallExceptionTableRegister - The JIT will use the given function
403 /// to register the exception tables it generates.
404 void InstallExceptionTableRegister(EERegisterFn F) {
405 ExceptionTableRegister = F;
407 void InstallExceptionTableDeregister(EERegisterFn F) {
408 ExceptionTableDeregister = F;
411 /// RegisterTable - Registers the given pointer as an exception table. It
412 /// uses the ExceptionTableRegister function.
413 void RegisterTable(void* res) {
414 if (ExceptionTableRegister) {
415 ExceptionTableRegister(res);
416 AllExceptionTables.push_back(res);
420 /// DeregisterAllTables - Deregisters all previously registered pointers to an
421 /// exception tables. It uses the ExceptionTableoDeregister function.
422 void DeregisterAllTables();
425 explicit ExecutionEngine(Module *M);
429 void EmitGlobalVariable(const GlobalVariable *GV);
431 GenericValue getConstantValue(const Constant *C);
432 void LoadValueFromMemory(GenericValue &Result, GenericValue *Ptr,
436 namespace EngineKind {
437 // These are actually bitmasks that get or-ed together.
442 const static Kind Either = (Kind)(JIT | Interpreter);
445 /// EngineBuilder - Builder class for ExecutionEngines. Use this by
446 /// stack-allocating a builder, chaining the various set* methods, and
447 /// terminating it with a .create() call.
448 class EngineBuilder {
451 EngineKind::Kind WhichEngine;
452 std::string *ErrorStr;
453 CodeGenOpt::Level OptLevel;
454 JITMemoryManager *JMM;
455 bool AllocateGVsWithCode;
456 CodeModel::Model CMModel;
459 SmallVector<std::string, 4> MAttrs;
462 /// InitEngine - Does the common initialization of default options.
464 WhichEngine = EngineKind::Either;
466 OptLevel = CodeGenOpt::Default;
468 AllocateGVsWithCode = false;
469 CMModel = CodeModel::Default;
474 /// EngineBuilder - Constructor for EngineBuilder. If create() is called and
475 /// is successful, the created engine takes ownership of the module.
476 EngineBuilder(Module *m) : M(m) {
480 /// setEngineKind - Controls whether the user wants the interpreter, the JIT,
481 /// or whichever engine works. This option defaults to EngineKind::Either.
482 EngineBuilder &setEngineKind(EngineKind::Kind w) {
487 /// setJITMemoryManager - Sets the memory manager to use. This allows
488 /// clients to customize their memory allocation policies. If create() is
489 /// called and is successful, the created engine takes ownership of the
490 /// memory manager. This option defaults to NULL.
491 EngineBuilder &setJITMemoryManager(JITMemoryManager *jmm) {
496 /// setErrorStr - Set the error string to write to on error. This option
497 /// defaults to NULL.
498 EngineBuilder &setErrorStr(std::string *e) {
503 /// setOptLevel - Set the optimization level for the JIT. This option
504 /// defaults to CodeGenOpt::Default.
505 EngineBuilder &setOptLevel(CodeGenOpt::Level l) {
510 /// setCodeModel - Set the CodeModel that the ExecutionEngine target
511 /// data is using. Defaults to target specific default "CodeModel::Default".
512 EngineBuilder &setCodeModel(CodeModel::Model M) {
517 /// setAllocateGVsWithCode - Sets whether global values should be allocated
518 /// into the same buffer as code. For most applications this should be set
519 /// to false. Allocating globals with code breaks freeMachineCodeForFunction
520 /// and is probably unsafe and bad for performance. However, we have clients
521 /// who depend on this behavior, so we must support it. This option defaults
522 /// to false so that users of the new API can safely use the new memory
523 /// manager and free machine code.
524 EngineBuilder &setAllocateGVsWithCode(bool a) {
525 AllocateGVsWithCode = a;
529 /// setMArch - Override the architecture set by the Module's triple.
530 EngineBuilder &setMArch(StringRef march) {
531 MArch.assign(march.begin(), march.end());
535 /// setMCPU - Target a specific cpu type.
536 EngineBuilder &setMCPU(StringRef mcpu) {
537 MCPU.assign(mcpu.begin(), mcpu.end());
541 /// setUseMCJIT - Set whether the MC-JIT implementation should be used
543 void setUseMCJIT(bool Value) {
547 /// setMAttrs - Set cpu-specific attributes.
548 template<typename StringSequence>
549 EngineBuilder &setMAttrs(const StringSequence &mattrs) {
551 MAttrs.append(mattrs.begin(), mattrs.end());
555 ExecutionEngine *create();
558 } // End llvm namespace