LLVM  4.0.0
CloneModule.cpp
Go to the documentation of this file.
1 //===- CloneModule.cpp - Clone an entire module ---------------------------===//
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 //
10 // This file implements the CloneModule interface which makes a copy of an
11 // entire module.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/IR/Constant.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/Module.h"
20 #include "llvm-c/Core.h"
21 using namespace llvm;
22 
23 /// This is not as easy as it might seem because we have to worry about making
24 /// copies of global variables and functions, and making their (initializers and
25 /// references, respectively) refer to the right globals.
26 ///
27 std::unique_ptr<Module> llvm::CloneModule(const Module *M) {
28  // Create the value map that maps things from the old module over to the new
29  // module.
30  ValueToValueMapTy VMap;
31  return CloneModule(M, VMap);
32 }
33 
34 std::unique_ptr<Module> llvm::CloneModule(const Module *M,
35  ValueToValueMapTy &VMap) {
36  return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; });
37 }
38 
39 std::unique_ptr<Module> llvm::CloneModule(
40  const Module *M, ValueToValueMapTy &VMap,
41  function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
42  // First off, we need to create the new module.
43  std::unique_ptr<Module> New =
44  llvm::make_unique<Module>(M->getModuleIdentifier(), M->getContext());
45  New->setDataLayout(M->getDataLayout());
46  New->setTargetTriple(M->getTargetTriple());
47  New->setModuleInlineAsm(M->getModuleInlineAsm());
48 
49  // Loop over all of the global variables, making corresponding globals in the
50  // new module. Here we add them to the VMap and to the new Module. We
51  // don't worry about attributes or initializers, they will come later.
52  //
54  I != E; ++I) {
55  GlobalVariable *GV = new GlobalVariable(*New,
56  I->getValueType(),
57  I->isConstant(), I->getLinkage(),
58  (Constant*) nullptr, I->getName(),
59  (GlobalVariable*) nullptr,
60  I->getThreadLocalMode(),
61  I->getType()->getAddressSpace());
62  GV->copyAttributesFrom(&*I);
63  VMap[&*I] = GV;
64  }
65 
66  // Loop over the functions in the module, making external functions as before
67  for (const Function &I : *M) {
68  Function *NF = Function::Create(cast<FunctionType>(I.getValueType()),
69  I.getLinkage(), I.getName(), New.get());
70  NF->copyAttributesFrom(&I);
71  VMap[&I] = NF;
72  }
73 
74  // Loop over the aliases in the module
75  for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
76  I != E; ++I) {
77  if (!ShouldCloneDefinition(&*I)) {
78  // An alias cannot act as an external reference, so we need to create
79  // either a function or a global variable depending on the value type.
80  // FIXME: Once pointee types are gone we can probably pick one or the
81  // other.
82  GlobalValue *GV;
83  if (I->getValueType()->isFunctionTy())
84  GV = Function::Create(cast<FunctionType>(I->getValueType()),
85  GlobalValue::ExternalLinkage, I->getName(),
86  New.get());
87  else
88  GV = new GlobalVariable(
89  *New, I->getValueType(), false, GlobalValue::ExternalLinkage,
90  (Constant *)nullptr, I->getName(), (GlobalVariable *)nullptr,
91  I->getThreadLocalMode(), I->getType()->getAddressSpace());
92  VMap[&*I] = GV;
93  // We do not copy attributes (mainly because copying between different
94  // kinds of globals is forbidden), but this is generally not required for
95  // correctness.
96  continue;
97  }
98  auto *GA = GlobalAlias::create(I->getValueType(),
99  I->getType()->getPointerAddressSpace(),
100  I->getLinkage(), I->getName(), New.get());
101  GA->copyAttributesFrom(&*I);
102  VMap[&*I] = GA;
103  }
104 
105  // Now that all of the things that global variable initializer can refer to
106  // have been created, loop through and copy the global variable referrers
107  // over... We also set the attributes on the global now.
108  //
109  for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
110  I != E; ++I) {
111  if (I->isDeclaration())
112  continue;
113 
114  GlobalVariable *GV = cast<GlobalVariable>(VMap[&*I]);
115  if (!ShouldCloneDefinition(&*I)) {
116  // Skip after setting the correct linkage for an external reference.
118  continue;
119  }
120  if (I->hasInitializer())
121  GV->setInitializer(MapValue(I->getInitializer(), VMap));
122 
124  I->getAllMetadata(MDs);
125  for (auto MD : MDs)
126  GV->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
127  }
128 
129  // Similarly, copy over function bodies now...
130  //
131  for (const Function &I : *M) {
132  if (I.isDeclaration())
133  continue;
134 
135  Function *F = cast<Function>(VMap[&I]);
136  if (!ShouldCloneDefinition(&I)) {
137  // Skip after setting the correct linkage for an external reference.
139  // Personality function is not valid on a declaration.
140  F->setPersonalityFn(nullptr);
141  continue;
142  }
143 
144  Function::arg_iterator DestI = F->arg_begin();
145  for (Function::const_arg_iterator J = I.arg_begin(); J != I.arg_end();
146  ++J) {
147  DestI->setName(J->getName());
148  VMap[&*J] = &*DestI++;
149  }
150 
151  SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
152  CloneFunctionInto(F, &I, VMap, /*ModuleLevelChanges=*/true, Returns);
153 
154  if (I.hasPersonalityFn())
155  F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap));
156  }
157 
158  // And aliases
159  for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
160  I != E; ++I) {
161  // We already dealt with undefined aliases above.
162  if (!ShouldCloneDefinition(&*I))
163  continue;
164  GlobalAlias *GA = cast<GlobalAlias>(VMap[&*I]);
165  if (const Constant *C = I->getAliasee())
166  GA->setAliasee(MapValue(C, VMap));
167  }
168 
169  // And named metadata....
170  for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
171  E = M->named_metadata_end(); I != E; ++I) {
172  const NamedMDNode &NMD = *I;
173  NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName());
174  for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
175  NewNMD->addOperand(MapMetadata(NMD.getOperand(i), VMap));
176  }
177 
178  return New;
179 }
180 
181 extern "C" {
182 
184  return wrap(CloneModule(unwrap(M)).release());
185 }
186 
187 }
StringRef getName() const
Definition: Metadata.cpp:1059
virtual void copyAttributesFrom(const GlobalValue *Src)
Copy all additional attributes (those not needed to create a GlobalValue) from the GlobalValue Src to...
Definition: Globals.cpp:66
size_t i
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: c/Types.h:62
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
void addOperand(MDNode *M)
Definition: Metadata.cpp:1048
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:83
Externally visible function.
Definition: GlobalValue.h:49
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:218
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:220
A tuple of MDNodes.
Definition: Metadata.h:1282
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:191
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:323
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...
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:193
global_iterator global_begin()
Definition: Module.h:518
#define F(x, y, z)
Definition: MD5.cpp:51
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
LLVMModuleRef LLVMCloneModule(LLVMModuleRef M)
Return an exact copy of the specified module.
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1042
void copyAttributesFrom(const GlobalValue *Src) override
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:431
arg_iterator arg_begin()
Definition: Function.h:550
std::unique_ptr< Module > CloneModule(const Module *M)
Return an exact copy of the specified module.
Definition: CloneModule.cpp:27
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:198
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
Definition: Module.h:226
global_iterator global_end()
Definition: Module.h:520
Iterator for intrusive lists based on ilist_node.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Module.h This file contains the declarations for the Module class.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1342
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:424
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:384
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:186
#define I(x, y, z)
Definition: MD5.cpp:54
void copyAttributesFrom(const GlobalValue *Src) override
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:346
unsigned getNumOperands() const
Definition: Metadata.cpp:1038
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Definition: Function.h:117
void setPersonalityFn(Constant *Fn)
Definition: Function.cpp:1223
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:384
void setAliasee(Constant *Aliasee)
These methods retrieve and set alias target.
Definition: Globals.cpp:421
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:222