LLVM  8.0.1
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 
15 #include "llvm/IR/Constant.h"
16 #include "llvm/IR/DerivedTypes.h"
17 #include "llvm/IR/Module.h"
20 using namespace llvm;
21 
22 static void copyComdat(GlobalObject *Dst, const GlobalObject *Src) {
23  const Comdat *SC = Src->getComdat();
24  if (!SC)
25  return;
26  Comdat *DC = Dst->getParent()->getOrInsertComdat(SC->getName());
28  Dst->setComdat(DC);
29 }
30 
31 /// This is not as easy as it might seem because we have to worry about making
32 /// copies of global variables and functions, and making their (initializers and
33 /// references, respectively) refer to the right globals.
34 ///
35 std::unique_ptr<Module> llvm::CloneModule(const Module &M) {
36  // Create the value map that maps things from the old module over to the new
37  // module.
38  ValueToValueMapTy VMap;
39  return CloneModule(M, VMap);
40 }
41 
42 std::unique_ptr<Module> llvm::CloneModule(const Module &M,
43  ValueToValueMapTy &VMap) {
44  return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; });
45 }
46 
47 std::unique_ptr<Module> llvm::CloneModule(
48  const Module &M, ValueToValueMapTy &VMap,
49  function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
50  // First off, we need to create the new module.
51  std::unique_ptr<Module> New =
52  llvm::make_unique<Module>(M.getModuleIdentifier(), M.getContext());
53  New->setSourceFileName(M.getSourceFileName());
54  New->setDataLayout(M.getDataLayout());
55  New->setTargetTriple(M.getTargetTriple());
56  New->setModuleInlineAsm(M.getModuleInlineAsm());
57 
58  // Loop over all of the global variables, making corresponding globals in the
59  // new module. Here we add them to the VMap and to the new Module. We
60  // don't worry about attributes or initializers, they will come later.
61  //
63  I != E; ++I) {
64  GlobalVariable *GV = new GlobalVariable(*New,
65  I->getValueType(),
66  I->isConstant(), I->getLinkage(),
67  (Constant*) nullptr, I->getName(),
68  (GlobalVariable*) nullptr,
69  I->getThreadLocalMode(),
70  I->getType()->getAddressSpace());
71  GV->copyAttributesFrom(&*I);
72  VMap[&*I] = GV;
73  }
74 
75  // Loop over the functions in the module, making external functions as before
76  for (const Function &I : M) {
77  Function *NF =
78  Function::Create(cast<FunctionType>(I.getValueType()), I.getLinkage(),
79  I.getAddressSpace(), I.getName(), New.get());
80  NF->copyAttributesFrom(&I);
81  VMap[&I] = NF;
82  }
83 
84  // Loop over the aliases in the module
85  for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
86  I != E; ++I) {
87  if (!ShouldCloneDefinition(&*I)) {
88  // An alias cannot act as an external reference, so we need to create
89  // either a function or a global variable depending on the value type.
90  // FIXME: Once pointee types are gone we can probably pick one or the
91  // other.
92  GlobalValue *GV;
93  if (I->getValueType()->isFunctionTy())
94  GV = Function::Create(cast<FunctionType>(I->getValueType()),
96  I->getAddressSpace(), I->getName(), New.get());
97  else
98  GV = new GlobalVariable(
99  *New, I->getValueType(), false, GlobalValue::ExternalLinkage,
100  nullptr, I->getName(), nullptr,
101  I->getThreadLocalMode(), I->getType()->getAddressSpace());
102  VMap[&*I] = GV;
103  // We do not copy attributes (mainly because copying between different
104  // kinds of globals is forbidden), but this is generally not required for
105  // correctness.
106  continue;
107  }
108  auto *GA = GlobalAlias::create(I->getValueType(),
109  I->getType()->getPointerAddressSpace(),
110  I->getLinkage(), I->getName(), New.get());
111  GA->copyAttributesFrom(&*I);
112  VMap[&*I] = GA;
113  }
114 
115  // Now that all of the things that global variable initializer can refer to
116  // have been created, loop through and copy the global variable referrers
117  // over... We also set the attributes on the global now.
118  //
119  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
120  I != E; ++I) {
121  if (I->isDeclaration())
122  continue;
123 
124  GlobalVariable *GV = cast<GlobalVariable>(VMap[&*I]);
125  if (!ShouldCloneDefinition(&*I)) {
126  // Skip after setting the correct linkage for an external reference.
128  continue;
129  }
130  if (I->hasInitializer())
131  GV->setInitializer(MapValue(I->getInitializer(), VMap));
132 
134  I->getAllMetadata(MDs);
135  for (auto MD : MDs)
136  GV->addMetadata(MD.first,
137  *MapMetadata(MD.second, VMap, RF_MoveDistinctMDs));
138 
139  copyComdat(GV, &*I);
140  }
141 
142  // Similarly, copy over function bodies now...
143  //
144  for (const Function &I : M) {
145  if (I.isDeclaration())
146  continue;
147 
148  Function *F = cast<Function>(VMap[&I]);
149  if (!ShouldCloneDefinition(&I)) {
150  // Skip after setting the correct linkage for an external reference.
152  // Personality function is not valid on a declaration.
153  F->setPersonalityFn(nullptr);
154  continue;
155  }
156 
157  Function::arg_iterator DestI = F->arg_begin();
158  for (Function::const_arg_iterator J = I.arg_begin(); J != I.arg_end();
159  ++J) {
160  DestI->setName(J->getName());
161  VMap[&*J] = &*DestI++;
162  }
163 
164  SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
165  CloneFunctionInto(F, &I, VMap, /*ModuleLevelChanges=*/true, Returns);
166 
167  if (I.hasPersonalityFn())
168  F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap));
169 
170  copyComdat(F, &I);
171  }
172 
173  // And aliases
174  for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
175  I != E; ++I) {
176  // We already dealt with undefined aliases above.
177  if (!ShouldCloneDefinition(&*I))
178  continue;
179  GlobalAlias *GA = cast<GlobalAlias>(VMap[&*I]);
180  if (const Constant *C = I->getAliasee())
181  GA->setAliasee(MapValue(C, VMap));
182  }
183 
184  // And named metadata....
185  for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
186  E = M.named_metadata_end();
187  I != E; ++I) {
188  const NamedMDNode &NMD = *I;
189  NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName());
190  for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
191  NewNMD->addOperand(MapMetadata(NMD.getOperand(i), VMap));
192  }
193 
194  return New;
195 }
196 
197 extern "C" {
198 
200  return wrap(CloneModule(*unwrap(M)).release());
201 }
202 
203 }
uint64_t CallInst * C
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:240
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1081
This class represents lattice values for constants.
Definition: AllocatorList.h:24
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: Types.h:62
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
void addOperand(MDNode *M)
Definition: Metadata.cpp:1087
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:117
Externally visible function.
Definition: GlobalValue.h:49
F(f)
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
A tuple of MDNodes.
Definition: Metadata.h:1326
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 DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:371
static ManagedStatic< DebugCounter > DC
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:195
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:363
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:244
unsigned getNumOperands() const
Definition: Metadata.cpp:1077
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:285
global_iterator global_begin()
Definition: Module.h:578
Instruct the remapper to move distinct metadata instead of duplicating it when there are module-level...
Definition: ValueMapper.h:95
void setComdat(Comdat *C)
Definition: GlobalObject.h:103
const std::string & getSourceFileName() const
Get the module&#39;s original source file name.
Definition: Module.h:221
std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
Definition: CloneModule.cpp:35
StringRef getName() const
Definition: Comdat.cpp:27
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:136
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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:484
LLVMModuleRef LLVMCloneModule(LLVMModuleRef M)
Return an exact copy of the specified module.
arg_iterator arg_begin()
Definition: Function.h:671
static void copyComdat(GlobalObject *Dst, const GlobalObject *Src)
Definition: CloneModule.cpp:22
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:484
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:210
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
global_iterator global_end()
Definition: Module.h:580
Iterator for intrusive lists based on ilist_node.
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:46
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1394
CHAIN = SC CHAIN, Imm128 - System call.
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:445
StringRef getName() const
Definition: Metadata.cpp:1098
const Comdat * getComdat() const
Definition: GlobalObject.h:101
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:190
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:386
#define I(x, y, z)
Definition: MD5.cpp:58
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
Definition: Module.h:248
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
void setPersonalityFn(Constant *Fn)
Definition: Function.cpp:1304
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:423
void setAliasee(Constant *Aliasee)
These methods retrieve and set alias target.
Definition: Globals.cpp:460
SelectionKind getSelectionKind() const
Definition: Comdat.h:45