CloneModule.cpp 7.9 KB

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