1 //===- CloneModule.cpp - Clone an entire module ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the CloneModule interface which makes a copy of an
10 // entire module.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/DerivedTypes.h"
15 #include "llvm/IR/Module.h"
16 #include "llvm/Transforms/Utils/Cloning.h"
17 #include "llvm/Transforms/Utils/ValueMapper.h"
18 using namespace llvm;
19 
20 namespace llvm {
21 class Constant;
22 }
23 
24 static void copyComdat(GlobalObject *Dst, const GlobalObject *Src) {
25   const Comdat *SC = Src->getComdat();
26   if (!SC)
27     return;
28   Comdat *DC = Dst->getParent()->getOrInsertComdat(SC->getName());
29   DC->setSelectionKind(SC->getSelectionKind());
30   Dst->setComdat(DC);
31 }
32 
33 /// This is not as easy as it might seem because we have to worry about making
34 /// copies of global variables and functions, and making their (initializers and
35 /// references, respectively) refer to the right globals.
36 ///
37 std::unique_ptr<Module> llvm::CloneModule(const Module &M) {
38   // Create the value map that maps things from the old module over to the new
39   // module.
40   ValueToValueMapTy VMap;
41   return CloneModule(M, VMap);
42 }
43 
44 std::unique_ptr<Module> llvm::CloneModule(const Module &M,
45                                           ValueToValueMapTy &VMap) {
46   return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; });
47 }
48 
49 std::unique_ptr<Module> llvm::CloneModule(
50     const Module &M, ValueToValueMapTy &VMap,
51     function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
52   // First off, we need to create the new module.
53   std::unique_ptr<Module> New =
54       std::make_unique<Module>(M.getModuleIdentifier(), M.getContext());
55   New->setSourceFileName(M.getSourceFileName());
56   New->setDataLayout(M.getDataLayout());
57   New->setTargetTriple(M.getTargetTriple());
58   New->setModuleInlineAsm(M.getModuleInlineAsm());
59 
60   // Loop over all of the global variables, making corresponding globals in the
61   // new module.  Here we add them to the VMap and to the new Module.  We
62   // don't worry about attributes or initializers, they will come later.
63   //
64   for (const GlobalVariable &I : M.globals()) {
65     GlobalVariable *NewGV = new GlobalVariable(
66         *New, I.getValueType(), I.isConstant(), I.getLinkage(),
67         (Constant *)nullptr, I.getName(), (GlobalVariable *)nullptr,
68         I.getThreadLocalMode(), I.getType()->getAddressSpace());
69     NewGV->copyAttributesFrom(&I);
70     VMap[&I] = NewGV;
71   }
72 
73   // Loop over the functions in the module, making external functions as before
74   for (const Function &I : M) {
75     Function *NF =
76         Function::Create(cast<FunctionType>(I.getValueType()), I.getLinkage(),
77                          I.getAddressSpace(), I.getName(), New.get());
78     NF->copyAttributesFrom(&I);
79     VMap[&I] = NF;
80   }
81 
82   // Loop over the aliases in the module
83   for (const GlobalAlias &I : M.aliases()) {
84     if (!ShouldCloneDefinition(&I)) {
85       // An alias cannot act as an external reference, so we need to create
86       // either a function or a global variable depending on the value type.
87       // FIXME: Once pointee types are gone we can probably pick one or the
88       // other.
89       GlobalValue *GV;
90       if (I.getValueType()->isFunctionTy())
91         GV = Function::Create(cast<FunctionType>(I.getValueType()),
92                               GlobalValue::ExternalLinkage, I.getAddressSpace(),
93                               I.getName(), New.get());
94       else
95         GV = new GlobalVariable(*New, I.getValueType(), false,
96                                 GlobalValue::ExternalLinkage, nullptr,
97                                 I.getName(), nullptr, I.getThreadLocalMode(),
98                                 I.getType()->getAddressSpace());
99       VMap[&I] = GV;
100       // We do not copy attributes (mainly because copying between different
101       // kinds of globals is forbidden), but this is generally not required for
102       // correctness.
103       continue;
104     }
105     auto *GA = GlobalAlias::create(I.getValueType(),
106                                    I.getType()->getPointerAddressSpace(),
107                                    I.getLinkage(), I.getName(), New.get());
108     GA->copyAttributesFrom(&I);
109     VMap[&I] = GA;
110   }
111 
112   // Now that all of the things that global variable initializer can refer to
113   // have been created, loop through and copy the global variable referrers
114   // over...  We also set the attributes on the global now.
115   //
116   for (const GlobalVariable &G : M.globals()) {
117     GlobalVariable *GV = cast<GlobalVariable>(VMap[&G]);
118 
119     SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
120     G.getAllMetadata(MDs);
121     for (auto MD : MDs)
122       GV->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
123 
124     if (G.isDeclaration())
125       continue;
126 
127     if (!ShouldCloneDefinition(&G)) {
128       // Skip after setting the correct linkage for an external reference.
129       GV->setLinkage(GlobalValue::ExternalLinkage);
130       continue;
131     }
132     if (G.hasInitializer())
133       GV->setInitializer(MapValue(G.getInitializer(), VMap));
134 
135     copyComdat(GV, &G);
136   }
137 
138   // Similarly, copy over function bodies now...
139   //
140   for (const Function &I : M) {
141     Function *F = cast<Function>(VMap[&I]);
142 
143     if (I.isDeclaration()) {
144       // Copy over metadata for declarations since we're not doing it below in
145       // CloneFunctionInto().
146       SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
147       I.getAllMetadata(MDs);
148       for (auto MD : MDs)
149         F->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
150       continue;
151     }
152 
153     if (!ShouldCloneDefinition(&I)) {
154       // Skip after setting the correct linkage for an external reference.
155       F->setLinkage(GlobalValue::ExternalLinkage);
156       // Personality function is not valid on a declaration.
157       F->setPersonalityFn(nullptr);
158       continue;
159     }
160 
161     Function::arg_iterator DestI = F->arg_begin();
162     for (const Argument &J : I.args()) {
163       DestI->setName(J.getName());
164       VMap[&J] = &*DestI++;
165     }
166 
167     SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
168     CloneFunctionInto(F, &I, VMap, CloneFunctionChangeType::ClonedModule,
169                       Returns);
170 
171     if (I.hasPersonalityFn())
172       F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap));
173 
174     copyComdat(F, &I);
175   }
176 
177   // And aliases
178   for (const GlobalAlias &I : M.aliases()) {
179     // We already dealt with undefined aliases above.
180     if (!ShouldCloneDefinition(&I))
181       continue;
182     GlobalAlias *GA = cast<GlobalAlias>(VMap[&I]);
183     if (const Constant *C = I.getAliasee())
184       GA->setAliasee(MapValue(C, VMap));
185   }
186 
187   // And named metadata....
188   for (const NamedMDNode &NMD : M.named_metadata()) {
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 
199 LLVMModuleRef LLVMCloneModule(LLVMModuleRef M) {
200   return wrap(CloneModule(*unwrap(M)).release());
201 }
202 
203 }
204