LLVM  8.0.1
ExecutionUtils.cpp
Go to the documentation of this file.
1 //===---- ExecutionUtils.cpp - Utilities for executing functions in Orc ---===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 
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 
23  : InitList(
24  GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
25  I((InitList && End) ? InitList->getNumOperands() : 0) {
26 }
27 
29  assert(InitList == Other.InitList && "Incomparable iterators.");
30  return I == Other.I;
31 }
32 
34  return !(*this == Other);
35 }
36 
38  ++I;
39  return *this;
40 }
41 
43  CtorDtorIterator Temp = *this;
44  ++I;
45  return Temp;
46 }
47 
49  ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(I));
50  assert(CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors");
51 
52  Constant *FuncC = CS->getOperand(1);
53  Function *Func = nullptr;
54 
55  // Extract function pointer, pulling off any casts.
56  while (FuncC) {
57  if (Function *F = dyn_cast_or_null<Function>(FuncC)) {
58  Func = F;
59  break;
60  } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
61  if (CE->isCast())
62  FuncC = dyn_cast_or_null<ConstantExpr>(CE->getOperand(0));
63  else
64  break;
65  } else {
66  // This isn't anything we recognize. Bail out with Func left set to null.
67  break;
68  }
69  }
70 
71  ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
72  Value *Data = CS->getNumOperands() == 3 ? CS->getOperand(2) : nullptr;
73  if (Data && !isa<GlobalValue>(Data))
74  Data = nullptr;
75  return Element(Priority->getZExtValue(), Func, Data);
76 }
77 
79  const GlobalVariable *CtorsList = M.getNamedGlobal("llvm.global_ctors");
80  return make_range(CtorDtorIterator(CtorsList, false),
81  CtorDtorIterator(CtorsList, true));
82 }
83 
85  const GlobalVariable *DtorsList = M.getNamedGlobal("llvm.global_dtors");
86  return make_range(CtorDtorIterator(DtorsList, false),
87  CtorDtorIterator(DtorsList, true));
88 }
89 
91  if (empty(CtorDtors))
92  return;
93 
94  MangleAndInterner Mangle(
95  JD.getExecutionSession(),
96  (*CtorDtors.begin()).Func->getParent()->getDataLayout());
97 
98  for (const auto &CtorDtor : CtorDtors) {
99  assert(CtorDtor.Func && CtorDtor.Func->hasName() &&
100  "Ctor/Dtor function must be named to be runnable under the JIT");
101 
102  // FIXME: Maybe use a symbol promoter here instead.
103  if (CtorDtor.Func->hasLocalLinkage()) {
104  CtorDtor.Func->setLinkage(GlobalValue::ExternalLinkage);
105  CtorDtor.Func->setVisibility(GlobalValue::HiddenVisibility);
106  }
107 
108  if (CtorDtor.Data && cast<GlobalValue>(CtorDtor.Data)->isDeclaration()) {
109  dbgs() << " Skipping because why now?\n";
110  continue;
111  }
112 
113  CtorDtorsByPriority[CtorDtor.Priority].push_back(
114  Mangle(CtorDtor.Func->getName()));
115  }
116 }
117 
119  using CtorDtorTy = void (*)();
120 
121  SymbolNameSet Names;
122 
123  for (auto &KV : CtorDtorsByPriority) {
124  for (auto &Name : KV.second) {
125  auto Added = Names.insert(Name).second;
126  (void)Added;
127  assert(Added && "Ctor/Dtor names clashed");
128  }
129  }
130 
131  auto &ES = JD.getExecutionSession();
132  if (auto CtorDtorMap =
133  ES.lookup(JITDylibSearchList({{&JD, true}}), std::move(Names),
134  NoDependenciesToRegister, true)) {
135  for (auto &KV : CtorDtorsByPriority) {
136  for (auto &Name : KV.second) {
137  assert(CtorDtorMap->count(Name) && "No entry for Name");
138  auto CtorDtor = reinterpret_cast<CtorDtorTy>(
139  static_cast<uintptr_t>((*CtorDtorMap)[Name].getAddress()));
140  CtorDtor();
141  }
142  }
143  return Error::success();
144  } else
145  return CtorDtorMap.takeError();
146 
147  CtorDtorsByPriority.clear();
148 
149  return Error::success();
150 }
151 
153  auto& CXXDestructorDataPairs = DSOHandleOverride;
154  for (auto &P : CXXDestructorDataPairs)
155  P.first(P.second);
156  CXXDestructorDataPairs.clear();
157 }
158 
160  void *Arg,
161  void *DSOHandle) {
162  auto& CXXDestructorDataPairs =
163  *reinterpret_cast<CXXDestructorDataPairList*>(DSOHandle);
164  CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
165  return 0;
166 }
167 
169  MangleAndInterner &Mangle) {
170  SymbolMap RuntimeInterposes;
171  RuntimeInterposes[Mangle("__dso_handle")] =
172  JITEvaluatedSymbol(toTargetAddress(&DSOHandleOverride),
174  RuntimeInterposes[Mangle("__cxa_atexit")] =
175  JITEvaluatedSymbol(toTargetAddress(&CXAAtExitOverride),
177 
178  return JD.define(absoluteSymbols(std::move(RuntimeInterposes)));
179 }
180 
182  sys::DynamicLibrary Dylib, const DataLayout &DL, SymbolPredicate Allow)
183  : Dylib(std::move(Dylib)), Allow(std::move(Allow)),
184  GlobalPrefix(DL.getGlobalPrefix()) {}
185 
187 DynamicLibrarySearchGenerator::Load(const char *FileName, const DataLayout &DL,
188  SymbolPredicate Allow) {
189  std::string ErrMsg;
190  auto Lib = sys::DynamicLibrary::getPermanentLibrary(FileName, &ErrMsg);
191  if (!Lib.isValid())
192  return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
193  return DynamicLibrarySearchGenerator(std::move(Lib), DL, std::move(Allow));
194 }
195 
197 operator()(JITDylib &JD, const SymbolNameSet &Names) {
198  orc::SymbolNameSet Added;
199  orc::SymbolMap NewSymbols;
200 
201  bool HasGlobalPrefix = (GlobalPrefix != '\0');
202 
203  for (auto &Name : Names) {
204  if ((*Name).empty())
205  continue;
206 
207  if (Allow && !Allow(Name))
208  continue;
209 
210  if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
211  continue;
212 
213  std::string Tmp((*Name).data() + (HasGlobalPrefix ? 1 : 0), (*Name).size());
214  if (void *Addr = Dylib.getAddressOfSymbol(Tmp.c_str())) {
215  Added.insert(Name);
216  NewSymbols[Name] = JITEvaluatedSymbol(
217  static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(Addr)),
219  }
220  }
221 
222  // Add any new symbols to JD. Since the generator is only called for symbols
223  // that are not already defined, this will never trigger a duplicate
224  // definition error, so we can wrap this call in a 'cantFail'.
225  if (!NewSymbols.empty())
226  cantFail(JD.define(absoluteSymbols(std::move(NewSymbols))));
227 
228  return Added;
229 }
230 
231 } // End namespace orc.
232 } // End namespace llvm.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:704
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
Accessor for an element of the global_ctors/global_dtors array.
This class represents lattice values for constants.
Definition: AllocatorList.h:24
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:65
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition: Module.h:402
Externally visible function.
Definition: GlobalValue.h:49
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:332
amdgpu Simplify well known AMD library false Value Value const Twine & Name
Definition: BitVector.h:938
std::vector< std::pair< JITDylib *, bool > > JITDylibSearchList
A list of (JITDylib*, bool) pairs.
Definition: Core.h:58
Error define(std::unique_ptr< MaterializationUnitType > &&MU)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition: Core.h:881
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Core.h:915
void * getAddressOfSymbol(const char *symbolName)
Searches through the library for the symbol symbolName.
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
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
std::function< bool(SymbolStringPtr)> SymbolPredicate
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.
Value * getOperand(unsigned i) const
Definition: User.h:170
static Expected< DynamicLibrarySearchGenerator > Load(const char *FileName, const DataLayout &DL, SymbolPredicate Allow=SymbolPredicate())
Permanently loads the library at the given path and, on success, returns a DynamicLibrarySearchGenera...
#define P(N)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:149
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:188
SymbolNameSet operator()(JITDylib &JD, const SymbolNameSet &Names)
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:344
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:210
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:327
unsigned getNumOperands() const
Definition: User.h:192
static int CXAAtExitOverride(DestructorPtr Destructor, void *Arg, void *DSOHandle)
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
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.
static Constant * getInitializer(Constant *C)
Definition: Evaluator.cpp:178
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
DynamicLibrarySearchGenerator(sys::DynamicLibrary Dylib, const DataLayout &DL, SymbolPredicate Allow=SymbolPredicate())
Create a DynamicLibrarySearchGenerator that searches for symbols in the given sys::DynamicLibrary.
A range adaptor for a pair of iterators.
ConstantArray - Constant Array Declarations.
Definition: Constants.h:414
Represents a symbol that has been evaluated to an address already.
Definition: JITSymbol.h:209
void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
amdgpu Simplify well known AMD library false Value Value * Arg
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:323
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:123
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
Element operator*() const
Dereference iterator.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:158
IteratorT begin() const
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition: Core.cpp:143
A symbol table that supports asynchoronous symbol queries.
Definition: Core.h:496
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:78