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