LLVM  7.0.0svn
IndirectionUtils.cpp
Go to the documentation of this file.
1 //===---- IndirectionUtils.cpp - Utilities for call indirection 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 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/Triple.h"
14 #include "llvm/IR/CallSite.h"
15 #include "llvm/IR/IRBuilder.h"
17 #include <sstream>
18 
19 namespace llvm {
20 namespace orc {
21 
22 void JITCompileCallbackManager::anchor() {}
23 void IndirectStubsManager::anchor() {}
24 
25 std::unique_ptr<JITCompileCallbackManager>
28  switch (T.getArch()) {
29  default: return nullptr;
30 
31  case Triple::aarch64: {
33  return llvm::make_unique<CCMgrT>(ErrorHandlerAddress);
34  }
35 
36  case Triple::x86: {
38  return llvm::make_unique<CCMgrT>(ErrorHandlerAddress);
39  }
40 
41  case Triple::x86_64: {
42  if ( T.getOS() == Triple::OSType::Win32 ) {
44  return llvm::make_unique<CCMgrT>(ErrorHandlerAddress);
45  } else {
47  return llvm::make_unique<CCMgrT>(ErrorHandlerAddress);
48  }
49  }
50 
51  }
52 }
53 
54 std::function<std::unique_ptr<IndirectStubsManager>()>
56  switch (T.getArch()) {
57  default:
58  return [](){
59  return llvm::make_unique<
61  };
62 
63  case Triple::aarch64:
64  return [](){
65  return llvm::make_unique<
67  };
68 
69  case Triple::x86:
70  return [](){
71  return llvm::make_unique<
73  };
74 
75  case Triple::x86_64:
76  if (T.getOS() == Triple::OSType::Win32) {
77  return [](){
78  return llvm::make_unique<
80  };
81  } else {
82  return [](){
83  return llvm::make_unique<
85  };
86  }
87 
88  }
89 }
90 
92  Constant *AddrIntVal =
94  Constant *AddrPtrVal =
95  ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
96  PointerType::get(&FT, 0));
97  return AddrPtrVal;
98 }
99 
101  const Twine &Name, Constant *Initializer) {
102  auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
103  Initializer, Name, nullptr,
104  GlobalValue::NotThreadLocal, 0, true);
105  IP->setVisibility(GlobalValue::HiddenVisibility);
106  return IP;
107 }
108 
109 void makeStub(Function &F, Value &ImplPointer) {
110  assert(F.isDeclaration() && "Can't turn a definition into a stub.");
111  assert(F.getParent() && "Function isn't in a module.");
112  Module &M = *F.getParent();
113  BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
114  IRBuilder<> Builder(EntryBlock);
115  LoadInst *ImplAddr = Builder.CreateLoad(&ImplPointer);
116  std::vector<Value*> CallArgs;
117  for (auto &A : F.args())
118  CallArgs.push_back(&A);
119  CallInst *Call = Builder.CreateCall(ImplAddr, CallArgs);
120  Call->setTailCall();
121  Call->setAttributes(F.getAttributes());
122  if (F.getReturnType()->isVoidTy())
123  Builder.CreateRetVoid();
124  else
125  Builder.CreateRet(Call);
126 }
127 
128 // Utility class for renaming global values and functions during partitioning.
130 public:
131 
132  static bool needsRenaming(const Value &New) {
133  return !New.hasName() || New.getName().startswith("\01L");
134  }
135 
136  const std::string& getRename(const Value &Orig) {
137  // See if we have a name for this global.
138  {
139  auto I = Names.find(&Orig);
140  if (I != Names.end())
141  return I->second;
142  }
143 
144  // Nope. Create a new one.
145  // FIXME: Use a more robust uniquing scheme. (This may blow up if the user
146  // writes a "__orc_anon[[:digit:]]* method).
147  unsigned ID = Names.size();
148  std::ostringstream NameStream;
149  NameStream << "__orc_anon" << ID++;
150  auto I = Names.insert(std::make_pair(&Orig, NameStream.str()));
151  return I.first->second;
152  }
153 private:
155 };
156 
158  if (V.hasLocalLinkage()) {
159  if (R.needsRenaming(V))
160  V.setName(R.getRename(V));
163  }
165  assert(!R.needsRenaming(V) && "Invalid global name.");
166 }
167 
169  GlobalRenamer Renamer;
170 
171  for (auto &F : M)
172  raiseVisibilityOnValue(F, Renamer);
173 
174  for (auto &GV : M.globals())
175  raiseVisibilityOnValue(GV, Renamer);
176 
177  for (auto &A : M.aliases())
178  raiseVisibilityOnValue(A, Renamer);
179 }
180 
182  ValueToValueMapTy *VMap) {
183  assert(F.getParent() != &Dst && "Can't copy decl over existing function.");
184  Function *NewF =
185  Function::Create(cast<FunctionType>(F.getValueType()),
186  F.getLinkage(), F.getName(), &Dst);
187  NewF->copyAttributesFrom(&F);
188 
189  if (VMap) {
190  (*VMap)[&F] = NewF;
191  auto NewArgI = NewF->arg_begin();
192  for (auto ArgI = F.arg_begin(), ArgE = F.arg_end(); ArgI != ArgE;
193  ++ArgI, ++NewArgI)
194  (*VMap)[&*ArgI] = &*NewArgI;
195  }
196 
197  return NewF;
198 }
199 
201  ValueMaterializer *Materializer,
202  Function *NewF) {
203  assert(!OrigF.isDeclaration() && "Nothing to move");
204  if (!NewF)
205  NewF = cast<Function>(VMap[&OrigF]);
206  else
207  assert(VMap[&OrigF] == NewF && "Incorrect function mapping in VMap.");
208  assert(NewF && "Function mapping missing from VMap.");
209  assert(NewF->getParent() != OrigF.getParent() &&
210  "moveFunctionBody should only be used to move bodies between "
211  "modules.");
212 
213  SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
214  CloneFunctionInto(NewF, &OrigF, VMap, /*ModuleLevelChanges=*/true, Returns,
215  "", nullptr, nullptr, Materializer);
216  OrigF.deleteBody();
217 }
218 
220  ValueToValueMapTy *VMap) {
221  assert(GV.getParent() != &Dst && "Can't copy decl over existing global var.");
222  GlobalVariable *NewGV = new GlobalVariable(
223  Dst, GV.getValueType(), GV.isConstant(),
224  GV.getLinkage(), nullptr, GV.getName(), nullptr,
226  NewGV->copyAttributesFrom(&GV);
227  if (VMap)
228  (*VMap)[&GV] = NewGV;
229  return NewGV;
230 }
231 
233  ValueToValueMapTy &VMap,
234  ValueMaterializer *Materializer,
235  GlobalVariable *NewGV) {
236  assert(OrigGV.hasInitializer() && "Nothing to move");
237  if (!NewGV)
238  NewGV = cast<GlobalVariable>(VMap[&OrigGV]);
239  else
240  assert(VMap[&OrigGV] == NewGV &&
241  "Incorrect global variable mapping in VMap.");
242  assert(NewGV->getParent() != OrigGV.getParent() &&
243  "moveGlobalVariable should only be used to move initializers between "
244  "modules");
245 
246  NewGV->setInitializer(MapValue(OrigGV.getInitializer(), VMap, RF_None,
247  nullptr, Materializer));
248 }
249 
251  ValueToValueMapTy &VMap) {
252  assert(OrigA.getAliasee() && "Original alias doesn't have an aliasee?");
253  auto *NewA = GlobalAlias::create(OrigA.getValueType(),
254  OrigA.getType()->getPointerAddressSpace(),
255  OrigA.getLinkage(), OrigA.getName(), &Dst);
256  NewA->copyAttributesFrom(&OrigA);
257  VMap[&OrigA] = NewA;
258  return NewA;
259 }
260 
261 void cloneModuleFlagsMetadata(Module &Dst, const Module &Src,
262  ValueToValueMapTy &VMap) {
263  auto *MFs = Src.getModuleFlagsMetadata();
264  if (!MFs)
265  return;
266  for (auto *MF : MFs->operands())
267  Dst.addModuleFlag(MapMetadata(MF, VMap));
268 }
269 
270 } // End namespace orc.
271 } // End namespace llvm.
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:238
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:254
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
IndirectStubsManager implementation for the host architecture, e.g.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
std::function< std::unique_ptr< IndirectStubsManager >)> createLocalIndirectStubsManagerBuilder(const Triple &T)
Create a local indriect stubs manager builder.
GlobalAlias * cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA, ValueToValueMapTy &VMap)
Clone a global alias declaration into a new module.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
Definition: Triple.h:292
void cloneModuleFlagsMetadata(Module &Dst, const Module &Src, ValueToValueMapTy &VMap)
Clone module flags metadata into the destination module.
This class represents a function call, abstracting a target machine&#39;s calling convention.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:617
static bool needsRenaming(const Value &New)
Externally visible function.
Definition: GlobalValue.h:49
arg_iterator arg_end()
Definition: Function.h:666
F(f)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
An instruction for reading from memory.
Definition: Instructions.h:164
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&... args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:1056
Manage compile callbacks for in-process JITs.
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Lookup or compute a mapping for a piece of metadata.
Definition: ValueMapper.h:228
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:130
const std::string & getRename(const Value &Orig)
void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst *> &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
void copyAttributesFrom(const GlobalValue *Src)
Definition: GlobalAlias.h:62
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:358
GlobalVariable * createImplPointer(PointerType &PT, Module &M, const Twine &Name, Constant *Initializer)
Create a function pointer with the given type, name, and initializer in the given Module...
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
std::unique_ptr< JITCompileCallbackManager > createLocalCompileCallbackManager(const Triple &T, JITTargetAddress ErrorHandlerAddress)
Create a local compile callback manager.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:677
static void raiseVisibilityOnValue(GlobalValue &V, GlobalRenamer &R)
void moveGlobalVariableInitializer(GlobalVariable &OrigGV, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, GlobalVariable *NewGV=nullptr)
Move global variable GV from its parent module to cloned global declaration in a different module...
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:295
void makeStub(Function &F, Value &ImplPointer)
Turn a function declaration into a stub function that makes an indirect call using the given function...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
Class to represent function types.
Definition: DerivedTypes.h:103
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:283
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:210
uint64_t JITTargetAddress
Represents an address in the target process&#39;s address space.
Definition: JITSymbol.h:40
LinkageTypes getLinkage() const
Definition: GlobalValue.h:450
GlobalVariable * cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV, ValueToValueMapTy *VMap=nullptr)
Clone a global variable declaration into a new module.
Class to represent pointers.
Definition: DerivedTypes.h:467
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
This is a class that can be implemented by clients to materialize Values on demand.
Definition: ValueMapper.h:51
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:155
void getModuleFlagsMetadata(SmallVectorImpl< ModuleFlagEntry > &Flags) const
Returns the module flags in the provided vector.
Definition: Module.cpp:282
bool hasName() const
Definition: Value.h:251
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
void deleteBody()
deleteBody - This method deletes the body of the function, and converts the linkage to external...
Definition: Function.h:595
This is an important base class in LLVM.
Definition: Constant.h:42
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:470
void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val)
Add a module-level flag to the module-level flags metadata.
Definition: Module.cpp:329
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:495
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:101
arg_iterator arg_begin()
Definition: Function.h:657
void setTailCall(bool isTC=true)
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Look up or compute a value in the value map.
Definition: ValueMapper.h:206
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
Constant * createIRTypedAddress(FunctionType &FT, JITTargetAddress Addr)
Build a function pointer of FunctionType with the given constant address.
Function * cloneFunctionDecl(Module &Dst, const Function &F, ValueToValueMapTy *VMap=nullptr)
Clone a function declaration into a new module.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:862
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:611
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:444
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1497
void makeAllSymbolsExternallyAccessible(Module &M)
Raise linkage types and rename as necessary to ensure that all symbols are accessible for other modul...
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:215
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:381
#define I(x, y, z)
Definition: MD5.cpp:58
Type * getValueType() const
Definition: GlobalValue.h:275
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:201
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:73
bool hasInitializer() const
Definitions have initializers, declarations don&#39;t.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Definition: Function.h:136
void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, Function *NewF=nullptr)
Move the body of function &#39;F&#39; to a cloned function declaration in a different module (See related clo...
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:418
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
iterator_range< arg_iterator > args()
Definition: Function.h:675
const Constant * getAliasee() const
Definition: GlobalAlias.h:78