LLVM 24.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
23#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 orc {
40
41class ObjectLayer;
42
43/// This iterator provides a convenient way to iterate over the elements
44/// of an llvm.global_ctors/llvm.global_dtors instance.
45///
46/// The easiest way to get hold of instances of this class is to use the
47/// getConstructors/getDestructors functions.
49public:
50 /// Accessor for an element of the global_ctors/global_dtors array.
51 ///
52 /// This class provides a read-only view of the element with any casts on
53 /// the function stripped away.
62
63 /// Construct an iterator instance. If End is true then this iterator
64 /// acts as the end of the range, otherwise it is the beginning.
66
67 /// Test iterators for equality.
68 LLVM_ABI bool operator==(const CtorDtorIterator &Other) const;
69
70 /// Test iterators for inequality.
71 LLVM_ABI bool operator!=(const CtorDtorIterator &Other) const;
72
73 /// Pre-increment iterator.
75
76 /// Post-increment iterator.
78
79 /// Dereference iterator. The resulting value provides a read-only view
80 /// of this element of the global_ctors/global_dtors list.
82
83private:
84 const ConstantArray *InitList;
85 unsigned I;
86};
87
88/// Create an iterator range over the entries of the llvm.global_ctors
89/// array.
91
92/// Create an iterator range over the entries of the llvm.global_ctors
93/// array.
95
96/// This iterator provides a convenient way to iterate over GlobalValues that
97/// have initialization effects.
99public:
101
103 : I(M.global_values().begin()), E(M.global_values().end()),
104 ObjFmt(M.getTargetTriple().getObjectFormat()) {
105 if (I != E) {
106 if (!isStaticInitGlobal(*I))
107 moveToNextStaticInitGlobal();
108 } else
110 }
111
112 bool operator==(const StaticInitGVIterator &O) const { return I == O.I; }
113 bool operator!=(const StaticInitGVIterator &O) const { return I != O.I; }
114
116 assert(I != E && "Increment past end of range");
117 moveToNextStaticInitGlobal();
118 return *this;
119 }
120
121 GlobalValue &operator*() { return *I; }
122
123private:
124 LLVM_ABI bool isStaticInitGlobal(GlobalValue &GV);
125 void moveToNextStaticInitGlobal() {
126 ++I;
127 while (I != E && !isStaticInitGlobal(*I))
128 ++I;
129 if (I == E)
131 }
132
135};
136
137/// Create an iterator range over the GlobalValues that contribute to static
138/// initialization.
142
144public:
145 CtorDtorRunner(JITDylib &JD) : JD(JD) {}
148
149private:
150 using CtorDtorList = std::vector<SymbolStringPtr>;
151 using CtorDtorPriorityMap = std::map<unsigned, CtorDtorList>;
152
153 JITDylib &JD;
154 CtorDtorPriorityMap CtorDtorsByPriority;
155};
156
157/// Support class for static dtor execution. For hosted (in-process) JITs
158/// only!
159///
160/// If a __cxa_atexit function isn't found C++ programs that use static
161/// destructors will fail to link. However, we don't want to use the host
162/// process's __cxa_atexit, because it will schedule JIT'd destructors to run
163/// after the JIT has been torn down, which is no good. This class makes it easy
164/// to override __cxa_atexit (and the related __dso_handle).
165///
166/// To use, clients should manually call searchOverrides from their symbol
167/// resolver. This should generally be done after attempting symbol resolution
168/// inside the JIT, but before searching the host process's symbol table. When
169/// the client determines that destructors should be run (generally at JIT
170/// teardown or after a return from main), the runDestructors method should be
171/// called.
173public:
174 /// Run any destructors recorded by the overriden __cxa_atexit function
175 /// (CXAAtExitOverride).
177
178protected:
179 using DestructorPtr = void (*)(void *);
180 using CXXDestructorDataPair = std::pair<DestructorPtr, void *>;
181 using CXXDestructorDataPairList = std::vector<CXXDestructorDataPair>;
183 LLVM_ABI static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg,
184 void *DSOHandle);
185};
186
191
192/// An interface for Itanium __cxa_atexit interposer implementations.
194public:
196 void (*F)(void *);
197 void *Ctx;
198 };
199
200 LLVM_ABI void registerAtExit(void (*F)(void *), void *Ctx, void *DSOHandle);
201 LLVM_ABI void runAtExits(void *DSOHandle);
202
203private:
204 std::mutex AtExitsMutex;
206};
207
208/// A utility class to expose symbols found via dlsym to the JIT.
209///
210/// If an instance of this class is attached to a JITDylib as a fallback
211/// definition generator, then any symbol found in the given DynamicLibrary that
212/// passes the 'Allow' predicate will be added to the JITDylib.
214public:
215 using SymbolPredicate = std::function<bool(const SymbolStringPtr &)>;
217
218 /// Create a DynamicLibrarySearchGenerator that searches for symbols in the
219 /// given sys::DynamicLibrary.
220 ///
221 /// If the Allow predicate is given then only symbols matching the predicate
222 /// will be searched for. If the predicate is not given then all symbols will
223 /// be searched for.
224 ///
225 /// If \p AddAbsoluteSymbols is provided, it is used to add the symbols to the
226 /// \c JITDylib; otherwise it uses JD.define(absoluteSymbols(...)).
228 sys::DynamicLibrary Dylib, char GlobalPrefix,
230 AddAbsoluteSymbolsFn AddAbsoluteSymbols = nullptr);
231
232 /// Permanently loads the library at the given path and, on success, returns
233 /// a DynamicLibrarySearchGenerator that will search it for symbol definitions
234 /// in the library. On failure returns the reason the library failed to load.
236 Load(const char *FileName, char GlobalPrefix,
238 AddAbsoluteSymbolsFn AddAbsoluteSymbols = nullptr);
239
240 /// Creates a DynamicLibrarySearchGenerator that searches for symbols in
241 /// the current process.
243 GetForCurrentProcess(char GlobalPrefix,
245 AddAbsoluteSymbolsFn AddAbsoluteSymbols = nullptr) {
246 return Load(nullptr, GlobalPrefix, std::move(Allow),
247 std::move(AddAbsoluteSymbols));
248 }
249
250 Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD,
251 JITDylibLookupFlags JDLookupFlags,
252 const SymbolLookupSet &Symbols) override;
253
254private:
256 SymbolPredicate Allow;
257 AddAbsoluteSymbolsFn AddAbsoluteSymbols;
258 char GlobalPrefix;
259};
260
261/// A utility class to expose symbols from a static library.
262///
263/// If an instance of this class is attached to a JITDylib as a fallback
264/// definition generator, then any symbol found in the archive will result in
265/// the containing object being added to the JITDylib.
266class LLVM_ABI StaticLibraryDefinitionGenerator : public DefinitionGenerator {
267public:
268 /// Interface builder function for objects loaded from this archive.
271 ExecutionSession &ES, MemoryBufferRef ObjBuffer)>;
272
273 /// Callback for visiting archive members at construction time. Can be used
274 /// to pre-load members.
275 ///
276 /// Callbacks are provided with a reference to the underlying archive, a
277 /// MemoryBufferRef covering the bytes for the given member, and the index of
278 /// the given member.
279 ///
280 /// Implementations should return true if the given member file should be
281 /// loadable via the generator, false if it should not, and an Error if the
282 /// member is malformed in a way that renders the archive itself invalid.
283 ///
284 /// Note: Linkers typically ignore invalid files within archives, so it's
285 /// expected that implementations will usually return `false` (i.e.
286 /// not-loadable) for malformed buffers, and will only return an
287 /// Error in exceptional circumstances.
289 object::Archive &, MemoryBufferRef, size_t)>;
290
291 /// A VisitMembersFunction that unconditionally loads all object files from
292 /// the archive.
293 /// Archive members that are not valid object files will be skipped.
295 JITDylib &JD);
296
297 static std::unique_ptr<MemoryBuffer>
298 createMemberBuffer(object::Archive &A, MemoryBufferRef BufRef, size_t Index);
299
300 /// Try to create a StaticLibraryDefinitionGenerator from the given path.
301 ///
302 /// This call will succeed if the file at the given path is a static library
303 /// or a MachO universal binary containing a static library that is compatible
304 /// with the ExecutionSession's triple. Otherwise it will return an error.
306 Load(ObjectLayer &L, const char *FileName,
308 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
309
310 /// Try to create a StaticLibrarySearchGenerator from the given memory buffer
311 /// and Archive object.
313 Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
314 std::unique_ptr<object::Archive> Archive,
316 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
317
318 /// Try to create a StaticLibrarySearchGenerator from the given memory buffer.
319 /// This call will succeed if the buffer contains a valid archive, otherwise
320 /// it will return an error.
321 ///
322 /// This call will succeed if the buffer contains a valid static library or a
323 /// MachO universal binary containing a static library that is compatible
324 /// with the ExecutionSession's triple. Otherwise it will return an error.
326 Create(ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
328 GetObjectFileInterface GetObjFileInterface = GetObjectFileInterface());
329
331 JITDylibLookupFlags JDLookupFlags,
332 const SymbolLookupSet &Symbols) override;
333
334private:
335 StaticLibraryDefinitionGenerator(
336 ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer,
337 std::unique_ptr<object::Archive> Archive,
338 GetObjectFileInterface GetObjFileInterface,
339 DenseMap<SymbolStringPtr, size_t> SymbolToMemberIndexMap);
340
341 ObjectLayer &L;
342 GetObjectFileInterface GetObjFileInterface;
343 std::unique_ptr<MemoryBuffer> ArchiveBuffer;
344 std::unique_ptr<object::Archive> Archive;
345 DenseMap<SymbolStringPtr, size_t> SymbolToMemberIndexMap;
346};
347
348/// A utility class to create COFF dllimport GOT symbols (__imp_*) and PLT
349/// stubs.
350///
351/// If an instance of this class is attached to a JITDylib as a fallback
352/// definition generator, PLT stubs and dllimport __imp_ symbols will be
353/// generated for external symbols found outside the given jitdylib. Currently
354/// only supports x86_64 architecture.
355class LLVM_ABI DLLImportDefinitionGenerator : public DefinitionGenerator {
356public:
357 /// Creates a DLLImportDefinitionGenerator instance.
358 static std::unique_ptr<DLLImportDefinitionGenerator>
360
362 JITDylibLookupFlags JDLookupFlags,
363 const SymbolLookupSet &Symbols) override;
364
365private:
366 DLLImportDefinitionGenerator(ExecutionSession &ES, ObjectLinkingLayer &L)
367 : ES(ES), L(L) {}
368
370 createStubsGraph(const SymbolMap &Resolved);
371
372 static StringRef getImpPrefix() { return "__imp_"; }
373
374 static StringRef getSectionName() { return "$__DLLIMPORT_STUBS"; }
375
378};
379
380} // end namespace orc
381} // end namespace llvm
382
383#endif // LLVM_EXECUTIONENGINE_ORC_EXECUTIONUTILS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
@ GlobalPrefix
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
concat_iterator< GlobalValue, iterator, global_iterator, alias_iterator, ifunc_iterator > global_value_iterator
Definition Module.h:899
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
LLVM Value Representation.
Definition Value.h:75
A range adaptor for a pair of iterators.
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)
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:625
friend class ExecutionSession
Definition Core.h:626
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
unique_function< Error(JITDylib &, SymbolMap)> AddAbsoluteSymbolsFn
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...
static Expected< std::unique_ptr< DynamicLibrarySearchGenerator > > GetForCurrentProcess(char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate(), AddAbsoluteSymbolsFn AddAbsoluteSymbols=nullptr)
Creates a DynamicLibrarySearchGenerator that searches for symbols in the current process.
An interface for Itanium __cxa_atexit interposer implementations.
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:668
Support class for static dtor execution.
static LLVM_ABI int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
CXXDestructorDataPairList DSOHandleOverride
std::pair< DestructorPtr, void * > CXXDestructorDataPair
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:600
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition Mangling.h:28
Applies linker name-mangling for a target.
Definition Mangler.h:31
Interface for Layers that accept object files.
Definition Layer.h:131
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
static VisitMembersFunction loadAllObjectFileMembers(ObjectLayer &L, JITDylib &JD)
A VisitMembersFunction that unconditionally loads all object files from the archive.
unique_function< Expected< MaterializationUnit::Interface >( ExecutionSession &ES, MemoryBufferRef ObjBuffer)> GetObjectFileInterface
Interface builder function for objects loaded from this archive.
unique_function< Expected< bool >( object::Archive &, MemoryBufferRef, size_t)> VisitMembersFunction
Callback for visiting archive members at construction time.
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.
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...
unique_function is a type-erasing functor similar to std::function.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
LLVM_ABI 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.
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.
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LookupKind
Describes the kind of lookup being performed.
Definition Core.h:138
@ Resolved
Queried, materialization begun.
Definition Core.h:543
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
@ Other
Any other memory.
Definition ModRef.h:68
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
Accessor for an element of the global_ctors/global_dtors array.
Element(unsigned Priority, Function *Func, Value *Data)