LLVM  7.0.0svn
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  : TT(std::move(TT)) {}
24 
27 }
28 
31  if (!Arch.empty()) {
33 
34  if (Type == Triple::UnknownArch)
35  return make_error<StringError>(std::string("Unknown arch: ") + Arch,
37  }
38 
39  std::string ErrMsg;
40  auto *TheTarget = TargetRegistry::lookupTarget(TT.getTriple(), ErrMsg);
41  if (!TheTarget)
42  return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
43 
44  auto *TM =
45  TheTarget->createTargetMachine(TT.getTriple(), CPU, Features.getString(),
46  Options, RM, CM, OptLevel, /*JIT*/ true);
47  if (!TM)
48  return make_error<StringError>("Could not allocate target machine",
50 
51  return std::unique_ptr<TargetMachine>(TM);
52 }
53 
55  const std::vector<std::string> &FeatureVec) {
56  for (const auto &F : FeatureVec)
57  Features.AddFeature(F);
58  return *this;
59 }
60 
62  : InitList(
63  GV ? dyn_cast_or_null<ConstantArray>(GV->getInitializer()) : nullptr),
64  I((InitList && End) ? InitList->getNumOperands() : 0) {
65 }
66 
68  assert(InitList == Other.InitList && "Incomparable iterators.");
69  return I == Other.I;
70 }
71 
73  return !(*this == Other);
74 }
75 
77  ++I;
78  return *this;
79 }
80 
82  CtorDtorIterator Temp = *this;
83  ++I;
84  return Temp;
85 }
86 
88  ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(I));
89  assert(CS && "Unrecognized type in llvm.global_ctors/llvm.global_dtors");
90 
91  Constant *FuncC = CS->getOperand(1);
92  Function *Func = nullptr;
93 
94  // Extract function pointer, pulling off any casts.
95  while (FuncC) {
96  if (Function *F = dyn_cast_or_null<Function>(FuncC)) {
97  Func = F;
98  break;
99  } else if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(FuncC)) {
100  if (CE->isCast())
101  FuncC = dyn_cast_or_null<ConstantExpr>(CE->getOperand(0));
102  else
103  break;
104  } else {
105  // This isn't anything we recognize. Bail out with Func left set to null.
106  break;
107  }
108  }
109 
110  ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
111  Value *Data = CS->getNumOperands() == 3 ? CS->getOperand(2) : nullptr;
112  if (Data && !isa<GlobalValue>(Data))
113  Data = nullptr;
114  return Element(Priority->getZExtValue(), Func, Data);
115 }
116 
118  const GlobalVariable *CtorsList = M.getNamedGlobal("llvm.global_ctors");
119  return make_range(CtorDtorIterator(CtorsList, false),
120  CtorDtorIterator(CtorsList, true));
121 }
122 
124  const GlobalVariable *DtorsList = M.getNamedGlobal("llvm.global_dtors");
125  return make_range(CtorDtorIterator(DtorsList, false),
126  CtorDtorIterator(DtorsList, true));
127 }
128 
130  if (CtorDtors.begin() == CtorDtors.end())
131  return;
132 
134  V.getExecutionSession(),
135  (*CtorDtors.begin()).Func->getParent()->getDataLayout());
136 
137  for (const auto &CtorDtor : CtorDtors) {
138  assert(CtorDtor.Func && CtorDtor.Func->hasName() &&
139  "Ctor/Dtor function must be named to be runnable under the JIT");
140 
141  if (CtorDtor.Data && cast<GlobalValue>(CtorDtor.Data)->isDeclaration()) {
142  dbgs() << " Skipping because why now?\n";
143  continue;
144  }
145 
146  CtorDtorsByPriority[CtorDtor.Priority].push_back(
147  Mangle(CtorDtor.Func->getName()));
148  }
149 }
150 
152  using CtorDtorTy = void (*)();
153 
154  SymbolNameSet Names;
155 
156  for (auto &KV : CtorDtorsByPriority) {
157  for (auto &Name : KV.second) {
158  auto Added = Names.insert(Name).second;
159  (void)Added;
160  assert(Added && "Ctor/Dtor names clashed");
161  }
162  }
163 
164  if (auto CtorDtorMap = lookup({&V}, std::move(Names))) {
165  for (auto &KV : CtorDtorsByPriority) {
166  for (auto &Name : KV.second) {
167  assert(CtorDtorMap->count(Name) && "No entry for Name");
168  auto CtorDtor = reinterpret_cast<CtorDtorTy>(
169  static_cast<uintptr_t>((*CtorDtorMap)[Name].getAddress()));
170  CtorDtor();
171  }
172  }
173  return Error::success();
174  } else
175  return CtorDtorMap.takeError();
176 
177  CtorDtorsByPriority.clear();
178 
179  return Error::success();
180 }
181 
183  auto& CXXDestructorDataPairs = DSOHandleOverride;
184  for (auto &P : CXXDestructorDataPairs)
185  P.first(P.second);
186  CXXDestructorDataPairs.clear();
187 }
188 
190  void *Arg,
191  void *DSOHandle) {
192  auto& CXXDestructorDataPairs =
193  *reinterpret_cast<CXXDestructorDataPairList*>(DSOHandle);
194  CXXDestructorDataPairs.push_back(std::make_pair(Destructor, Arg));
195  return 0;
196 }
197 
199  SymbolMap RuntimeInterposes(
200  {{Mangle("__dso_handle"),
201  JITEvaluatedSymbol(toTargetAddress(&DSOHandleOverride),
203  {Mangle("__cxa_atexit"),
204  JITEvaluatedSymbol(toTargetAddress(&CXAAtExitOverride),
206 
207  return V.define(absoluteSymbols(std::move(RuntimeInterposes)));
208 }
209 
211  sys::DynamicLibrary Dylib, const DataLayout &DL, SymbolPredicate Allow)
212  : Dylib(std::move(Dylib)), Allow(std::move(Allow)),
213  GlobalPrefix(DL.getGlobalPrefix()) {}
214 
216 operator()(VSO &V, const SymbolNameSet &Names) {
217  orc::SymbolNameSet Added;
218  orc::SymbolMap NewSymbols;
219 
220  bool HasGlobalPrefix = (GlobalPrefix != '\0');
221 
222  for (auto &Name : Names) {
223  if (!Allow(Name) || (*Name).empty())
224  continue;
225 
226  if (HasGlobalPrefix && (*Name).front() != GlobalPrefix)
227  continue;
228 
229  std::string Tmp((*Name).data() + (HasGlobalPrefix ? 1 : 0), (*Name).size());
230  if (void *Addr = Dylib.getAddressOfSymbol(Tmp.c_str())) {
231  Added.insert(Name);
232  NewSymbols[Name] = JITEvaluatedSymbol(
233  static_cast<JITTargetAddress>(reinterpret_cast<uintptr_t>(Addr)),
235  }
236  }
237 
238  // Add any new symbols to V. Since the fallback generator is only called for
239  // symbols that are not already defined, this will never trigger a duplicate
240  // definition error, so we can wrap this call in a 'cantFail'.
241  if (!NewSymbols.empty())
242  cantFail(V.define(absoluteSymbols(std::move(NewSymbols))));
243 
244  return Added;
245 }
246 
247 } // End namespace orc.
248 } // End namespace llvm.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:696
SymbolNameSet operator()(VSO &V, const SymbolNameSet &Names)
std::enable_if< std::is_convertible< typename std::decay< UniquePtrToMaterializationUnit >::type, std::unique_ptr< MaterializationUnit > >::value, Error >::type define(UniquePtrToMaterializationUnit &&MU)
Define all symbols provided by the materialization unit to be part of the given VSO.
Definition: Core.h:621
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.
Compute iterated dominance frontiers using a linear time algorithm.
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:63
A symbol table that supports asynchoronous symbol queries.
Definition: Core.h:544
std::string getString() const
Returns features as a string.
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition: Module.h:395
std::map< SymbolStringPtr, JITEvaluatedSymbol > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
Definition: Core.h:51
F(f)
std::vector< CXXDestructorDataPair > CXXDestructorDataPairList
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
CtorDtorIterator & operator++()
Pre-increment iterator.
Definition: BitVector.h:921
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Core.h:766
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 AddFeature(StringRef String, bool Enable=true)
Adds Features.
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:885
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< JITTargetMachineBuilder > detectHost()
#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
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
Error enable(VSO &V, MangleAndInterner &Mangler)
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::function< bool(SymbolStringPtr)> SymbolPredicate
JITTargetMachineBuilder & addFeatures(const std::vector< std::string > &FeatureVec)
std::string getProcessTriple()
getProcessTriple() - Return an appropriate target triple for generating code to be loaded into the cu...
Definition: Host.cpp:1365
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
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
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:321
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
std::unique_ptr< AbsoluteSymbolsMaterializationUnit > absoluteSymbols(SymbolMap Symbols)
Create an AbsoluteSymbolsMaterializationUnit with the given symbols.
Definition: Core.h:277
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 ArchType getArchTypeForLLVMName(StringRef Str)
getArchTypeForLLVMName - The canonical type for the given LLVM architecture name (e.g., "x86").
Definition: Triple.cpp:258
Expected< SymbolMap > lookup(const VSOList &VSOs, SymbolNameSet Names)
Look up the given names in the given VSOs.
Definition: Core.cpp:1655
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
A range adaptor for a pair of iterators.
ConstantArray - Constant Array Declarations.
Definition: Constants.h:410
void add(iterator_range< CtorDtorIterator > CtorDtors)
const std::string & getTriple() const
Definition: Triple.h:356
Represents a symbol that has been evaluated to an address already.
Definition: JITSymbol.h:157
void runDestructors()
Run any destructors recorded by the overriden __cxa_atexit function (CXAAtExitOverride).
amdgpu Simplify well known AMD library false Value Value * Arg
Expected< std::unique_ptr< TargetMachine > > createTargetMachine()
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
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:156
IteratorT begin() const
DynamicLibraryFallbackGenerator(sys::DynamicLibrary Dylib, const DataLayout &DL, SymbolPredicate Allow)
bool operator!=(const CtorDtorIterator &Other) const
Test iterators for inequality.
IteratorT end() const
std::set< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
Definition: Core.h:44
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:73
A utility class for building TargetMachines for JITs.