LLVM  10.0.0
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 
10 
12 #include "llvm/IR/Constants.h"
13 #include "llvm/IR/Function.h"
14 #include "llvm/IR/GlobalVariable.h"
15 #include "llvm/IR/Module.h"
18 
19 namespace llvm {
20 namespace orc {
21 
22 int runAsMain(int (*Main)(int, char *[]), ArrayRef<std::string> Args,
23  Optional<StringRef> ProgramName) {
24  std::vector<std::unique_ptr<char[]>> ArgVStorage;
25  std::vector<char *> ArgV;
26 
27  ArgVStorage.reserve(Args.size() + (ProgramName ? 1 : 0));
28  ArgV.reserve(Args.size() + 1 + (ProgramName ? 1 : 0));
29 
30  if (ProgramName) {
31  ArgVStorage.push_back(std::make_unique<char[]>(ProgramName->size() + 1));
32  llvm::copy(*ProgramName, &ArgVStorage.back()[0]);
33  ArgVStorage.back()[ProgramName->size()] = '\0';
34  ArgV.push_back(ArgVStorage.back().get());
35  }
36 
37  for (auto &Arg : Args) {
38  ArgVStorage.push_back(std::make_unique<char[]>(Arg.size() + 1));
39  llvm::copy(Arg, &ArgVStorage.back()[0]);
40  ArgVStorage.back()[Arg.size()] = '\0';
41  ArgV.push_back(ArgVStorage.back().get());
42  }
43  ArgV.push_back(nullptr);
44 
45  return Main(Args.size() + !!ProgramName, ArgV.data());
46 }
47 
49  : InitList(
50  GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
51  I((InitList && End) ? InitList->getNumOperands() : 0) {
52 }
53 
55  assert(InitList == Other.InitList && "Incomparable iterators.");
56  return I == Other.I;
57 }
58 
60  return !(*this == Other);
61 }
62 
64  ++I;
65  return *this;
66 }
67 
69  CtorDtorIterator Temp = *this;
70  ++I;
71  return Temp;
72 }
73 
75  ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(I));
76  assert(CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors");
77 
78  Constant *FuncC = CS->getOperand(1);
79  Function *Func = nullptr;
80 
81  // Extract function pointer, pulling off any casts.
82  while (FuncC) {
83  if (Function *F = dyn_cast_or_null<Function>(FuncC)) {
84  Func = F;
85  break;
86  } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
87  if (CE->isCast())
88  FuncC = dyn_cast_or_null<ConstantExpr>(CE->getOperand(0));
89  else
90  break;
91  } else {
92  // This isn't anything we recognize. Bail out with Func left set to null.
93  break;
94  }
95  }
96 
97  auto *Priority = cast<ConstantInt>(CS->getOperand(0));
98  Value *Data = CS->getNumOperands() == 3 ? CS->getOperand(2) : nullptr;
99  if (Data && !isa<GlobalValue>(Data))
100  Data = nullptr;
101  return Element(Priority->getZExtValue(), Func, Data);
102 }
103 
105  const GlobalVariable *CtorsList = M.getNamedGlobal("llvm.global_ctors");
106  return make_range(CtorDtorIterator(CtorsList, false),
107  CtorDtorIterator(CtorsList, true));
108 }
109 
111  const GlobalVariable *DtorsList = M.getNamedGlobal("llvm.global_dtors");
112  return make_range(CtorDtorIterator(DtorsList, false),
113  CtorDtorIterator(DtorsList, true));
114 }
115 
117  if (CtorDtors.empty())
118  return;
119 
120  MangleAndInterner Mangle(
121  JD.getExecutionSession(),
122  (*CtorDtors.begin()).Func->getParent()->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 = reinterpret_cast<CtorDtorTy>(
162  static_cast<uintptr_t>((*CtorDtorMap)[Name].getAddress()));
163  CtorDtor();
164  }
165  }
166  CtorDtorsByPriority.clear();
167  return Error::success();
168  } else
169  return CtorDtorMap.takeError();
170 }
171 
173  auto& CXXDestructorDataPairs = DSOHandleOverride;
174  for (auto &P : CXXDestructorDataPairs)
175  P.first(P.second);
176  CXXDestructorDataPairs.clear();
177 }
178 
180  void *Arg,
181  void *DSOHandle) {
182  auto& CXXDestructorDataPairs =
183  *reinterpret_cast<CXXDestructorDataPairList*>(DSOHandle);
184  CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
185  return 0;
186 }
187 
189  MangleAndInterner &Mangle) {
190  SymbolMap RuntimeInterposes;
191  RuntimeInterposes[Mangle("__dso_handle")] =
192  JITEvaluatedSymbol(toTargetAddress(&DSOHandleOverride),
194  RuntimeInterposes[Mangle("__cxa_atexit")] =
195  JITEvaluatedSymbol(toTargetAddress(&CXAAtExitOverride),
197 
198  return JD.define(absoluteSymbols(std::move(RuntimeInterposes)));
199 }
200 
203  : Dylib(std::move(Dylib)), Allow(std::move(Allow)),
204  GlobalPrefix(GlobalPrefix) {}
205 
207 DynamicLibrarySearchGenerator::Load(const char *FileName, char GlobalPrefix,
208  SymbolPredicate Allow) {
209  std::string ErrMsg;
210  auto Lib = sys::DynamicLibrary::getPermanentLibrary(FileName, &ErrMsg);
211  if (!Lib.isValid())
212  return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
213  return std::make_unique<DynamicLibrarySearchGenerator>(
214  std::move(Lib), GlobalPrefix, std::move(Allow));
215 }
216 
218  LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
219  const SymbolLookupSet &Symbols) {
220  orc::SymbolMap NewSymbols;
221 
222  bool HasGlobalPrefix = (GlobalPrefix != '\0');
223 
224  for (auto &KV : Symbols) {
225  auto &Name = KV.first;
226 
227  if ((*Name).empty())
228  continue;
229 
230  if (Allow && !Allow(Name))
231  continue;
232 
233  if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
234  continue;
235 
236  std::string Tmp((*Name).data() + HasGlobalPrefix,
237  (*Name).size() - HasGlobalPrefix);
238  if (void *Addr = Dylib.getAddressOfSymbol(Tmp.c_str())) {
239  NewSymbols[Name] = JITEvaluatedSymbol(
240  static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(Addr)),
242  }
243  }
244 
245  if (NewSymbols.empty())
246  return Error::success();
247 
248  return JD.define(absoluteSymbols(std::move(NewSymbols)));
249 }
250 
253  auto ArchiveBuffer = errorOrToExpected(MemoryBuffer::getFile(FileName));
254 
255  if (!ArchiveBuffer)
256  return ArchiveBuffer.takeError();
257 
258  return Create(L, std::move(*ArchiveBuffer));
259 }
260 
263  ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer) {
264  Error Err = Error::success();
265 
266  std::unique_ptr<StaticLibraryDefinitionGenerator> ADG(
267  new StaticLibraryDefinitionGenerator(L, std::move(ArchiveBuffer), Err));
268 
269  if (Err)
270  return std::move(Err);
271 
272  return std::move(ADG);
273 }
274 
276  LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
277  const SymbolLookupSet &Symbols) {
278 
279  // Don't materialize symbols from static archives unless this is a static
280  // lookup.
281  if (K != LookupKind::Static)
282  return Error::success();
283 
284  // Bail out early if we've already freed the archive.
285  if (!Archive)
286  return Error::success();
287 
289 
290  for (const auto &KV : Symbols) {
291  const auto &Name = KV.first;
292  auto Child = Archive->findSym(*Name);
293  if (!Child)
294  return Child.takeError();
295  if (*Child == None)
296  continue;
297  auto ChildBuffer = (*Child)->getMemoryBufferRef();
298  if (!ChildBuffer)
299  return ChildBuffer.takeError();
300  ChildBufferInfos.insert(
301  {ChildBuffer->getBuffer(), ChildBuffer->getBufferIdentifier()});
302  }
303 
304  for (auto ChildBufferInfo : ChildBufferInfos) {
305  MemoryBufferRef ChildBufferRef(ChildBufferInfo.first,
306  ChildBufferInfo.second);
307 
308  if (auto Err =
309  L.add(JD, MemoryBuffer::getMemBuffer(ChildBufferRef), VModuleKey()))
310  return Err;
311  }
312 
313  return Error::success();
314 }
315 
316 StaticLibraryDefinitionGenerator::StaticLibraryDefinitionGenerator(
317  ObjectLayer &L, std::unique_ptr<MemoryBuffer> ArchiveBuffer, Error &Err)
318  : L(L), ArchiveBuffer(std::move(ArchiveBuffer)),
319  Archive(std::make_unique<object::Archive>(*this->ArchiveBuffer, Err)) {}
320 
321 } // End namespace orc.
322 } // End namespace llvm.
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...
const NoneType None
Definition: None.h:23
Accessor for an element of the global_ctors/global_dtors array.
LookupKind
Describes the kind of lookup being performed.
Definition: Core.h:89
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool operator==(const CtorDtorIterator &Other) const
Test iterators for equality.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
std::function< bool(const SymbolStringPtr &)> SymbolPredicate
Implements a dense probed hash-table based set.
Definition: DenseSet.h:249
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition: Module.h:406
Externally visible function.
Definition: GlobalValue.h:48
F(f)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
Error enable(JITDylib &JD, MangleAndInterner &Mangler)
CtorDtorIterator & operator++()
Pre-increment iterator.
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols, VModuleKey K=VModuleKey())
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
Definition: Core.h:630
Definition: BitVector.h:937
A utility class to expose symbols from a static library.
Error define(std::unique_ptr< MaterializationUnitType > &&MU)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition: Core.h:1253
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Core.h:1310
void * getAddressOfSymbol(const char *symbolName)
Searches through the library for the symbol symbolName.
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
void add(iterator_range< CtorDtorIterator > CtorDtors)
This class provides a portable interface to dynamic libraries which also might be known as shared lib...
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:889
iterator_range< CtorDtorIterator > getDestructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
CtorDtorIterator(const GlobalVariable *GV, bool End)
Construct an iterator instance.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, char GlobalPrefix, SymbolPredicate Allow=SymbolPredicate())
Create a DynamicLibrarySearchGenerator that searches for symbols in the given sys::DynamicLibrary.
Value * getOperand(unsigned i) const
Definition: User.h:169
bool containsDuplicates()
Returns true if this set contains any duplicates.
Definition: Core.h:285
#define P(N)
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:158
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Definition: Error.h:1137
void add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
Definition: Core.h:163
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
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:98
Error tryToGenerate(LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib...
static DynamicLibrary getPermanentLibrary(const char *filename, std::string *errMsg=nullptr)
This function permanently loads the dynamic library at the given path.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast_or_null(const Y &Val)
Definition: Casting.h:353
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Error tryToGenerate(LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &Symbols) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib...
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
unsigned getNumOperands() const
Definition: User.h:191
static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
This iterator provides a convenient way to iterate over the elements of an llvm.global_ctors/llvm.global_dtors instance.
Module.h This file contains the declarations for the Module class.
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition: Core.h:115
static Constant * getInitializer(Constant *C)
Definition: Evaluator.cpp:205
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
A range adaptor for a pair of iterators.
ConstantArray - Constant Array Declarations.
Definition: Constants.h:413
Represents a symbol that has been evaluated to an address already.
Definition: JITSymbol.h:208
void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
uint8_t uint64_t VModuleKey
VModuleKey provides a unique identifier (allocated and managed by ExecutionSessions) for a module add...
Definition: Core.h:42
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Load(ObjectLayer &L, const char *FileName)
Try to create a StaticLibraryDefinitionGenerator from the given path.
iterator_range< CtorDtorIterator > getConstructors(const Module &M)
Create an iterator range over the entries of the llvm.global_ctors array.
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:96
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
int runAsMain(int(*Main)(int, char *[]), ArrayRef< std::string > Args, Optional< StringRef > ProgramName=None)
Run a main function, returning the result.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:74
Element operator*() const
Dereference iterator.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
IteratorT begin() const
Interface for Layers that accept object files.
Definition: Layer.h:126
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition: Core.h:67
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1234
static Expected< std::unique_ptr< StaticLibraryDefinitionGenerator > > Create(ObjectLayer &L, std::unique_ptr< MemoryBuffer > ArchiveBuffer)
Try to create a StaticLibrarySearchGenerator from the given memory buffer.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
A symbol table that supports asynchoronous symbol queries.
Definition: Core.h:774
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77