12#include "llvm/Config/llvm-config.h"
34#define DEBUG_TYPE "orc"
60 std::vector<Type *> HelperArgTypes;
61 for (
auto *Arg : HelperPrefixArgs)
62 HelperArgTypes.push_back(Arg->getType());
71 WrapperFn->setVisibility(WrapperVisibility);
76 std::vector<Value *> HelperArgs;
78 for (
auto &Arg : WrapperFn->args())
79 HelperArgs.push_back(&Arg);
80 auto *HelperResult = IB.CreateCall(HelperFn, HelperArgs);
81 if (HelperFn->getReturnType()->isVoidTy())
84 IB.CreateRet(HelperResult);
89class GenericLLVMIRPlatformSupport;
93class GenericLLVMIRPlatform :
public Platform {
95 GenericLLVMIRPlatform(GenericLLVMIRPlatformSupport &S) : S(S) {}
106 GenericLLVMIRPlatformSupport &S;
112class GlobalCtorDtorScraper {
114 GlobalCtorDtorScraper(GenericLLVMIRPlatformSupport &PS,
117 : PS(PS), InitFunctionPrefix(InitFunctionPrefix),
118 DeInitFunctionPrefix(DeInitFunctionPrefix) {}
123 GenericLLVMIRPlatformSupport &PS;
136 : J(J), InitFunctionPrefix(J.
mangle(
"__orc_init_func.")),
137 DeInitFunctionPrefix(J.
mangle(
"__orc_deinit_func.")) {
139 getExecutionSession().setPlatform(
140 std::make_unique<GenericLLVMIRPlatform>(*
this));
142 setInitTransform(J, GlobalCtorDtorScraper(*
this, InitFunctionPrefix,
143 DeInitFunctionPrefix));
147 StdInterposes[J.
mangleAndIntern(
"__lljit.platform_support_instance")] = {
153 cantFail(setupJITDylib(PlatformJD));
170 auto Ctx = std::make_unique<LLVMContext>();
171 auto M = std::make_unique<Module>(
"__standard_lib", *Ctx);
177 ConstantInt::get(Int64Ty,
reinterpret_cast<uintptr_t>(&JD)),
180 DSOHandle->setInitializer(
183 auto *GenericIRPlatformSupportTy =
188 nullptr,
"__lljit.platform_support_instance");
194 {PlatformInstanceDecl, DSOHandle});
198 auto *AtExit = addHelperAndWrapper(
201 {PlatformInstanceDecl, DSOHandle});
205 AtExit->addRetAttr(AtExitExtAttr);
221 if ((*KV.first).starts_with(InitFunctionPrefix)) {
222 InitSymbols[&JD].add(KV.first,
224 InitFunctions[&JD].add(KV.first);
225 }
else if ((*KV.first).starts_with(DeInitFunctionPrefix)) {
226 DeInitFunctions[&JD].add(KV.first);
234 dbgs() <<
"GenericLLVMIRPlatformSupport getting initializers to run\n";
236 if (
auto Initializers = getInitializers(JD)) {
238 {
dbgs() <<
"GenericLLVMIRPlatformSupport running initializers\n"; });
239 for (
auto InitFnAddr : *Initializers) {
241 dbgs() <<
" Running init " <<
formatv(
"{0:x16}", InitFnAddr)
244 auto *InitFn = InitFnAddr.toPtr<void (*)()>();
248 return Initializers.takeError();
254 dbgs() <<
"GenericLLVMIRPlatformSupport getting deinitializers to run\n";
256 if (
auto Deinitializers = getDeinitializers(JD)) {
258 dbgs() <<
"GenericLLVMIRPlatformSupport running deinitializers\n";
260 for (
auto DeinitFnAddr : *Deinitializers) {
262 dbgs() <<
" Running deinit " <<
formatv(
"{0:x16}", DeinitFnAddr)
265 auto *DeinitFn = DeinitFnAddr.toPtr<void (*)()>();
269 return Deinitializers.takeError();
275 getExecutionSession().runSessionLocked(
276 [&]() { InitFunctions[&JD].add(InitName); });
280 getExecutionSession().runSessionLocked(
281 [&]() { DeInitFunctions[&JD].add(DeInitName); });
286 if (
auto Err = issueInitLookups(JD))
287 return std::move(Err);
290 std::vector<JITDylibSP> DFSLinkOrder;
292 if (
auto Err = getExecutionSession().runSessionLocked([&]() ->
Error {
294 DFSLinkOrder = std::move(*DFSLinkOrderOrErr);
296 return DFSLinkOrderOrErr.takeError();
298 for (
auto &NextJD : DFSLinkOrder) {
299 auto IFItr = InitFunctions.find(NextJD.get());
300 if (IFItr != InitFunctions.end()) {
301 LookupSymbols[NextJD.get()] = std::move(IFItr->second);
302 InitFunctions.erase(IFItr);
307 return std::move(Err);
310 dbgs() <<
"JITDylib init order is [ ";
314 dbgs() <<
"Looking up init functions:\n";
315 for (
auto &KV : LookupSymbols)
316 dbgs() <<
" \"" << KV.first->getName() <<
"\": " << KV.second <<
"\n";
319 auto &ES = getExecutionSession();
323 return LookupResult.takeError();
325 std::vector<ExecutorAddr> Initializers;
326 while (!DFSLinkOrder.empty()) {
327 auto &NextJD = *DFSLinkOrder.back();
328 DFSLinkOrder.pop_back();
329 auto InitsItr = LookupResult->find(&NextJD);
330 if (InitsItr == LookupResult->end())
332 for (
auto &KV : InitsItr->second)
333 Initializers.push_back(KV.second.getAddress());
340 auto &ES = getExecutionSession();
345 std::vector<JITDylibSP> DFSLinkOrder;
347 if (
auto Err = ES.runSessionLocked([&]() ->
Error {
348 if (auto DFSLinkOrderOrErr = JD.getDFSLinkOrder())
349 DFSLinkOrder = std::move(*DFSLinkOrderOrErr);
351 return DFSLinkOrderOrErr.takeError();
353 for (auto &NextJD : DFSLinkOrder) {
354 auto &JDLookupSymbols = LookupSymbols[NextJD.get()];
355 auto DIFItr = DeInitFunctions.find(NextJD.get());
356 if (DIFItr != DeInitFunctions.end()) {
357 LookupSymbols[NextJD.get()] = std::move(DIFItr->second);
358 DeInitFunctions.erase(DIFItr);
360 JDLookupSymbols.add(LLJITRunAtExits,
361 SymbolLookupFlags::WeaklyReferencedSymbol);
365 return std::move(Err);
368 dbgs() <<
"JITDylib deinit order is [ ";
369 for (
auto &JD : DFSLinkOrder)
372 dbgs() <<
"Looking up deinit functions:\n";
373 for (
auto &KV : LookupSymbols)
374 dbgs() <<
" \"" << KV.first->getName() <<
"\": " << KV.second <<
"\n";
380 return LookupResult.takeError();
382 std::vector<ExecutorAddr> DeInitializers;
383 for (
auto &NextJD : DFSLinkOrder) {
384 auto DeInitsItr = LookupResult->find(NextJD.get());
385 assert(DeInitsItr != LookupResult->end() &&
386 "Every JD should have at least __lljit_run_atexits");
388 auto RunAtExitsItr = DeInitsItr->second.find(LLJITRunAtExits);
389 if (RunAtExitsItr != DeInitsItr->second.end())
390 DeInitializers.push_back(RunAtExitsItr->second.getAddress());
392 for (
auto &KV : DeInitsItr->second)
393 if (KV.first != LLJITRunAtExits)
394 DeInitializers.push_back(KV.second.getAddress());
397 return DeInitializers;
404 std::vector<JITDylibSP> DFSLinkOrder;
406 if (
auto Err = getExecutionSession().runSessionLocked([&]() ->
Error {
408 DFSLinkOrder = std::move(*DFSLinkOrderOrErr);
410 return DFSLinkOrderOrErr.takeError();
412 for (
auto &NextJD : DFSLinkOrder) {
413 auto ISItr = InitSymbols.find(NextJD.get());
414 if (ISItr != InitSymbols.end()) {
415 RequiredInitSymbols[NextJD.get()] = std::move(ISItr->second);
416 InitSymbols.erase(ISItr);
428 static void registerCxaAtExitHelper(
void *Self,
void (*
F)(
void *),
void *Ctx,
431 dbgs() <<
"Registering cxa atexit function " << (
void *)
F <<
" for JD "
432 << (*
static_cast<JITDylib **
>(DSOHandle))->getName() <<
"\n";
434 static_cast<GenericLLVMIRPlatformSupport *
>(Self)->AtExitMgr.registerAtExit(
438 static void registerAtExitHelper(
void *Self,
void *DSOHandle,
void (*
F)()) {
440 dbgs() <<
"Registering atexit function " << (
void *)
F <<
" for JD "
441 << (*
static_cast<JITDylib **
>(DSOHandle))->getName() <<
"\n";
443 static_cast<GenericLLVMIRPlatformSupport *
>(Self)->AtExitMgr.registerAtExit(
444 reinterpret_cast<void (*)(
void *)
>(
F),
nullptr, DSOHandle);
447 static void runAtExitsHelper(
void *Self,
void *DSOHandle) {
449 dbgs() <<
"Running atexit functions for JD "
452 static_cast<GenericLLVMIRPlatformSupport *
>(Self)->AtExitMgr.runAtExits(
459 auto Ctx = std::make_unique<LLVMContext>();
460 auto M = std::make_unique<Module>(
"__standard_lib", *Ctx);
461 M->setDataLayout(J.getDataLayout());
463 auto *GenericIRPlatformSupportTy =
468 nullptr,
"__lljit.platform_support_instance");
474 auto *CxaAtExit = addHelperAndWrapper(
479 {PlatformInstanceDecl});
481 TargetLibraryInfo::getExtAttrForI32Return(J.getTargetTriple());
483 CxaAtExit->addRetAttr(CxaAtExitExtAttr);
489 std::string InitFunctionPrefix;
490 std::string DeInitFunctionPrefix;
498 return S.setupJITDylib(JD);
501Error GenericLLVMIRPlatform::teardownJITDylib(JITDylib &JD) {
505Error GenericLLVMIRPlatform::notifyAdding(ResourceTracker &RT,
506 const MaterializationUnit &MU) {
507 return S.notifyAdding(RT, MU);
510Expected<ThreadSafeModule>
511GlobalCtorDtorScraper::operator()(ThreadSafeModule TSM,
512 MaterializationResponsibility &R) {
514 auto &Ctx =
M.getContext();
515 auto *GlobalCtors =
M.getNamedGlobal(
"llvm.global_ctors");
516 auto *GlobalDtors =
M.getNamedGlobal(
"llvm.global_dtors");
518 auto RegisterCOrDtors = [&](GlobalVariable *GlobalCOrDtors,
519 bool isCtor) ->
Error {
523 std::string InitOrDeInitFunctionName;
525 raw_string_ostream(InitOrDeInitFunctionName)
526 << InitFunctionPrefix <<
M.getModuleIdentifier();
528 raw_string_ostream(InitOrDeInitFunctionName)
529 << DeInitFunctionPrefix <<
M.getModuleIdentifier();
531 MangleAndInterner
Mangle(PS.getExecutionSession(),
M.getDataLayout());
532 auto InternedInitOrDeInitName =
Mangle(InitOrDeInitFunctionName);
533 if (
auto Err =
R.defineMaterializing(
534 {{InternedInitOrDeInitName, JITSymbolFlags::Callable}}))
538 FunctionType::get(Type::getVoidTy(Ctx), {},
false),
541 std::vector<std::pair<Function *, unsigned>> InitsOrDeInits;
544 for (
auto E : COrDtors)
545 InitsOrDeInits.push_back(std::make_pair(
E.Func,
E.Priority));
548 auto *InitOrDeInitFuncEntryBlock =
551 for (
auto &KV : InitsOrDeInits)
552 IB.CreateCall(KV.first);
556 PS.registerInitFunc(
R.getTargetJITDylib(), InternedInitOrDeInitName);
558 PS.registerDeInitFunc(
R.getTargetJITDylib(), InternedInitOrDeInitName);
564 if (
auto Err = RegisterCOrDtors(GlobalCtors,
true))
566 if (
auto Err = RegisterCOrDtors(GlobalDtors,
false))
573 return std::move(Err);
575 return std::move(TSM);
582class InactivePlatformSupport :
public LLJIT::PlatformSupport {
584 InactivePlatformSupport() =
default;
587 LLVM_DEBUG(
dbgs() <<
"InactivePlatformSupport: no initializers running for "
592 Error deinitialize(JITDylib &JD)
override {
594 dbgs() <<
"InactivePlatformSupport: no deinitializers running for "
606 enum dlopen_mode : int32_t {
607 ORC_RT_RTLD_LAZY = 0x1,
608 ORC_RT_RTLD_NOW = 0x2,
609 ORC_RT_RTLD_LOCAL = 0x4,
610 ORC_RT_RTLD_GLOBAL = 0x8
613 auto &ES = J.getExecutionSession();
614 auto MainSearchOrder = J.getMainJITDylib().withLinkOrderDo(
617 if (InitializedDylib.contains(&JD)) {
624 auto Result = Update(ES, DSOHandles[&JD]);
626 return Result.takeError();
633 InitializedDylib.insert(&JD);
638 auto H = Open(ES, JD.
getName(), int32_t(ORC_RT_RTLD_LAZY));
640 return H.takeError();
641 DSOHandles[&JD] = *
H;
646 auto &ES = J.getExecutionSession();
647 auto MainSearchOrder = J.getMainJITDylib().withLinkOrderDo(
655 auto Result = Close(ES, DSOHandles[&JD]);
657 return Result.takeError();
660 DSOHandles.erase(&JD);
661 InitializedDylib.erase(&JD);
678 dbgs() <<
" No explicitly set JITTargetMachineBuilder. "
679 "Detecting host...\n";
682 JTMB = std::move(*JTMBOrErr);
684 return JTMBOrErr.takeError();
689 "NumCompileThreads cannot be used with a custom ExecutionSession or "
690 "ExecutorProcessControl",
693#if !LLVM_ENABLE_THREADS
697 " but LLVM was compiled with LLVM_ENABLE_THREADS=Off",
702 [[maybe_unused]]
bool ConcurrentCompilationSettingDefaulted =
706#if LLVM_ENABLE_THREADS
712#if !LLVM_ENABLE_THREADS
715 "LLJIT concurrent compilation support requested, but LLVM was built "
716 "with LLVM_ENABLE_THREADS=Off",
722 dbgs() <<
" JITTargetMachineBuilder is "
724 <<
" Pre-constructed ExecutionSession: " << (
ES ?
"Yes" :
"No")
728 dbgs() <<
DL->getStringRepresentation() <<
"\n";
730 dbgs() <<
"None (will be created by JITTargetMachineBuilder)\n";
732 dbgs() <<
" Custom object-linking-layer creator: "
734 <<
" Custom compile-function creator: "
736 <<
" Custom platform-setup function: "
738 <<
" Support concurrent compilation: "
740 if (ConcurrentCompilationSettingDefaulted)
741 dbgs() <<
" (defaulted based on ES / EPC / NumCompileThreads)\n";
749 if (
auto DLOrErr =
JTMB->getDefaultDataLayoutForTarget())
750 DL = std::move(*DLOrErr);
752 return DLOrErr.takeError();
758 dbgs() <<
"ExecutorProcessControl not specified, "
759 "Creating SelfExecutorProcessControl instance\n";
762 std::unique_ptr<TaskDispatcher>
D =
nullptr;
763#if LLVM_ENABLE_THREADS
765 std::optional<size_t> NumThreads = std ::nullopt;
768 D = std::make_unique<DynamicThreadPoolTaskDispatcher>(NumThreads);
770 D = std::make_unique<InPlaceTaskDispatcher>();
774 EPC = std::move(*EPCOrErr);
776 return EPCOrErr.takeError();
779 dbgs() <<
"Using explicitly specified ExecutorProcessControl instance "
780 <<
EPC.get() <<
"\n";
784 dbgs() <<
"Using explicitly specified ExecutionSession instance "
792 auto &TT =
JTMB->getTargetTriple();
793 bool UseJITLink =
false;
794 switch (TT.getArch()) {
800 UseJITLink = !TT.isOSBinFormatCOFF();
806 UseJITLink = TT.isOSBinFormatELF();
809 UseJITLink = !TT.isOSBinFormatCOFF();
812 UseJITLink = TT.isPPC64ELFv2ABI();
815 UseJITLink = TT.isOSBinFormatELF();
818 UseJITLink = TT.isOSBinFormatELF();
824 if (!
JTMB->getCodeModel())
829 ->
Expected<std::unique_ptr<ObjectLayer>> {
830 return std::make_unique<ObjectLinkingLayer>(
ES, MemMgr);
838 LLVM_DEBUG(
dbgs() <<
"Creating default Process JD setup function\n");
843 J.getExecutionSession(), J.getDylibMgr());
845 return G.takeError();
855 if (
auto Err =
ES->endSession())
856 ES->reportError(std::move(Err));
864 auto JD =
ES->createJITDylib(std::move(Name));
866 return JD.takeError();
875 return G.takeError();
877 if (
auto *ExistingJD =
ES->getJITDylibByName(Path))
880 auto &JD =
ES->createBareJITDylib(Path);
886 std::unique_ptr<MemoryBuffer> LibBuffer) {
888 std::move(LibBuffer));
890 return G.takeError();
900 return G.takeError();
908 assert(TSM &&
"Can not add null module");
922 std::unique_ptr<MemoryBuffer> Obj) {
923 assert(Obj &&
"Can not add null object");
934 if (
auto Sym =
ES->lookup(
937 return Sym->getAddress();
946 return ES.getExecutorProcessControl().createDefaultMemoryManager();
960 return std::make_unique<SectionMemoryManager>();
963 std::make_unique<RTDyldObjectLinkingLayer>(
ES, std::move(GetMemMgr));
965 if (S.
JTMB->getTargetTriple().isOSBinFormatCOFF()) {
966 Layer->setOverrideObjectFlagsWithResponsibilityFlags(
true);
967 Layer->setAutoClaimResponsibilityForObjectSymbols(
true);
970 if (S.
JTMB->getTargetTriple().isOSBinFormatELF() &&
973 Layer->setAutoClaimResponsibilityForObjectSymbols(
true);
978 return std::unique_ptr<ObjectLayer>(std::move(Layer));
991 return std::make_unique<ConcurrentIRCompiler>(std::move(JTMB));
995 return TM.takeError();
997 return std::make_unique<TMOwningSimpleCompiler>(std::move(*TM));
1005 assert(!(S.
EPC && S.
ES) &&
"EPC and ES should not both be set");
1008 ES = std::make_unique<ExecutionSession>(std::move(S.
EPC));
1010 ES = std::move(S.
ES);
1013 ES = std::make_unique<ExecutionSession>(std::move(*EPC));
1015 Err = EPC.takeError();
1023 Err = MM.takeError();
1027 if (
auto DM =
ES->getExecutorProcessControl().createDefaultDylibMgr())
1030 Err =
DM.takeError();
1036 Err = ObjLayer.takeError();
1045 if (!CompileFunction) {
1046 Err = CompileFunction.takeError();
1063 Err = ProcSymsJD.takeError();
1081 Err = PlatformJDOrErr.takeError();
1092 Err = MainOrErr.takeError();
1098 std::string MangledName;
1107 if (M.getTargetTriple().empty())
1108 M.setTargetTriple(
TT);
1110 if (M.getDataLayout().isDefault())
1111 M.setDataLayout(
DL);
1113 if (M.getDataLayout() !=
DL)
1115 "Added modules have incompatible data layouts: " +
1116 M.getDataLayout().getStringRepresentation() +
" (module) vs " +
1117 DL.getStringRepresentation() +
" (jit)",
1124 LLVM_DEBUG({
dbgs() <<
"Setting up orc platform support for LLJIT\n"; });
1136 auto DLLNameStr = DLLName.
str();
1137 auto DLLJD = J.loadPlatformDynamicLibrary(DLLNameStr.c_str());
1139 return DLLJD.takeError();
1150 if (!ProcessSymbolsJD)
1152 "Native platforms require a process symbols JITDylib",
1159 if (!ObjLinkingLayer)
1161 "ExecutorNativePlatform requires ObjectLinkingLayer",
1164 std::unique_ptr<MemoryBuffer> RuntimeArchiveBuffer;
1165 if (OrcRuntime.index() == 0) {
1168 return A.takeError();
1169 RuntimeArchiveBuffer = std::move(*
A);
1171 RuntimeArchiveBuffer = std::move(std::get<1>(OrcRuntime));
1179 switch (TT.getObjectFormat()) {
1181 const char *VCRuntimePath =
nullptr;
1182 bool StaticVCRuntime =
false;
1184 VCRuntimePath = VCRuntime->first.c_str();
1185 StaticVCRuntime = VCRuntime->second;
1188 *ObjLinkingLayer, PlatformJD, std::move(RuntimeArchiveBuffer),
1192 return P.takeError();
1197 *ObjLinkingLayer, std::move(RuntimeArchiveBuffer));
1199 return G.takeError();
1205 return P.takeError();
1210 *ObjLinkingLayer, std::move(RuntimeArchiveBuffer));
1212 return G.takeError();
1216 ES.setPlatform(std::move(*
P));
1218 return P.takeError();
1232 {
dbgs() <<
"Setting up GenericLLVMIRPlatform support for LLJIT\n"; });
1234 if (!ProcessSymbolsJD)
1236 "Native platforms require a process symbols JITDylib",
1244 bool UseEHFrames =
true;
1253 std::optional<bool> ForceEHFrames;
1255 "darwin-use-ehframes-only", ForceEHFrames))
1257 if (ForceEHFrames.has_value())
1258 UseEHFrames = *ForceEHFrames;
1260 UseEHFrames =
false;
1266 OLL->addPlugin(std::move(*UIRP));
1269 return UIRP.takeError();
1277 OLL->addPlugin(std::move(*EHFP));
1280 return EHFP.takeError();
1285 std::make_unique<GenericLLVMIRPlatformSupport>(J, PlatformJD));
1292 {
dbgs() <<
"Explicitly deactivated platform support for LLJIT\n"; });
1300 TT =
JTMB->getTargetTriple();
1305 assert(TSM &&
"Can not add null module");
1308 [&](
Module &M) ->
Error { return applyTargetConfig(M); }))
1311 return CODLayer->add(JD, std::move(TSM));
1318 if (
auto Err =
ES->endSession())
1319 ES->reportError(std::move(Err));
1332 LCTMgr = std::move(S.
LCTMgr);
1336 LCTMgr = std::move(*LCTMgrOrErr);
1338 Err = LCTMgrOrErr.takeError();
1353 "IndirectStubsManagerBuilder for target " +
1363 CODLayer = std::make_unique<CompileOnDemandLayer>(*
ES, *IPLayer, *LCTMgr,
1364 std::move(ISMBuilder));
1367 CODLayer->setCloneToNewContextOnEmit(
true);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ATTRIBUTE_USED
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
Module.h This file contains the declarations for the Module class.
static constexpr Value * getValue(Ty &ValueOrUse)
Machine Check Debug Module
static StringRef getName(Value *V)
LLVM_ABI llvm::orc::shared::CWrapperFunctionBuffer llvm_orc_deregisterEHFrameSectionAllocAction(const char *ArgData, size_t ArgSize)
LLVM_ABI llvm::orc::shared::CWrapperFunctionBuffer llvm_orc_registerEHFrameSectionAllocAction(const char *ArgData, size_t ArgSize)
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Helper for Errors used as out-parameters.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
void setVisibility(VisibilityTypes V)
@ ExternalLinkage
Externally visible function.
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Flags for symbols in the JIT.
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
A Module instance is used to store all the information related to an LLVM module.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
Represent a constant reference to a string, i.e.
std::string str() const
Get the contents as an std::string.
LLVM_ABI bool ends_with_insensitive(StringRef Suffix) const
Check if this string ends with the given Suffix, ignoring case.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Triple - Helper class for working with autoconf configuration names.
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
const std::string & str() const
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
const std::string & getName() const
Get the name for this JITLinkDylib.
Manages allocations of JIT memory.
static Expected< std::unique_ptr< EHFrameRegistrationPlugin > > Create(ExecutionSession &ES)
static Expected< std::unique_ptr< EPCDynamicLibrarySearchGenerator > > Load(ExecutionSession &ES, DylibManager &DylibMgr, const char *LibraryPath, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Permanently loads the library at the given path and, on success, returns an EPCDynamicLibrarySearchGe...
static Expected< std::unique_ptr< EPCDynamicLibrarySearchGenerator > > GetForTargetProcess(ExecutionSession &ES, DylibManager &DylibMgr, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Creates a EPCDynamicLibrarySearchGenerator that searches for symbols in the target process.
An ExecutionSession represents a running JIT program.
void setPlatform(std::unique_ptr< Platform > P)
Set the Platform for this ExecutionSession.
LLVM_ABI JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Error getBootstrapMapValue(StringRef Key, std::optional< T > &Val) const
Look up and SPS-deserialize a bootstrap map value.
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
An interface for Itanium __cxa_atexit interposer implementations.
Represents a JIT'd dynamic library.
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
LLVM_ABI void addToLinkOrder(const JITDylibSearchOrder &NewLinks)
Append the given JITDylibSearchOrder to the link order for this JITDylib (discarding any elements alr...
static LLVM_ABI Expected< std::vector< JITDylibSP > > getDFSLinkOrder(ArrayRef< JITDylibSP > JDs)
Returns the given JITDylibs and all of their transitive dependencies in DFS order (based on linkage r...
LLVM_ABI ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
A utility class for building TargetMachines for JITs.
static LLVM_ABI Expected< JITTargetMachineBuilder > detectHost()
Create a JITTargetMachineBuilder for the host system.
LLVM_ABI Expected< std::unique_ptr< TargetMachine > > createTargetMachine()
Create a TargetMachine.
LLVM_ABI Error prepareForConstruction()
Called prior to JIT class construcion to fix up defaults.
ProcessSymbolsJITDylibSetupFunction SetupProcessSymbolsJITDylib
ObjectLinkingLayerCreator CreateObjectLinkingLayer
MemoryManagerCreator CreateMemoryManager
unsigned NumCompileThreads
std::unique_ptr< ExecutionSession > ES
unique_function< Error(LLJIT &)> PrePlatformSetup
CompileFunctionCreator CreateCompileFunction
std::optional< bool > SupportConcurrentCompilation
bool LinkProcessSymbolsByDefault
std::unique_ptr< ExecutorProcessControl > EPC
std::optional< DataLayout > DL
std::optional< JITTargetMachineBuilder > JTMB
PlatformSetupFunction SetUpPlatform
A pre-fabricated ORC JIT stack that can serve as an alternative to MCJIT.
void setPlatformSupport(std::unique_ptr< PlatformSupport > PS)
Set the PlatformSupport instance.
std::unique_ptr< ExecutionSession > ES
LLJIT(LLJITBuilderState &S, Error &Err)
Create an LLJIT instance with a single compile thread.
Error addObjectFile(ResourceTrackerSP RT, std::unique_ptr< MemoryBuffer > Obj)
Adds an object file to the given JITDylib.
Expected< JITDylib & > createJITDylib(std::string Name)
Create a new JITDylib with the given name and return a reference to it.
JITDylibSearchOrder DefaultLinks
const DataLayout & getDataLayout() const
Returns a reference to the DataLayout for this instance.
ObjectLayer & getObjLinkingLayer()
Returns a reference to the ObjLinkingLayer.
std::unique_ptr< jitlink::JITLinkMemoryManager > MemMgr
std::unique_ptr< ObjectTransformLayer > ObjTransformLayer
virtual ~LLJIT()
Destruct this instance.
std::string mangle(StringRef UnmangledName) const
Returns a linker-mangled version of UnmangledName.
JITDylibSP getPlatformJITDylib()
Returns the Platform JITDylib, which will contain the ORC runtime (if given) and any platform symbols...
Error applyTargetConfig(Module &M)
Expected< JITDylib & > loadPlatformDynamicLibrary(const char *Path)
Load a (real) dynamic library and make its symbols available through a new JITDylib with the same nam...
std::unique_ptr< IRTransformLayer > InitHelperTransformLayer
static Expected< std::unique_ptr< ObjectLayer > > createObjectLinkingLayer(LLJITBuilderState &S, ExecutionSession &ES, jitlink::JITLinkMemoryManager &MemMgr)
std::unique_ptr< IRCompileLayer > CompileLayer
const Triple & getTargetTriple() const
Returns a reference to the triple for this instance.
JITDylibSP getProcessSymbolsJITDylib()
Returns the ProcessSymbols JITDylib, which by default reflects non-JIT'd symbols in the host process.
Expected< ExecutorAddr > lookupLinkerMangled(JITDylib &JD, SymbolStringPtr Name)
Look up a symbol in JITDylib JD by the symbol's linker-mangled name (to look up symbols based on thei...
static Expected< std::unique_ptr< IRCompileLayer::IRCompiler > > createCompileFunction(LLJITBuilderState &S, JITTargetMachineBuilder JTMB)
JITDylib * ProcessSymbols
ExecutionSession & getExecutionSession()
Returns the ExecutionSession for this instance.
std::unique_ptr< IRTransformLayer > TransformLayer
SymbolStringPtr mangleAndIntern(StringRef UnmangledName) const
Returns an interned, linker-mangled version of UnmangledName.
Error linkStaticLibraryInto(JITDylib &JD, std::unique_ptr< MemoryBuffer > LibBuffer)
Link a static library into the given JITDylib.
std::unique_ptr< DylibManager > DylibMgr
std::unique_ptr< ObjectLayer > ObjLinkingLayer
static Expected< std::unique_ptr< jitlink::JITLinkMemoryManager > > createMemoryManager(LLJITBuilderState &S, ExecutionSession &ES)
LLVM_ABI friend Expected< JITDylibSP > setUpGenericLLVMIRPlatform(LLJIT &J)
Configure the LLJIT instance to scrape modules for llvm.global_ctors and llvm.global_dtors variables ...
Error addIRModule(ResourceTrackerSP RT, ThreadSafeModule TSM)
Adds an IR module with the given ResourceTracker.
ExecutorAddr LazyCompileFailureAddr
std::unique_ptr< LazyCallThroughManager > LCTMgr
LLVM_ABI Error prepareForConstruction()
IndirectStubsManagerBuilderFunction ISMBuilder
Error addLazyIRModule(JITDylib &JD, ThreadSafeModule M)
Add a module to be lazily compiled to JITDylib JD.
LoadAndLinkDynLibrary(LLJIT &J)
Error operator()(JITDylib &JD, StringRef DLLName)
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
const SymbolFlagsMap & getSymbols() const
Return the set of symbols that this source provides.
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization symbol for this MaterializationUnit (if any).
An ObjectLayer implementation built on JITLink.
API to remove / transfer ownership of JIT resources.
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
static Expected< std::unique_ptr< SelfExecutorProcessControl > > Create(std::shared_ptr< SymbolStringPool > SSP=nullptr, std::unique_ptr< TaskDispatcher > D=nullptr)
Create a SelfExecutorProcessControl with the given symbol string pool and memory manager.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Create(ObjectLayer &L, std::unique_ptr< MemoryBuffer > ArchiveBuffer, std::unique_ptr< object::Archive > Archive, VisitMembersFunction VisitMembers=VisitMembersFunction(), GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibrarySearchGenerator from the given memory buffer and Archive object.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName, VisitMembersFunction VisitMembers=VisitMembersFunction(), GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibraryDefinitionGenerator from the given path.
Pointer to a pooled string representing a symbol name.
An LLVM Module together with a shared ThreadSafeContext.
decltype(auto) withModuleDo(Func &&F)
Locks the associated ThreadSafeContext and calls the given function on the contained Module.
static Expected< std::shared_ptr< UnwindInfoRegistrationPlugin > > Create(ExecutionSession &ES, rt::MachOUnwindInfoRegistrarSymbolNames SNs=rt::orc_rt_MachOUnwindInfoRegistrarSPSSymbols)
A raw_ostream that writes to an std::string.
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
IntrusiveRefCntPtr< JITDylib > JITDylibSP
LLVM_ABI iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
LookupPrepareFn recordProxy(Proxy< FnT > *P, typename Proxy< FnT >::DispatchFn Dispatch, SymbolNameSpec Name, SymbolLookupFlags LF=SymbolLookupFlags::RequiredSymbol)
Builds P over the symbol with the given name, dispatching through Dispatch.
IntrusiveRefCntPtr< ResourceTracker > ResourceTrackerSP
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
Proxy< ExecutorAddr(std::string, int32_t)> DlfcnOpenProxy
Open a JITDylib by name with the given dlopen-style mode flags; returns its dso handle.
LLVM_ABI void lookupAndApply(unique_function< void(Error)> OnApplied, LookupKind K, const JITDylibSearchOrder &SearchOrder, ArrayRef< LookupPrepareFn > PrepareFns)
Resolve the symbols contributed by every prepare function with a single lookup, then let each of thei...
LLVM_ABI iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
Proxy< int32_t(ExecutorAddr)> DlfcnCloseProxy
Close the given dso handle, running its deinitializers; returns nonzero on failure.
@ MatchExportedSymbolsOnly
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LLVM_ABI Expected< JITDylibSP > setUpInactivePlatform(LLJIT &J)
Configure the LLJIT instance to disable platform support explicitly.
LLVM_ATTRIBUTE_USED void linkComponents()
LLVM_ABI std::function< std::unique_ptr< IndirectStubsManager >()> createLocalIndirectStubsManagerBuilder(const Triple &T)
Create a local indirect stubs manager builder.
Proxy< int32_t(ExecutorAddr)> DlfcnUpdateProxy
Run newly added initializers for an already-open dso handle; returns nonzero on failure.
LLVM_ABI Expected< std::unique_ptr< LazyCallThroughManager > > createLocalLazyCallThroughManager(const Triple &T, ExecutionSession &ES, ExecutorAddr ErrorHandlerAddr)
Create a LocalLazyCallThroughManager from the given triple and execution session.
LLVM_ABI Expected< JITDylibSP > setUpGenericLLVMIRPlatform(LLJIT &J)
Configure the LLJIT instance to scrape modules for llvm.global_ctors and llvm.global_dtors variables ...
LLVM_ABI Error setUpOrcPlatformManually(LLJIT &J)
Configure the LLJIT instance to use orc runtime support.
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Implement std::hash so that hash_code can be used in STL containers.