CloneModule.cpp 7.7 KB

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