34 static struct RegisterJIT {
45 std::string *ErrorStr,
46 std::shared_ptr<MCJITMemoryManager> MemMgr,
47 std::shared_ptr<JITSymbolResolver> Resolver,
48 std::unique_ptr<TargetMachine>
TM) {
54 if (!MemMgr || !Resolver) {
55 auto RTDyldMM = std::make_shared<SectionMemoryManager>();
62 return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
66 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine>
TM,
67 std::shared_ptr<MCJITMemoryManager> MemMgr,
68 std::shared_ptr<JITSymbolResolver> Resolver)
69 :
ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
70 Ctx(nullptr), MemMgr(std::move(MemMgr)),
71 Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
83 std::unique_ptr<Module> First = std::move(
Modules[0]);
86 if (First->getDataLayout().isDefault())
89 OwnedModules.addModule(std::move(First));
98 for (
auto &Obj : LoadedObjects)
108 if (M->getDataLayout().isDefault())
111 OwnedModules.addModule(std::move(M));
116 return OwnedModules.removeModule(M);
120 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
L = Dyld.
loadObject(*Obj);
130 std::unique_ptr<object::ObjectFile> ObjFile;
131 std::unique_ptr<MemoryBuffer> MemBuf;
134 Buffers.push_back(std::move(MemBuf));
168 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
180 return CompiledObjBuffer;
188 assert(OwnedModules.ownsModule(M) &&
189 "MCJIT::generateCodeForModule: Unknown module.");
192 if (OwnedModules.hasModuleBeenLoaded(M))
195 std::unique_ptr<MemoryBuffer> ObjectToLoad;
205 assert(ObjectToLoad &&
"Compilation did not produce an object.");
219 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
L =
227 Buffers.push_back(std::move(ObjectToLoad));
228 LoadedObjects.
push_back(std::move(*LoadedObject));
230 OwnedModules.markModuleAsLoaded(M);
239 OwnedModules.markAllLoadedModulesAsFinalized();
245 MemMgr->finalizeMemory();
255 for (
auto M : OwnedModules.added())
258 for (
auto M : ModsToAdd)
268 assert(OwnedModules.ownsModule(M) &&
"MCJIT::finalizeModule: Unknown module.");
271 if (!OwnedModules.hasModuleBeenLoaded(M))
280 reinterpret_cast<uintptr_t>(Addr)),
287 bool CheckFunctionsOnly) {
290 DemangledName = DemangledName.
substr(1);
296 E = OwnedModules.end_added();
302 if (!CheckFunctionsOnly) {
314 bool CheckFunctionsOnly) {
315 std::string MangledName;
320 if (
auto Sym =
findSymbol(MangledName, CheckFunctionsOnly)) {
321 if (
auto AddrOrErr = Sym.getAddress())
330 bool CheckFunctionsOnly) {
340 auto OptionalChildOrErr = A->
findSym(Name);
341 if (!OptionalChildOrErr)
343 auto &OptionalChild = *OptionalChildOrErr;
347 OptionalChild->getAsBinary();
348 if (!ChildBinOrErr) {
353 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.
get();
354 if (ChildBin->isObject()) {
355 std::unique_ptr<object::ObjectFile> OF(
356 static_cast<object::ObjectFile *>(ChildBin.release()));
378 auto Addr =
static_cast<uint64_t
>(
408 TM->getNameWithPrefix(Name, F, Mang);
418 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
421 if (HasBeenAddedButNotLoaded)
423 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
438 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
439 bool isDtors, ModulePtrSet::iterator
I, ModulePtrSet::iterator
E) {
440 for (; I !=
E; ++
I) {
447 runStaticConstructorsDestructorsInModulePtrSet(
448 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
449 runStaticConstructorsDestructorsInModulePtrSet(
450 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
451 runStaticConstructorsDestructorsInModulePtrSet(
452 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
456 ModulePtrSet::iterator I,
457 ModulePtrSet::iterator E) {
458 for (; I !=
E; ++
I) {
468 ModulePtrSet::iterator I,
469 ModulePtrSet::iterator E) {
470 for (; I !=
E; ++
I) {
471 GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
480 Function *F = FindFunctionNamedInModulePtrSet(
481 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
483 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
484 OwnedModules.end_loaded());
486 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
487 OwnedModules.end_finalized());
493 Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
495 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
496 OwnedModules.end_loaded());
498 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
499 OwnedModules.end_finalized());
504 assert(F &&
"Function *F was null at entry to run()");
508 assert(FPtr &&
"Pointer to fn's code was null after getPointerToFunction");
514 "Wrong number of arguments passed into function!");
516 "This doesn't support passing arguments through varargs (yet)!");
521 switch (ArgValues.
size()) {
526 int (*PF)(int,
char **,
const char **) =
527 (
int(*)(int,
char **,
const char **))(
intptr_t)FPtr;
532 (
char **)
GVTOP(ArgValues[1]),
533 (
const char **)
GVTOP(ArgValues[2])));
540 int (*PF)(int,
char **) = (
int(*)(int,
char **))(
intptr_t)FPtr;
545 (
char **)
GVTOP(ArgValues[1])));
553 int (*PF)(int) = (
int(*)(int))(
intptr_t)FPtr;
562 if (ArgValues.
empty()) {
567 unsigned BitWidth = cast<IntegerType>(RetTy)->
getBitWidth();
570 else if (BitWidth <= 8)
572 else if (BitWidth <= 16)
574 else if (BitWidth <= 32)
576 else if (BitWidth <= 64)
601 "argument passing. Please use "
602 "ExecutionEngine::getFunctionAddress and cast the result "
603 "to the desired function pointer type.");
608 if (
auto Sym = Resolver.findSymbol(Name)) {
609 if (
auto AddrOrErr = Sym.getAddress())
610 return reinterpret_cast<void*>(
611 static_cast<uintptr_t>(*AddrOrErr));
612 }
else if (
auto Err = Sym.takeError())
621 if (AbortOnFailure) {
623 "' which could not be resolved!");
632 EventListeners.push_back(L);
640 if (I != EventListeners.rend()) {
642 EventListeners.pop_back();
649 MemMgr->notifyObjectLoaded(
this, Obj);
650 for (
unsigned I = 0, S = EventListeners.size(); I < S; ++
I) {
651 EventListeners[
I]->NotifyObjectEmitted(Obj, L);
658 L->NotifyFreeingObject(Obj);
663 auto Result = ParentEngine.
findSymbol(Name,
false);
668 return ClientResolver->findSymbol(Name);
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Function * FindFunctionNamed(StringRef FnName) override
FindFunctionNamed - Search all of the active modules to find the function that defines FnName...
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Create ObjectFile from path.
Information about the loaded object.
void setObjectCache(ObjectCache *manager) override
Sets the object manager that MCJIT should use to avoid compilation.
void push_back(const T &Elt)
std::unique_ptr< LoadedObjectInfo > loadObject(const object::ObjectFile &O)
Add the referenced object file to the list of objects to be loaded and relocated. ...
void registerEHFrames()
Register any EH frame sections that have been loaded but not previously registered with the memory ma...
Represents a symbol in the JIT.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Expected< Optional< Child > > findSym(StringRef name) const
A Module instance is used to store all the information related to an LLVM module. ...
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
2: 32-bit floating point type
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner)
Log all errors (if any) in E to OS.
virtual std::unique_ptr< MemoryBuffer > getObject(const Module *M)=0
Returns a pointer to a newly allocated MemoryBuffer that contains the object which corresponds with M...
void * getPointerToGlobalIfAvailable(StringRef S)
getPointerToGlobalIfAvailable - This returns the address of the specified global value if it is has a...
sys::Mutex lock
lock - This lock protects the ExecutionEngine and MCJIT classes.
static ExecutionEngine * createJIT(std::unique_ptr< Module > M, std::string *ErrorStr, std::shared_ptr< MCJITMemoryManager > MemMgr, std::shared_ptr< JITSymbolResolver > Resolver, std::unique_ptr< TargetMachine > TM)
uint64_t updateGlobalMapping(const GlobalValue *GV, void *Addr)
updateGlobalMapping - Replace an existing mapping for GV with a new address.
JITEventListener - Abstract interface for use by the JIT to notify clients about significant events d...
StringRef getErrorString()
static JITEventListener * createGDBRegistrationListener()
This class is the base class for all object file types.
bool hasAvailableExternallyLinkage() const
A raw_ostream that writes to an SmallVector or SmallString.
void generateCodeForModule(Module *M) override
generateCodeForModule - Run code generation for the specified module and load it into memory...
4: 80-bit floating point type (X87)
Error takeError()
Take ownership of the stored error.
void UnregisterJITEventListener(JITEventListener *L) override
void deregisterEHFrames()
const DataLayout & getDataLayout() const
virtual void runStaticConstructorsDestructors(bool isDtors)
runStaticConstructorsDestructors - This method is used to execute all of the static constructors or d...
static bool LoadLibraryPermanently(const char *Filename, std::string *ErrMsg=nullptr)
This function permanently loads the dynamic library at the given path.
Tagged union holding either a T or a Error.
void runStaticConstructorsDestructors(bool isDtors) override
runStaticConstructorsDestructors - This method is used to execute all of the static constructors or d...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
uint64_t getGlobalValueAddress(const std::string &Name) override
getGlobalValueAddress - Return the address of the specified global value.
Class to represent function types.
virtual void finalizeModule(Module *)
GlobalVariable * FindGlobalVariableNamed(StringRef Name, bool AllowInternal=false) override
FindGlobalVariableNamed - Search all of the active modules to find the global variable that defines N...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
TypeID getTypeID() const
Return the type id for the type.
void * getPointerToFunction(Function *F) override
getPointerToFunction - The different EE's represent function bodies in different ways.
JITSymbol findSymbol(const std::string &Name) override
This method returns the address of the specified function or variable.
JITEvaluatedSymbol getSymbol(StringRef Name) const
Get the target address and flags for the named symbol.
size_t size() const
size - Get the array size.
JITSymbol findExistingSymbol(const std::string &Name)
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
void finalizeObject() override
finalizeObject - ensure the module is fully processed and is usable.
11: Arbitrary bit width integers
PassManager manages ModulePassManagers.
Instances of this class acquire a given Mutex Lock when constructed and hold that lock until destruct...
Type * getParamType(unsigned i) const
Parameter type accessors.
void addModule(std::unique_ptr< Module > M) override
Add a Module to the list of modules that we can JIT from.
The instances of the Type class are immutable: once they are created, they are never changed...
FunctionType * getFunctionType() const
Returns the FunctionType for me.
bool removeModule(Module *M) override
removeModule - Removes a Module from the list of modules, but does not free the module's memory...
void * getPointerToNamedFunction(StringRef Name, bool AbortOnFailure=true) override
getPointerToNamedFunction - This method returns the address of the specified function by using the dl...
bool isSymbolSearchingDisabled() const
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
uint64_t getFunctionAddress(const std::string &Name) override
getFunctionAddress - Return the address of the specified function.
6: 128-bit floating point type (two 64-bits, PowerPC)
bool empty() const
empty - Check if the array is empty.
JITSymbol findSymbol(const std::string &Name, bool CheckFunctionsOnly)
bool getVerifyModules() const
bool isPointerTy() const
True if this is an instance of PointerType.
void consumeError(Error Err)
Consume a Error without doing anything.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
Abstract interface for implementation execution of LLVM modules, designed to support both interpreter...
virtual void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj)=0
notifyObjectCompiled - Provides a pointer to compiled code for Module M.
void * GVTOP(const GenericValue &GV)
std::pair< std::unique_ptr< T >, std::unique_ptr< MemoryBuffer > > takeBinary()
void addArchive(object::OwningBinary< object::Archive > O) override
addArchive - Add an Archive to the execution engine.
SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
bool hasExternalWeakLinkage() const
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Module.h This file contains the declarations for the Module class.
reference get()
Returns a reference to the stored T value.
uint64_t getSymbolAddress(const std::string &Name, bool CheckFunctionsOnly)
void RegisterJITEventListener(JITEventListener *L) override
Registers a listener to be called back on various events within the JIT.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
GenericValue PTOGV(void *P)
Class for arbitrary precision integers.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Module * findModuleForSymbol(const std::string &Name, bool CheckFunctionsOnly)
GenericValue runFunction(Function *F, ArrayRef< GenericValue > ArgValues) override
runFunction - Execute the specified function with the specified arguments, and return the result...
std::unique_ptr< MemoryBuffer > emitObject(Module *M)
emitObject – Generate a JITed object in memory from the specified module Currently, MCJIT only supports a single module and the module passed to this function call is expected to be the contained module.
SmallVector< std::unique_ptr< Module >, 1 > Modules
The list of Modules that we are JIT'ing from.
llvm_unreachable("Unknown RegBank!")
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
JITTargetAddress getAddress() const
Return the address of this symbol.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
SmallVector-backed MemoryBuffer instance.
This is the base ObjectCache type which can be provided to an ExecutionEngine for the purpose of avoi...
void resolveRelocations()
Resolve the relocations for all symbols we currently know about.
3: 64-bit floating point type
Type * getReturnType() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
FunctionCreator LazyFunctionCreator
LazyFunctionCreator - If an unknown function is needed, this function pointer is invoked to create it...
A raw_ostream that writes to an std::string.
Module * getParent()
Get the module that this global value is contained inside of...
void NotifyFreeingObject(const object::ObjectFile &Obj)
StringRef - Represent a constant reference to a string, i.e.
void NotifyObjectEmitted(const object::ObjectFile &Obj, const RuntimeDyld::LoadedObjectInfo &L)
void finalizeLoadedModules()
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
bool isVoidTy() const
Return true if this is 'void'.
5: 128-bit floating point type (112-bit mantissa)
void addObjectFile(std::unique_ptr< object::ObjectFile > O) override
addObjectFile - Add an ObjectFile to the execution engine.