LLVM 20.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
14#include "llvm/IR/Constants.h"
15#include "llvm/IR/Function.h"
17#include "llvm/IR/Module.h"
23#include <string>
24
25namespace llvm {
26namespace orc {
27
29 : InitList(
30 GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
31 I((InitList && End) ? InitList->getNumOperands() : 0) {
32}
33
35 assert(InitList == Other.InitList && "Incomparable iterators.");
36 return I == Other.I;
37}
38
40 return !(*this == Other);
41}
42
44 ++I;
45 return *this;
46}
47
49 CtorDtorIterator Temp = *this;
50 ++I;
51 return Temp;
52}
53
55 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(I));
56 assert(CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors");
57
58 Constant *FuncC = CS->getOperand(1);
59 Function *Func = nullptr;
60
61 // Extract function pointer, pulling off any casts.
62 while (FuncC) {
63 if (Function *F = dyn_cast_or_null<Function>(FuncC)) {
64 Func = F;
65 break;
66 } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
67 if (CE->isCast())
68 FuncC = CE->getOperand(0);
69 else
70 break;
71 } else {
72 // This isn't anything we recognize. Bail out with Func left set to null.
73 break;
74 }
75 }
76
77 auto *Priority = cast<ConstantInt>(CS->getOperand(0));
78 Value *Data = CS->getNumOperands() == 3 ? CS->getOperand(2) : nullptr;
79 if (Data && !isa<GlobalValue>(Data))
80 Data = nullptr;
81 return Element(Priority->getZExtValue(), Func, Data);
82}
83
85 const GlobalVariable *CtorsList = M.getNamedGlobal("llvm.global_ctors");
86 return make_range(CtorDtorIterator(CtorsList, false),
87 CtorDtorIterator(CtorsList, true));
88}
89
91 const GlobalVariable *DtorsList = M.getNamedGlobal("llvm.global_dtors");
92 return make_range(CtorDtorIterator(DtorsList, false),
93 CtorDtorIterator(DtorsList, true));
94}
95
96bool StaticInitGVIterator::isStaticInitGlobal(GlobalValue &GV) {
97 if (GV.isDeclaration())
98 return false;
99
100 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
101 GV.getName() == "llvm.global_dtors"))
102 return true;
103
104 if (ObjFmt == Triple::MachO) {
105 // FIXME: These section checks are too strict: We should match first and
106 // second word split by comma.
107 if (GV.hasSection() &&
108 (GV.getSection().starts_with("__DATA,__objc_classlist") ||
109 GV.getSection().starts_with("__DATA,__objc_selrefs")))
110 return true;
111 }
112
113 return false;
114}
115
117 if (CtorDtors.empty())
118 return;
119
120 MangleAndInterner Mangle(
122 (*CtorDtors.begin()).Func->getDataLayout());
123
124 for (auto CtorDtor : CtorDtors) {
125 assert(CtorDtor.Func && CtorDtor.Func->hasName() &&
126 "Ctor/Dtor function must be named to be runnable under the JIT");
127
128 // FIXME: Maybe use a symbol promoter here instead.
129 if (CtorDtor.Func->hasLocalLinkage()) {
130 CtorDtor.Func->setLinkage(GlobalValue::ExternalLinkage);
131 CtorDtor.Func->setVisibility(GlobalValue::HiddenVisibility);
132 }
133
134 if (CtorDtor.Data && cast<GlobalValue>(CtorDtor.Data)->isDeclaration()) {
135 dbgs() << " Skipping because why now?\n";
136 continue;
137 }
138
139 CtorDtorsByPriority[CtorDtor.Priority].push_back(
140 Mangle(CtorDtor.Func->getName()));
141 }
142}
143
145 using CtorDtorTy = void (*)();
146
147 SymbolLookupSet LookupSet;
148 for (auto &KV : CtorDtorsByPriority)
149 for (auto &Name : KV.second)
150 LookupSet.add(Name);
151 assert(!LookupSet.containsDuplicates() &&
152 "Ctor/Dtor list contains duplicates");
153
154 auto &ES = JD.getExecutionSession();
155 if (auto CtorDtorMap = ES.lookup(
157 std::move(LookupSet))) {
158 for (auto &KV : CtorDtorsByPriority) {
159 for (auto &Name : KV.second) {
160 assert(CtorDtorMap->count(Name) && "No entry for Name");
161 auto CtorDtor = (*CtorDtorMap)[Name].getAddress().toPtr<CtorDtorTy>();
162 CtorDtor();
163 }
164 }
165 CtorDtorsByPriority.clear();
166 return Error::success();
167 } else
168 return CtorDtorMap.takeError();
169}
170
172 auto& CXXDestructorDataPairs = DSOHandleOverride;
173 for (auto &P : CXXDestructorDataPairs)
174 P.first(P.second);
175 CXXDestructorDataPairs.clear();
176}
177
179 void *Arg,
180 void *DSOHandle) {
181 auto& CXXDestructorDataPairs =
182 *reinterpret_cast<CXXDestructorDataPairList*>(DSOHandle);
183 CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
184 return 0;
185}
186
188 MangleAndInterner &Mangle) {
189 SymbolMap RuntimeInterposes;
190 RuntimeInterposes[Mangle("__dso_handle")] = {
192 RuntimeInterposes[Mangle("__cxa_atexit")] = {
194
195 return JD.define(absoluteSymbols(std::move(RuntimeInterposes)));
196}
197
198void ItaniumCXAAtExitSupport::registerAtExit(void (*F)(void *), void *Ctx,
199 void *DSOHandle) {
200 std::lock_guard<std::mutex> Lock(AtExitsMutex);
201 AtExitRecords[DSOHandle].push_back({F, Ctx});
202}
203
205 std::vector<AtExitRecord> AtExitsToRun;
206
207 {
208 std::lock_guard<std::mutex> Lock(AtExitsMutex);
209 auto I = AtExitRecords.find(DSOHandle);
210 if (I != AtExitRecords.end()) {
211 AtExitsToRun = std::move(I->second);
212 AtExitRecords.erase(I);
213 }
214 }
215
216 while (!AtExitsToRun.empty()) {
217 AtExitsToRun.back().F(AtExitsToRun.back().Ctx);
218 AtExitsToRun.pop_back();
219 }
220}
221
224 AddAbsoluteSymbolsFn AddAbsoluteSymbols)
225 : Dylib(std::move(Dylib)), Allow(std::move(Allow)),
226 AddAbsoluteSymbols(std::move(AddAbsoluteSymbols)),
228
231 SymbolPredicate Allow,
232 AddAbsoluteSymbolsFn AddAbsoluteSymbols) {
233 std::string ErrMsg;
234 auto Lib = sys::DynamicLibrary::getPermanentLibrary(FileName, &ErrMsg);
235 if (!Lib.isValid())
236 return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
237 return std::make_unique<DynamicLibrarySearchGenerator>(
238 std::move(Lib), GlobalPrefix, std::move(Allow),
239 std::move(AddAbsoluteSymbols));
240}
241
243 LookupState &LS, LookupKind K, JITDylib &JD,
244 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
245 orc::SymbolMap NewSymbols;
246
247 bool HasGlobalPrefix = (GlobalPrefix != '\0');
248
249 for (auto &KV : Symbols) {
250 auto &Name = KV.first;
251
252 if ((*Name).empty())
253 continue;
254
255 if (Allow && !Allow(Name))
256 continue;
257
258 if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
259 continue;
260
261 std::string Tmp((*Name).data() + HasGlobalPrefix,
262 (*Name).size() - HasGlobalPrefix);
263 if (void *P = Dylib.getAddressOfSymbol(Tmp.c_str()))
265 }
266
267 if (NewSymbols.empty())
268 return Error::success();
269
270 if (AddAbsoluteSymbols)
271 return AddAbsoluteSymbols(JD, std::move(NewSymbols));
272 return JD.define(absoluteSymbols(std::move(NewSymbols)));
273}
274
277 ObjectLayer &L, const char *FileName,
278 GetObjectFileInterface GetObjFileInterface) {
279
280 auto B = object::createBinary(FileName);
281 if (!B)
282 return createFileError(FileName, B.takeError());
283
284 // If this is a regular archive then create an instance from it.
285 if (isa<object::Archive>(B->getBinary())) {
286 auto [Archive, ArchiveBuffer] = B->takeBinary();
287 return Create(L, std::move(ArchiveBuffer),
288 std::unique_ptr<object::Archive>(
289 static_cast<object::Archive *>(Archive.release())),
290 std::move(GetObjFileInterface));
291 }
292
293 // If this is a universal binary then search for a slice matching the given
294 // Triple.
295 if (auto *UB = dyn_cast<object::MachOUniversalBinary>(B->getBinary())) {
296
297 const auto &TT = L.getExecutionSession().getTargetTriple();
298
299 auto SliceRange = getMachOSliceRangeForTriple(*UB, TT);
300 if (!SliceRange)
301 return SliceRange.takeError();
302
303 auto SliceBuffer = MemoryBuffer::getFileSlice(FileName, SliceRange->second,
304 SliceRange->first);
305 if (!SliceBuffer)
306 return make_error<StringError>(
307 Twine("Could not create buffer for ") + TT.str() + " slice of " +
308 FileName + ": [ " + formatv("{0:x}", SliceRange->first) + " .. " +
309 formatv("{0:x}", SliceRange->first + SliceRange->second) + ": " +
310 SliceBuffer.getError().message(),
311 SliceBuffer.getError());
312
313 return Create(L, std::move(*SliceBuffer), std::move(GetObjFileInterface));
314 }
315
316 return make_error<StringError>(Twine("Unrecognized file type for ") +
317 FileName,
319}
320
323 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
324 std::unique_ptr<object::Archive> Archive,
325 GetObjectFileInterface GetObjFileInterface) {
326
327 Error Err = Error::success();
328
329 std::unique_ptr<StaticLibraryDefinitionGenerator> ADG(
331 L, std::move(ArchiveBuffer), std::move(Archive),
332 std::move(GetObjFileInterface), Err));
333
334 if (Err)
335 return std::move(Err);
336
337 return std::move(ADG);
338}
339
342 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
343 GetObjectFileInterface GetObjFileInterface) {
344
345 auto B = object::createBinary(ArchiveBuffer->getMemBufferRef());
346 if (!B)
347 return B.takeError();
348
349 // If this is a regular archive then create an instance from it.
350 if (isa<object::Archive>(*B))
351 return Create(L, std::move(ArchiveBuffer),
352 std::unique_ptr<object::Archive>(
353 static_cast<object::Archive *>(B->release())),
354 std::move(GetObjFileInterface));
355
356 // If this is a universal binary then search for a slice matching the given
357 // Triple.
358 if (auto *UB = dyn_cast<object::MachOUniversalBinary>(B->get())) {
359
360 const auto &TT = L.getExecutionSession().getTargetTriple();
361
362 auto SliceRange = getMachOSliceRangeForTriple(*UB, TT);
363 if (!SliceRange)
364 return SliceRange.takeError();
365
366 MemoryBufferRef SliceRef(
367 StringRef(ArchiveBuffer->getBufferStart() + SliceRange->first,
368 SliceRange->second),
369 ArchiveBuffer->getBufferIdentifier());
370
371 auto Archive = object::Archive::create(SliceRef);
372 if (!Archive)
373 return Archive.takeError();
374
375 return Create(L, std::move(ArchiveBuffer), std::move(*Archive),
376 std::move(GetObjFileInterface));
377 }
378
379 return make_error<StringError>(Twine("Unrecognized file type for ") +
380 ArchiveBuffer->getBufferIdentifier(),
382}
383
385 LookupState &LS, LookupKind K, JITDylib &JD,
386 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
387 // Don't materialize symbols from static archives unless this is a static
388 // lookup.
389 if (K != LookupKind::Static)
390 return Error::success();
391
392 // Bail out early if we've already freed the archive.
393 if (!Archive)
394 return Error::success();
395
397
398 for (const auto &KV : Symbols) {
399 const auto &Name = KV.first;
400 if (!ObjectFilesMap.count(Name))
401 continue;
402 auto ChildBuffer = ObjectFilesMap[Name];
403 ChildBufferInfos.insert(
404 {ChildBuffer.getBuffer(), ChildBuffer.getBufferIdentifier()});
405 }
406
407 for (auto ChildBufferInfo : ChildBufferInfos) {
408 MemoryBufferRef ChildBufferRef(ChildBufferInfo.first,
409 ChildBufferInfo.second);
410
411 auto I = GetObjFileInterface(L.getExecutionSession(), ChildBufferRef);
412 if (!I)
413 return I.takeError();
414
415 if (auto Err = L.add(JD, MemoryBuffer::getMemBuffer(ChildBufferRef, false),
416 std::move(*I)))
417 return Err;
418 }
419
420 return Error::success();
421}
422
423Error StaticLibraryDefinitionGenerator::buildObjectFilesMap() {
425 DenseSet<uint64_t> Visited;
426 DenseSet<uint64_t> Excluded;
427 StringSaver FileNames(ObjFileNameStorage);
428 for (auto &S : Archive->symbols()) {
429 StringRef SymName = S.getName();
430 auto Member = S.getMember();
431 if (!Member)
432 return Member.takeError();
433 auto DataOffset = Member->getDataOffset();
434 if (!Visited.count(DataOffset)) {
435 Visited.insert(DataOffset);
436 auto Child = Member->getAsBinary();
437 if (!Child)
438 return Child.takeError();
439 if ((*Child)->isCOFFImportFile()) {
440 ImportedDynamicLibraries.insert((*Child)->getFileName().str());
441 Excluded.insert(DataOffset);
442 continue;
443 }
444
445 // Give members of the archive a name that contains the archive path so
446 // that they can be differentiated from a member with the same name in a
447 // different archive. This also ensure initializer symbols names will be
448 // unique within a JITDylib.
449 StringRef FullName = FileNames.save(Archive->getFileName() + "(" +
450 (*Child)->getFileName() + ")");
451 MemoryBufferRef MemBuffer((*Child)->getMemoryBufferRef().getBuffer(),
452 FullName);
453
454 MemoryBuffers[DataOffset] = MemBuffer;
455 }
456 if (!Excluded.count(DataOffset))
457 ObjectFilesMap[L.getExecutionSession().intern(SymName)] =
458 MemoryBuffers[DataOffset];
459 }
460
461 return Error::success();
462}
463
464StaticLibraryDefinitionGenerator::StaticLibraryDefinitionGenerator(
465 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
466 std::unique_ptr<object::Archive> Archive,
467 GetObjectFileInterface GetObjFileInterface, Error &Err)
468 : L(L), GetObjFileInterface(std::move(GetObjFileInterface)),
469 ArchiveBuffer(std::move(ArchiveBuffer)), Archive(std::move(Archive)) {
470 ErrorAsOutParameter _(&Err);
471 if (!this->GetObjFileInterface)
472 this->GetObjFileInterface = getObjectFileInterface;
473 if (!Err)
474 Err = buildObjectFilesMap();
475}
476
477std::unique_ptr<DLLImportDefinitionGenerator>
480 return std::unique_ptr<DLLImportDefinitionGenerator>(
482}
483
485 LookupState &LS, LookupKind K, JITDylib &JD,
486 JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) {
487 JITDylibSearchOrder LinkOrder;
488 JD.withLinkOrderDo([&](const JITDylibSearchOrder &LO) {
489 LinkOrder.reserve(LO.size());
490 for (auto &KV : LO) {
491 if (KV.first == &JD)
492 continue;
493 LinkOrder.push_back(KV);
494 }
495 });
496
497 // FIXME: if regular symbol name start with __imp_ we have to issue lookup of
498 // both __imp_ and stripped name and use the lookup information to resolve the
499 // real symbol name.
500 SymbolLookupSet LookupSet;
502 for (auto &KV : Symbols) {
503 StringRef Deinterned = *KV.first;
504 if (Deinterned.starts_with(getImpPrefix()))
505 Deinterned = Deinterned.drop_front(StringRef(getImpPrefix()).size());
506 // Don't degrade the required state
507 if (ToLookUpSymbols.count(Deinterned) &&
508 ToLookUpSymbols[Deinterned] == SymbolLookupFlags::RequiredSymbol)
509 continue;
510 ToLookUpSymbols[Deinterned] = KV.second;
511 }
512
513 for (auto &KV : ToLookUpSymbols)
514 LookupSet.add(ES.intern(KV.first), KV.second);
515
516 auto Resolved =
517 ES.lookup(LinkOrder, LookupSet, LookupKind::DLSym, SymbolState::Resolved);
518 if (!Resolved)
519 return Resolved.takeError();
520
521 auto G = createStubsGraph(*Resolved);
522 if (!G)
523 return G.takeError();
524 return L.add(JD, std::move(*G));
525}
526
528DLLImportDefinitionGenerator::getTargetPointerSize(const Triple &TT) {
529 switch (TT.getArch()) {
530 case Triple::x86_64:
531 return 8;
532 default:
533 return make_error<StringError>(
534 "architecture unsupported by DLLImportDefinitionGenerator",
536 }
537}
538
539Expected<llvm::endianness>
540DLLImportDefinitionGenerator::getEndianness(const Triple &TT) {
541 switch (TT.getArch()) {
542 case Triple::x86_64:
544 default:
545 return make_error<StringError>(
546 "architecture unsupported by DLLImportDefinitionGenerator",
548 }
549}
550
551Expected<std::unique_ptr<jitlink::LinkGraph>>
552DLLImportDefinitionGenerator::createStubsGraph(const SymbolMap &Resolved) {
553 Triple TT = ES.getTargetTriple();
554 auto PointerSize = getTargetPointerSize(TT);
555 if (!PointerSize)
556 return PointerSize.takeError();
557 auto Endianness = getEndianness(TT);
558 if (!Endianness)
559 return Endianness.takeError();
560
561 auto G = std::make_unique<jitlink::LinkGraph>(
562 "<DLLIMPORT_STUBS>", TT, *PointerSize, *Endianness,
564 jitlink::Section &Sec =
565 G->createSection(getSectionName(), MemProt::Read | MemProt::Exec);
566
567 for (auto &KV : Resolved) {
568 jitlink::Symbol &Target = G->addAbsoluteSymbol(
569 *KV.first, KV.second.getAddress(), *PointerSize,
571
572 // Create __imp_ symbol
573 jitlink::Symbol &Ptr =
575 auto NameCopy = G->allocateContent(Twine(getImpPrefix()) + *KV.first);
576 StringRef NameCopyRef = StringRef(NameCopy.data(), NameCopy.size());
577 Ptr.setName(NameCopyRef);
578 Ptr.setLinkage(jitlink::Linkage::Strong);
580
581 // Create PLT stub
582 // FIXME: check PLT stub of data symbol is not accessed
583 jitlink::Block &StubBlock =
585 G->addDefinedSymbol(StubBlock, 0, *KV.first, StubBlock.getSize(),
587 false);
588 }
589
590 return std::move(G);
591}
592
593} // End namespace orc.
594} // End namespace llvm.
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
@ GlobalPrefix
Definition: AsmWriter.cpp:376
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::string Name
bool End
Definition: ELF_riscv.cpp:480
#define _
#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
Module.h This file contains the declarations for the Module class.
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ConstantArray - Constant Array Declarations.
Definition: Constants.h:424
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1097
This is an important base class in LLVM.
Definition: Constant.h:42
bool empty() const
Definition: DenseMap.h:98
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:151
Implements a dense probed hash-table based set.
Definition: DenseSet.h:271
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:290
StringRef getSection() const
Definition: Globals.cpp:183
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
bool hasSection() const
Definition: GlobalValue.h:290
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Map a subrange of the specified file as a MemoryBuffer.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:250
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:594
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition: StringSaver.h:21
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
Value * getOperand(unsigned i) const
Definition: User.h:169
unsigned getNumOperands() const
Definition: User.h:191
LLVM Value Representation.
Definition: Value.h:74
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
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:97
A range adaptor for a pair of iterators.
IteratorT begin() const
static Expected< std::unique_ptr< Archive > > create(MemoryBufferRef Source)
Definition: Archive.cpp:669
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm....
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
Element operator*() const
Dereference iterator.
CtorDtorIterator(const GlobalVariable *GV, bool End)
Construct an iterator instance.
CtorDtorIterator & operator++()
Pre-increment iterator.
bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
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:1431
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition: Core.h:1474
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1485
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:1810
static ExecutorAddr fromPtr(T *Ptr, UnwrapFn &&Unwrap=UnwrapFn())
Create an ExecutorAddr from the given pointer.
void registerAtExit(void(*F)(void *), void *Ctx, void *DSOHandle)
Represents a JIT'd dynamic library.
Definition: Core.h:989
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:1910
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition: Core.h:1008
auto withLinkOrderDo(Func &&F) -> decltype(F(std::declval< const JITDylibSearchOrder & >()))
Do something with the link order (run under the session lock).
Definition: Core.h:1903
static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
CXXDestructorDataPairList DSOHandleOverride
void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
Error enable(JITDylib &JD, MangleAndInterner &Mangler)
Wraps state for a lookup-in-progress.
Definition: Core.h:921
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Mangling.h:26
Interface for Layers that accept object files.
Definition: Layer.h:133
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:170
ExecutionSession & getExecutionSession()
Returns the execution session for this layer.
Definition: Layer.h:141
An ObjectLayer implementation built on JITLink.
A utility class to expose symbols from a static library.
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName, GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibraryDefinitionGenerator from the given path.
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, GetObjectFileInterface GetObjFileInterface=GetObjectFileInterface())
Try to create a StaticLibrarySearchGenerator from the given memory buffer and Archive object.
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:183
SymbolLookupSet & add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
Definition: Core.h:244
bool containsDuplicates()
Returns true if this set contains any duplicates.
Definition: Core.h:371
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
static 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...
void * getAddressOfSymbol(const char *symbolName)
Searches through the library for the symbol symbolName.
constexpr llvm::endianness Endianness
The endianness of all multi-byte encoded values in MessagePack.
Definition: MsgPack.h:24
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:166
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:162
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
Definition: Core.h:791
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:135
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
Definition: Core.h:121
Expected< MaterializationUnit::Interface > getObjectFileInterface(ExecutionSession &ES, MemoryBufferRef ObjBuffer)
Returns a MaterializationUnit::Interface for the object file contained in the given buffer,...
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:133
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:157
@ Resolved
Queried, materialization begun.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition: Error.h:1380
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:1680
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 formatv(const char *Fmt, Ts &&...Vals) -> formatv_object< decltype(std::make_tuple(support::detail::build_format_adapter(std::forward< Ts >(Vals))...))>
auto dyn_cast_or_null(const Y &Val)
Definition: Casting.h:759
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
@ 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:1856
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Accessor for an element of the global_ctors/global_dtors array.