LLVM 22.0.0git
ExecutionUtils.cpp
Go to the documentation of this file.
1//===---- ExecutionUtils.cpp - Utilities for executing functions in Orc ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
17#include "llvm/IR/Constants.h"
18#include "llvm/IR/Function.h"
20#include "llvm/IR/Module.h"
24#include <string>
25
26namespace llvm {
27namespace orc {
28
30 : InitList(
31 GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
32 I((InitList && End) ? InitList->getNumOperands() : 0) {
33}
34
36 assert(InitList == Other.InitList && "Incomparable iterators.");
37 return I == Other.I;
38}
39
41 return !(*this == Other);
42}
43
45 ++I;
46 return *this;
47}
48
50 CtorDtorIterator Temp = *this;
51 ++I;
52 return Temp;
53}
54
56 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(I));
57 assert(CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors");
58
59 Constant *FuncC = CS->getOperand(1);
60 Function *Func = nullptr;
61
62 // Extract function pointer, pulling off any casts.
63 while (FuncC) {
64 if (Function *F = dyn_cast_or_null<Function>(FuncC)) {
65 Func = F;
66 break;
67 } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
68 if (CE->isCast())
69 FuncC = CE->getOperand(0);
70 else
71 break;
72 } else {
73 // This isn't anything we recognize. Bail out with Func left set to null.
74 break;
75 }
76 }
77
78 auto *Priority = cast<ConstantInt>(CS->getOperand(0));
79 Value *Data = CS->getNumOperands() == 3 ? CS->getOperand(2) : nullptr;
80 if (Data && !isa<GlobalValue>(Data))
81 Data = nullptr;
82 return Element(Priority->getZExtValue(), Func, Data);
83}
84
86 const GlobalVariable *CtorsList = M.getNamedGlobal("llvm.global_ctors");
87 return make_range(CtorDtorIterator(CtorsList, false),
88 CtorDtorIterator(CtorsList, true));
89}
90
92 const GlobalVariable *DtorsList = M.getNamedGlobal("llvm.global_dtors");
93 return make_range(CtorDtorIterator(DtorsList, false),
94 CtorDtorIterator(DtorsList, true));
95}
96
97bool StaticInitGVIterator::isStaticInitGlobal(GlobalValue &GV) {
98 if (GV.isDeclaration())
99 return false;
100
101 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
102 GV.getName() == "llvm.global_dtors"))
103 return true;
104
105 if (ObjFmt == Triple::MachO) {
106 // FIXME: These section checks are too strict: We should match first and
107 // second word split by comma.
108 if (GV.hasSection() &&
109 (GV.getSection().starts_with("__DATA,__objc_classlist") ||
110 GV.getSection().starts_with("__DATA,__objc_selrefs")))
111 return true;
112 }
113
114 return false;
115}
116
118 if (CtorDtors.empty())
119 return;
120
121 MangleAndInterner Mangle(
123 (*CtorDtors.begin()).Func->getDataLayout());
124
125 for (auto CtorDtor : CtorDtors) {
126 assert(CtorDtor.Func && CtorDtor.Func->hasName() &&
127 "Ctor/Dtor function must be named to be runnable under the JIT");
128
129 // FIXME: Maybe use a symbol promoter here instead.
130 if (CtorDtor.Func->hasLocalLinkage()) {
131 CtorDtor.Func->setLinkage(GlobalValue::ExternalLinkage);
132 CtorDtor.Func->setVisibility(GlobalValue::HiddenVisibility);
133 }
134
135 if (CtorDtor.Data && cast<GlobalValue>(CtorDtor.Data)->isDeclaration())
136 continue;
137
138 CtorDtorsByPriority[CtorDtor.Priority].push_back(
139 Mangle(CtorDtor.Func->getName()));
140 }
141}
142
144 using CtorDtorTy = void (*)();
145
146 SymbolLookupSet LookupSet;
147 for (auto &KV : CtorDtorsByPriority)
148 for (auto &Name : KV.second)
149 LookupSet.add(Name);
150 assert(!LookupSet.containsDuplicates() &&
151 "Ctor/Dtor list contains duplicates");
152
153 auto &ES = JD.getExecutionSession();
154 if (auto CtorDtorMap = ES.lookup(
156 std::move(LookupSet))) {
157 for (auto &KV : CtorDtorsByPriority) {
158 for (auto &Name : KV.second) {
159 assert(CtorDtorMap->count(Name) && "No entry for Name");
160 auto CtorDtor = (*CtorDtorMap)[Name].getAddress().toPtr<CtorDtorTy>();
161 CtorDtor();
162 }
163 }
164 CtorDtorsByPriority.clear();
165 return Error::success();
166 } else
167 return CtorDtorMap.takeError();
168}
169
171 auto& CXXDestructorDataPairs = DSOHandleOverride;
172 for (auto &P : CXXDestructorDataPairs)
173 P.first(P.second);
174 CXXDestructorDataPairs.clear();
175}
176
178 void *Arg,
179 void *DSOHandle) {
180 auto& CXXDestructorDataPairs =
181 *reinterpret_cast<CXXDestructorDataPairList*>(DSOHandle);
182 CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
183 return 0;
184}
185
187 MangleAndInterner &Mangle) {
188 SymbolMap RuntimeInterposes;
189 RuntimeInterposes[Mangle("__dso_handle")] = {
191 RuntimeInterposes[Mangle("__cxa_atexit")] = {
193
194 return JD.define(absoluteSymbols(std::move(RuntimeInterposes)));
195}
196
197void ItaniumCXAAtExitSupport::registerAtExit(void (*F)(void *), void *Ctx,
198 void *DSOHandle) {
199 std::lock_guard<std::mutex> Lock(AtExitsMutex);
200 AtExitRecords[DSOHandle].push_back({F, Ctx});
201}
202
204 std::vector<AtExitRecord> AtExitsToRun;
205
206 {
207 std::lock_guard<std::mutex> Lock(AtExitsMutex);
208 auto I = AtExitRecords.find(DSOHandle);
209 if (I != AtExitRecords.end()) {
210 AtExitsToRun = std::move(I->second);
211 AtExitRecords.erase(I);
212 }
213 }
214
215 while (!AtExitsToRun.empty()) {
216 AtExitsToRun.back().F(AtExitsToRun.back().Ctx);
217 AtExitsToRun.pop_back();
218 }
219}
220
223 AddAbsoluteSymbolsFn AddAbsoluteSymbols)
224 : Dylib(std::move(Dylib)), Allow(std::move(Allow)),
225 AddAbsoluteSymbols(std::move(AddAbsoluteSymbols)),
227
230 SymbolPredicate Allow,
231 AddAbsoluteSymbolsFn AddAbsoluteSymbols) {
232 std::string ErrMsg;
233 auto Lib = sys::DynamicLibrary::getPermanentLibrary(FileName, &ErrMsg);
234 if (!Lib.isValid())
235 return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
236 return std::make_unique<DynamicLibrarySearchGenerator>(
237 std::move(Lib), GlobalPrefix, std::move(Allow),
238 std::move(AddAbsoluteSymbols));
239}
240
242 LookupState &LS, LookupKind K, JITDylib &JD,
243 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
244 orc::SymbolMap NewSymbols;
245
246 bool HasGlobalPrefix = (GlobalPrefix != '\0');
247
248 for (auto &KV : Symbols) {
249 auto &Name = KV.first;
250
251 if ((*Name).empty())
252 continue;
253
254 if (Allow && !Allow(Name))
255 continue;
256
257 if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
258 continue;
259
260 std::string Tmp((*Name).data() + HasGlobalPrefix,
261 (*Name).size() - HasGlobalPrefix);
262 if (void *P = Dylib.getAddressOfSymbol(Tmp.c_str()))
264 }
265
266 if (NewSymbols.empty())
267 return Error::success();
268
269 if (AddAbsoluteSymbols)
270 return AddAbsoluteSymbols(JD, std::move(NewSymbols));
271 return JD.define(absoluteSymbols(std::move(NewSymbols)));
272}
273
276 JITDylib &JD) {
277 return [&](object::Archive &A, MemoryBufferRef Buf,
278 size_t Index) -> Expected<bool> {
279 switch (identify_magic(Buf.getBuffer())) {
283 if (auto Err = L.add(JD, createMemberBuffer(A, Buf, Index)))
284 return std::move(Err);
285 // Since we've loaded it already, mark this as not loadable.
286 return false;
287 default:
288 // Non-object-file members are not loadable.
289 return false;
290 }
291 };
292}
293
296 ObjectLayer &L, const char *FileName, VisitMembersFunction VisitMembers,
297 GetObjectFileInterface GetObjFileInterface) {
298
299 const auto &TT = L.getExecutionSession().getTargetTriple();
300 auto Linkable = loadLinkableFile(FileName, TT, LoadArchives::Required);
301 if (!Linkable)
302 return Linkable.takeError();
303
304 return Create(L, std::move(Linkable->first), std::move(VisitMembers),
305 std::move(GetObjFileInterface));
306}
307
310 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
311 std::unique_ptr<object::Archive> Archive, VisitMembersFunction VisitMembers,
312 GetObjectFileInterface GetObjFileInterface) {
313
314 DenseSet<uint64_t> Excluded;
315
316 if (VisitMembers) {
317 size_t Index = 0;
318 Error Err = Error::success();
319 for (auto Child : Archive->children(Err)) {
320 if (auto ChildBuf = Child.getMemoryBufferRef()) {
321 if (auto Loadable = VisitMembers(*Archive, *ChildBuf, Index++)) {
322 if (!*Loadable)
323 Excluded.insert(Child.getDataOffset());
324 } else
325 return Loadable.takeError();
326 } else {
327 // We silently allow non-object archive members. This matches the
328 // behavior of ld.
329 consumeError(ChildBuf.takeError());
330 }
331 }
332 if (Err)
333 return std::move(Err);
334 }
335
336 DenseMap<SymbolStringPtr, size_t> SymbolToMemberIndexMap;
337 {
338 DenseMap<uint64_t, size_t> OffsetToIndex;
339 size_t Index = 0;
340 Error Err = Error::success();
341 for (auto &Child : Archive->children(Err)) {
342 // For all members not excluded above, add them to the OffsetToIndex map.
343 if (!Excluded.count(Child.getDataOffset()))
344 OffsetToIndex[Child.getDataOffset()] = Index;
345 ++Index;
346 }
347 if (Err)
348 return Err;
349
350 auto &ES = L.getExecutionSession();
351 for (auto &Sym : Archive->symbols()) {
352 auto Member = Sym.getMember();
353 if (!Member)
354 return Member.takeError();
355 auto EntryItr = OffsetToIndex.find(Member->getDataOffset());
356
357 // Missing entry means this member should be ignored.
358 if (EntryItr == OffsetToIndex.end())
359 continue;
360
361 SymbolToMemberIndexMap[ES.intern(Sym.getName())] = EntryItr->second;
362 }
363 }
364
365 return std::unique_ptr<StaticLibraryDefinitionGenerator>(
367 L, std::move(ArchiveBuffer), std::move(Archive),
368 std::move(GetObjFileInterface), std::move(SymbolToMemberIndexMap)));
369}
370
373 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
374 VisitMembersFunction VisitMembers,
375 GetObjectFileInterface GetObjFileInterface) {
376
377 auto B = object::createBinary(ArchiveBuffer->getMemBufferRef());
378 if (!B)
379 return B.takeError();
380
381 // If this is a regular archive then create an instance from it.
382 if (isa<object::Archive>(*B))
383 return Create(L, std::move(ArchiveBuffer),
384 std::unique_ptr<object::Archive>(
385 static_cast<object::Archive *>(B->release())),
386 std::move(VisitMembers), std::move(GetObjFileInterface));
387
388 // If this is a universal binary then search for a slice matching the given
389 // Triple.
390 if (auto *UB = dyn_cast<object::MachOUniversalBinary>(B->get())) {
391
392 const auto &TT = L.getExecutionSession().getTargetTriple();
393
394 auto SliceRange = getMachOSliceRangeForTriple(*UB, TT);
395 if (!SliceRange)
396 return SliceRange.takeError();
397
398 MemoryBufferRef SliceRef(
399 StringRef(ArchiveBuffer->getBufferStart() + SliceRange->first,
400 SliceRange->second),
401 ArchiveBuffer->getBufferIdentifier());
402
403 auto Archive = object::Archive::create(SliceRef);
404 if (!Archive)
405 return Archive.takeError();
406
407 return Create(L, std::move(ArchiveBuffer), std::move(*Archive),
408 std::move(VisitMembers), std::move(GetObjFileInterface));
409 }
410
411 return make_error<StringError>(Twine("Unrecognized file type for ") +
412 ArchiveBuffer->getBufferIdentifier(),
414}
415
417 LookupState &LS, LookupKind K, JITDylib &JD,
418 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
419 // Don't materialize symbols from static archives unless this is a static
420 // lookup.
421 if (K != LookupKind::Static)
422 return Error::success();
423
424 // Bail out early if we've already freed the archive.
425 if (!Archive)
426 return Error::success();
427
429
430 for (const auto &[Name, _] : Symbols) {
431 // Check whehter the archive contains this symbol.
432 auto It = SymbolToMemberIndexMap.find(Name);
433 if (It == SymbolToMemberIndexMap.end())
434 continue;
435 size_t Index = It->second;
436
437 // If we're already loading the member containing this symbol then we're
438 // done.
439 if (ToLoad.count(Index))
440 continue;
441
442 auto Member = Archive->findSym(*Name);
443 if (!Member)
444 return Member.takeError();
445 if (!*Member) // Skip "none" children.
446 continue;
447
448 auto MemberBuf = (*Member)->getMemoryBufferRef();
449 if (!MemberBuf)
450 return MemberBuf.takeError();
451
452 ToLoad[Index] = *MemberBuf;
453 }
454
455 // Remove symbols to be loaded.
456 {
457 // FIXME: Enable DenseMap removal using NonOwningSymbolStringPtr?
458 std::vector<SymbolStringPtr> ToRemove;
459 for (auto &[Name, Index] : SymbolToMemberIndexMap)
460 if (ToLoad.count(Index))
461 ToRemove.push_back(Name);
462 for (auto &Name : ToRemove)
463 SymbolToMemberIndexMap.erase(Name);
464 }
465
466 // Add loaded files to JITDylib.
467 for (auto &[Index, Buf] : ToLoad) {
468 auto MemberBuf = createMemberBuffer(*Archive, Buf, Index);
469
470 auto Interface = GetObjFileInterface(L.getExecutionSession(),
471 MemberBuf->getMemBufferRef());
472 if (!Interface)
473 return Interface.takeError();
474
475 if (auto Err = L.add(JD, std::move(MemberBuf), std::move(*Interface)))
476 return Err;
477 }
478
479 return Error::success();
480}
481
482std::unique_ptr<MemoryBuffer>
484 MemoryBufferRef BufRef,
485 size_t Index) {
487 (A.getFileName() + "[" + Twine(Index) +
488 "](" + BufRef.getBufferIdentifier() + ")")
489 .str(),
490 false);
491}
492
493StaticLibraryDefinitionGenerator::StaticLibraryDefinitionGenerator(
494 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
495 std::unique_ptr<object::Archive> Archive,
496 GetObjectFileInterface GetObjFileInterface,
497 DenseMap<SymbolStringPtr, size_t> SymbolToMemberIndexMap)
498 : L(L), GetObjFileInterface(std::move(GetObjFileInterface)),
499 ArchiveBuffer(std::move(ArchiveBuffer)), Archive(std::move(Archive)),
500 SymbolToMemberIndexMap(std::move(SymbolToMemberIndexMap)) {
501 if (!this->GetObjFileInterface)
502 this->GetObjFileInterface = getObjectFileInterface;
503}
504
505std::unique_ptr<DLLImportDefinitionGenerator>
508 return std::unique_ptr<DLLImportDefinitionGenerator>(
510}
511
513 LookupState &LS, LookupKind K, JITDylib &JD,
514 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
515 JITDylibSearchOrder LinkOrder;
516 JD.withLinkOrderDo([&](const JITDylibSearchOrder &LO) {
517 LinkOrder.reserve(LO.size());
518 for (auto &KV : LO) {
519 if (KV.first == &JD)
520 continue;
521 LinkOrder.push_back(KV);
522 }
523 });
524
525 // FIXME: if regular symbol name start with __imp_ we have to issue lookup of
526 // both __imp_ and stripped name and use the lookup information to resolve the
527 // real symbol name.
528 SymbolLookupSet LookupSet;
530 for (auto &KV : Symbols) {
531 StringRef Deinterned = *KV.first;
532 if (Deinterned.starts_with(getImpPrefix()))
533 Deinterned = Deinterned.drop_front(StringRef(getImpPrefix()).size());
534 // Don't degrade the required state
535 auto [It, Inserted] = ToLookUpSymbols.try_emplace(Deinterned);
536 if (Inserted || It->second != SymbolLookupFlags::RequiredSymbol)
537 It->second = KV.second;
538 }
539
540 for (auto &KV : ToLookUpSymbols)
541 LookupSet.add(ES.intern(KV.first), KV.second);
542
543 auto Resolved = ES.lookup(LinkOrder, LookupSet, LookupKind::Static,
545 if (!Resolved)
546 return Resolved.takeError();
547
548 auto G = createStubsGraph(*Resolved);
549 if (!G)
550 return G.takeError();
551 return L.add(JD, std::move(*G));
552}
553
555DLLImportDefinitionGenerator::createStubsGraph(const SymbolMap &Resolved) {
556 auto G = std::make_unique<jitlink::LinkGraph>(
557 "<DLLIMPORT_STUBS>", ES.getSymbolStringPool(), ES.getTargetTriple(),
559 jitlink::Section &Sec =
560 G->createSection(getSectionName(), MemProt::Read | MemProt::Exec);
561
562 for (auto &KV : Resolved) {
563 jitlink::Symbol &Target = G->addAbsoluteSymbol(
564 *KV.first, KV.second.getAddress(), G->getPointerSize(),
566
567 // Create __imp_ symbol
570 Ptr.setName(G->intern((Twine(getImpPrefix()) + *KV.first).str()));
571 Ptr.setLinkage(jitlink::Linkage::Strong);
573
574 // Create PLT stub
575 // FIXME: check PLT stub of data symbol is not accessed
576 jitlink::Block &StubBlock =
578 G->addDefinedSymbol(StubBlock, 0, *KV.first, StubBlock.getSize(),
580 false);
581 }
582
583 return std::move(G);
584}
585
586} // End namespace orc.
587} // End namespace llvm.
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefAnalysis InstSet & ToRemove
@ GlobalPrefix
Definition: AsmWriter.cpp:435
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::string Name
uint32_t Index
bool End
Definition: ELF_riscv.cpp:480
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define _
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
#define P(N)
ConstantArray - Constant Array Declarations.
Definition: Constants.h:433
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1120
This is an important base class in LLVM.
Definition: Constant.h:43
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:177
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition: DenseMap.h:245
bool empty() const
Definition: DenseMap.h:119
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:173
iterator end()
Definition: DenseMap.h:87
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
static ErrorSuccess success()
Create a success value.
Definition: Error.h:336
Tagged union holding either a T or a Error.
Definition: Error.h:485
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:316
LLVM_ABI StringRef getSection() const
Definition: Globals.cpp:191
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:69
bool hasSection() const
Definition: GlobalValue.h:292
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:53
StringRef getBufferIdentifier() const
StringRef getBuffer() const
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:233
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:269
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:619
Manages the enabling and disabling of subtarget specific features.
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
Value * getOperand(unsigned i) const
Definition: User.h:232
unsigned getNumOperands() const
Definition: User.h:254
LLVM Value Representation.
Definition: Value.h:75
bool hasName() const
Definition: Value.h:262
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:322
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:194
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:174
A range adaptor for a pair of iterators.
IteratorT begin() const
static Expected< std::unique_ptr< Archive > > create(MemoryBufferRef Source)
Definition: Archive.cpp:668
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm....
LLVM_ABI bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
LLVM_ABI Element operator*() const
Dereference iterator.
LLVM_ABI CtorDtorIterator(const GlobalVariable *GV, bool End)
Construct an iterator instance.
LLVM_ABI CtorDtorIterator & operator++()
Pre-increment iterator.
LLVM_ABI bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
LLVM_ABI void add(iterator_range< CtorDtorIterator > CtorDtors)
A utility class to create COFF dllimport GOT symbols (__imp_*) and PLT stubs.
static std::unique_ptr< DLLImportDefinitionGenerator > Create(ExecutionSession &ES, ObjectLinkingLayer &L)
Creates a DLLImportDefinitionGenerator instance.
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Create a DynamicLibrarySearchGenerator that searches for symbols in the given sys::DynamicLibrary.
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > Load(const char *FileName, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Permanently loads the library at the given path and, on success, returns a DynamicLibrarySearchGenera...
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
An ExecutionSession represents a running JIT program.
Definition: Core.h:1355
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition: Core.h:1398
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1409
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition: Core.h:1404
LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition: Core.cpp:1803
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
LLVM_ABI void runAtExits(void *DSOHandle)
LLVM_ABI void registerAtExit(void(*F)(void *), void *Ctx, void *DSOHandle)
Represents a JIT'd dynamic library.
Definition: Core.h:902
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition: Core.h:1882
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition: Core.h:921
auto withLinkOrderDo(Func &&F) -> decltype(F(std::declval< const JITDylibSearchOrder & >()))
Do something with the link order (run under the session lock).
Definition: Core.h:1875
static LLVM_ABI int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
CXXDestructorDataPairList DSOHandleOverride
LLVM_ABI void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
LLVM_ABI Error enable(JITDylib &JD, MangleAndInterner &Mangler)
Wraps state for a lookup-in-progress.
Definition: Core.h:834
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Mangling.h:27
Interface for Layers that accept object files.
Definition: Layer.h:134
virtual Error add(ResourceTrackerSP RT, std::unique_ptr< MemoryBuffer > O, MaterializationUnit::Interface I)
Adds a MaterializationUnit for the object file in the given memory buffer to the JITDylib for the giv...
Definition: Layer.cpp:171
ExecutionSession & getExecutionSession()
Returns the execution session for this layer.
Definition: Layer.h:142
An ObjectLayer implementation built on JITLink.
A utility class to expose symbols from a static library.
static VisitMembersFunction loadAllObjectFileMembers(ObjectLayer &L, JITDylib &JD)
A VisitMembersFunction that unconditionally loads all object files from the archive.
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
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.
static std::unique_ptr< MemoryBuffer > createMemberBuffer(object::Archive &A, MemoryBufferRef BufRef, size_t Index)
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:195
SymbolLookupSet & add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
Definition: Core.h:261
bool containsDuplicates()
Returns true if this set contains any duplicates.
Definition: Core.h:388
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
static LLVM_ABI DynamicLibrary getPermanentLibrary(const char *filename, std::string *errMsg=nullptr)
This function permanently loads the dynamic library at the given path using the library load operatio...
LLVM_ABI void * getAddressOfSymbol(const char *symbolName)
Searches through the library for the symbol symbolName.
LLVM_ABI Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
Definition: Binary.cpp:45
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...
Definition: Core.h:178
LLVM_ABI Expected< std::pair< std::unique_ptr< MemoryBuffer >, LinkableFileKind > > loadLinkableFile(StringRef Path, const Triple &TT, LoadArchives LA, std::optional< StringRef > IdentifierOverride=std::nullopt)
Create a MemoryBuffer covering the "linkable" part of the given path.
LLVM_ABI iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition: Core.h:174
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
LLVM_ABI iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:147
LLVM_ABI Expected< MaterializationUnit::Interface > getObjectFileInterface(ExecutionSession &ES, MemoryBufferRef ObjBuffer)
Returns a MaterializationUnit::Interface for the object file contained in the given buffer,...
LLVM_ABI Expected< std::pair< size_t, size_t > > getMachOSliceRangeForTriple(object::MachOUniversalBinary &UB, const Triple &TT)
Utility for identifying the file-slice compatible with TT in a universal binary.
Definition: MachO.cpp:203
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:169
@ Resolved
Queried, materialization begun.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
LLVM_ABI file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Magic.cpp:33
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1702
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto dyn_cast_or_null(const Y &Val)
Definition: Casting.h:759
@ Other
Any other memory.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1083
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
@ elf_relocatable
ELF Relocatable object file.
Definition: Magic.h:28
@ macho_object
Mach-O Object file.
Definition: Magic.h:33
@ coff_object
COFF object file.
Definition: Magic.h:48
Accessor for an element of the global_ctors/global_dtors array.