LLVM 17.0.0git
ExecutionUtils.h
Go to the documentation of this file.
1//===- ExecutionUtils.h - Utilities for executing code in Orc ---*- C++ -*-===//
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//
9// Contains utilities for executing code in Orc.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
14#define LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
15
16#include "llvm/ADT/StringMap.h"
24#include "llvm/Object/Archive.h"
26#include <algorithm>
27#include <cstdint>
28#include <utility>
29#include <vector>
30
31namespace llvm {
32
33class ConstantArray;
34class GlobalVariable;
35class Function;
36class Module;
37class Value;
38
39namespace object {
40class MachOUniversalBinary;
41}
42
43namespace orc {
44
45class ObjectLayer;
46
47/// This iterator provides a convenient way to iterate over the elements
48/// of an llvm.global_ctors/llvm.global_dtors instance.
49///
50/// The easiest way to get hold of instances of this class is to use the
51/// getConstructors/getDestructors functions.
53public:
54 /// Accessor for an element of the global_ctors/global_dtors array.
55 ///
56 /// This class provides a read-only view of the element with any casts on
57 /// the function stripped away.
58 struct Element {
61
62 unsigned Priority;
65 };
66
67 /// Construct an iterator instance. If End is true then this iterator
68 /// acts as the end of the range, otherwise it is the beginning.
69 CtorDtorIterator(const GlobalVariable *GV, bool End);
70
71 /// Test iterators for equality.
72 bool operator==(const CtorDtorIterator &Other) const;
73
74 /// Test iterators for inequality.
75 bool operator!=(const CtorDtorIterator &Other) const;
76
77 /// Pre-increment iterator.
79
80 /// Post-increment iterator.
82
83 /// Dereference iterator. The resulting value provides a read-only view
84 /// of this element of the global_ctors/global_dtors list.
85 Element operator*() const;
86
87private:
88 const ConstantArray *InitList;
89 unsigned I;
90};
91
92/// Create an iterator range over the entries of the llvm.global_ctors
93/// array.
95
96/// Create an iterator range over the entries of the llvm.global_ctors
97/// array.
99
100/// This iterator provides a convenient way to iterate over GlobalValues that
101/// have initialization effects.
103public:
105
107 : I(M.global_values().begin()), E(M.global_values().end()),
108 ObjFmt(Triple(M.getTargetTriple()).getObjectFormat()) {
109 if (I != E) {
110 if (!isStaticInitGlobal(*I))
111 moveToNextStaticInitGlobal();
112 } else
114 }
115
116 bool operator==(const StaticInitGVIterator &O) const { return I == O.I; }
117 bool operator!=(const StaticInitGVIterator &O) const { return I != O.I; }
118
120 assert(I != E && "Increment past end of range");
121 moveToNextStaticInitGlobal();
122 return *this;
123 }
124
125 GlobalValue &operator*() { return *I; }
126
127private:
128 bool isStaticInitGlobal(GlobalValue &GV);
129 void moveToNextStaticInitGlobal() {
130 ++I;
131 while (I != E && !isStaticInitGlobal(*I))
132 ++I;
133 if (I == E)
135 }
136
139};
140
141/// Create an iterator range over the GlobalValues that contribute to static
142/// initialization.
145}
146
148public:
149 CtorDtorRunner(JITDylib &JD) : JD(JD) {}
151 Error run();
152
153private:
154 using CtorDtorList = std::vector<SymbolStringPtr>;
155 using CtorDtorPriorityMap = std::map<unsigned, CtorDtorList>;
156
157 JITDylib &JD;
158 CtorDtorPriorityMap CtorDtorsByPriority;
159};
160
161/// Support class for static dtor execution. For hosted (in-process) JITs
162/// only!
163///
164/// If a __cxa_atexit function isn't found C++ programs that use static
165/// destructors will fail to link. However, we don't want to use the host
166/// process's __cxa_atexit, because it will schedule JIT'd destructors to run
167/// after the JIT has been torn down, which is no good. This class makes it easy
168/// to override __cxa_atexit (and the related __dso_handle).
169///
170/// To use, clients should manually call searchOverrides from their symbol
171/// resolver. This should generally be done after attempting symbol resolution
172/// inside the JIT, but before searching the host process's symbol table. When
173/// the client determines that destructors should be run (generally at JIT
174/// teardown or after a return from main), the runDestructors method should be
175/// called.
177public:
178 /// Run any destructors recorded by the overriden __cxa_atexit function
179 /// (CXAAtExitOverride).
180 void runDestructors();
181
182protected:
183 using DestructorPtr = void (*)(void *);
184 using CXXDestructorDataPair = std::pair<DestructorPtr, void *>;
185 using CXXDestructorDataPairList = std::vector<CXXDestructorDataPair>;
187 static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg,
188 void *DSOHandle);
189};
190
192public:
194};
195
196/// An interface for Itanium __cxa_atexit interposer implementations.
198public:
200 void (*F)(void *);
201 void *Ctx;
202 };
203
204 void registerAtExit(void (*F)(void *), void *Ctx, void *DSOHandle);
205 void runAtExits(void *DSOHandle);
206
207private:
208 std::mutex AtExitsMutex;
210};
211
212/// A utility class to expose symbols found via dlsym to the JIT.
213///
214/// If an instance of this class is attached to a JITDylib as a fallback
215/// definition generator, then any symbol found in the given DynamicLibrary that
216/// passes the 'Allow' predicate will be added to the JITDylib.
218public:
219 using SymbolPredicate = std::function<bool(const SymbolStringPtr &)>;
220
221 /// Create a DynamicLibrarySearchGenerator that searches for symbols in the
222 /// given sys::DynamicLibrary.
223 ///
224 /// If the Allow predicate is given then only symbols matching the predicate
225 /// will be searched for. If the predicate is not given then all symbols will
226 /// be searched for.
227 DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix,
229
230 /// Permanently loads the library at the given path and, on success, returns
231 /// a DynamicLibrarySearchGenerator that will search it for symbol definitions
232 /// in the library. On failure returns the reason the library failed to load.
234 Load(const char *FileName, char GlobalPrefix,
236
237 /// Creates a DynamicLibrarySearchGenerator that searches for symbols in
238 /// the current process.
240 GetForCurrentProcess(char GlobalPrefix,
242 return Load(nullptr, GlobalPrefix, std::move(Allow));
243 }
244
246 JITDylibLookupFlags JDLookupFlags,
247 const SymbolLookupSet &Symbols) override;
248
249private:
251 SymbolPredicate Allow;
252 char GlobalPrefix;
253};
254
255/// A utility class to expose symbols from a static library.
256///
257/// If an instance of this class is attached to a JITDylib as a fallback
258/// definition generator, then any symbol found in the archive will result in
259/// the containing object being added to the JITDylib.
261public:
262 // Interface builder function for objects loaded from this archive.
265 ExecutionSession &ES, MemoryBufferRef ObjBuffer)>;
266
267 /// Try to create a StaticLibraryDefinitionGenerator from the given path.
268 ///
269 /// This call will succeed if the file at the given path is a static library
270 /// or a MachO universal binary containing a static library that is compatible
271 /// with the ExecutionSession's triple. Otherwise it will return an error.
273 Load(ObjectLayer &L, const char *FileName,
274 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
275
276 /// Try to create a StaticLibrarySearchGenerator from the given memory buffer
277 /// and Archive object.
279 Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
280 std::unique_ptr<object::Archive> Archive,
281 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
282
283 /// Try to create a StaticLibrarySearchGenerator from the given memory buffer.
284 /// This call will succeed if the buffer contains a valid archive, otherwise
285 /// it will return an error.
286 ///
287 /// This call will succeed if the buffer contains a valid static library or a
288 /// MachO universal binary containing a static library that is compatible
289 /// with the ExecutionSession's triple. Otherwise it will return an error.
291 Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
292 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
293
294 /// Returns a list of filenames of dynamic libraries that this archive has
295 /// imported. This class does not load these libraries by itself. User is
296 /// responsible for making sure these libraries are avaliable to the JITDylib.
297 const std::set<std::string> &getImportedDynamicLibraries() const {
298 return ImportedDynamicLibraries;
299 }
300
302 JITDylibLookupFlags JDLookupFlags,
303 const SymbolLookupSet &Symbols) override;
304
305private:
307 std::unique_ptr<MemoryBuffer> ArchiveBuffer,
308 std::unique_ptr<object::Archive> Archive,
309 GetObjectFileInterface GetObjFileInterface,
310 Error &Err);
311 Error buildObjectFilesMap();
312
314 getSliceRangeForArch(object::MachOUniversalBinary &UB, const Triple &TT);
315
316 ObjectLayer &L;
317 GetObjectFileInterface GetObjFileInterface;
318 std::set<std::string> ImportedDynamicLibraries;
319 std::unique_ptr<MemoryBuffer> ArchiveBuffer;
320 std::unique_ptr<object::Archive> Archive;
322};
323
324/// A utility class to create COFF dllimport GOT symbols (__imp_*) and PLT
325/// stubs.
326///
327/// If an instance of this class is attached to a JITDylib as a fallback
328/// definition generator, PLT stubs and dllimport __imp_ symbols will be
329/// generated for external symbols found outside the given jitdylib. Currently
330/// only supports x86_64 architecture.
332public:
333 /// Creates a DLLImportDefinitionGenerator instance.
334 static std::unique_ptr<DLLImportDefinitionGenerator>
336
338 JITDylibLookupFlags JDLookupFlags,
339 const SymbolLookupSet &Symbols) override;
340
341private:
343 : ES(ES), L(L) {}
344
345 static Expected<unsigned> getTargetPointerSize(const Triple &TT);
346 static Expected<support::endianness> getTargetEndianness(const Triple &TT);
348 createStubsGraph(const SymbolMap &Resolved);
349
350 static StringRef getImpPrefix() { return "__imp_"; }
351
352 static StringRef getSectionName() { return "$__DLLIMPORT_STUBS"; }
353
356};
357
358} // end namespace orc
359} // end namespace llvm
360
361#endif // LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
This file defines the StringMap class.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
@ GlobalPrefix
Definition: AsmWriter.cpp:351
bool End
Definition: ELF_riscv.cpp:464
#define F(x, y, z)
Definition: MD5.cpp:55
Machine Check Debug Module
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ConstantArray - Constant Array Declarations.
Definition: Constants.h:408
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
Tagged union holding either a T or a Error.
Definition: Error.h:470
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
concat_iterator< GlobalValue, iterator, global_iterator, alias_iterator, ifunc_iterator > global_value_iterator
Definition: Module.h:747
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
ObjectFormatType
Definition: Triple.h:281
LLVM Value Representation.
Definition: Value.h:74
A range adaptor for a pair of iterators.
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 & 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.
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition: Core.h:914
A utility class to expose symbols found via dlsym to the JIT.
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > GetForCurrentProcess(char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Creates a DynamicLibrarySearchGenerator that searches for symbols in the current process.
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
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< DynamicLibrarySearchGenerator > > Load(const char *FileName, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Permanently loads the library at the given path and, on success, returns a DynamicLibrarySearchGenera...
An ExecutionSession represents a running JIT program.
Definition: Core.h:1364
An interface for Itanium __cxa_atexit interposer implementations.
void registerAtExit(void(*F)(void *), void *Ctx, void *DSOHandle)
Represents a JIT'd dynamic library.
Definition: Core.h:950
Support class for static dtor execution.
static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
CXXDestructorDataPairList DSOHandleOverride
std::pair< DestructorPtr, void * > CXXDestructorDataPair
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:889
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
An ObjectLayer implementation built on JITLink.
This iterator provides a convenient way to iterate over GlobalValues that have initialization effects...
StaticInitGVIterator & operator++()
bool operator!=(const StaticInitGVIterator &O) const
bool operator==(const StaticInitGVIterator &O) const
A utility class to expose symbols from a static library.
const std::set< std::string > & getImportedDynamicLibraries() const
Returns a list of filenames of dynamic libraries that this archive has imported.
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.
unique_function< Expected< MaterializationUnit::Interface >(ExecutionSession &ES, MemoryBufferRef ObjBuffer)> GetObjectFileInterface
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:182
Pointer to a pooled string representing a symbol name.
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
iterator_range< StaticInitGVIterator > getStaticInitGVs(Module &M)
Create an iterator range over the GlobalValues that contribute to static initialization.
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:134
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:156
@ Resolved
Queried, materialization begun.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Accessor for an element of the global_ctors/global_dtors array.
Element(unsigned Priority, Function *Func, Value *Data)