CloneModule.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 (const GlobalVariable &I : M.globals()) {
  56. GlobalVariable *NewGV = new GlobalVariable(
  57. *New, I.getValueType(), I.isConstant(), I.getLinkage(),
  58. (Constant *)nullptr, I.getName(), (GlobalVariable *)nullptr,
  59. I.getThreadLocalMode(), I.getType()->getAddressSpace());
  60. NewGV->copyAttributesFrom(&I);
  61. VMap[&I] = NewGV;
  62. }
  63. // Loop over the functions in the module, making external functions as before
  64. for (const Function &I : M) {
  65. Function *NF =
  66. Function::Create(cast<FunctionType>(I.getValueType()), I.getLinkage(),
  67. I.getAddressSpace(), I.getName(), New.get());
  68. NF->copyAttributesFrom(&I);
  69. VMap[&I] = NF;
  70. }
  71. // Loop over the aliases in the module
  72. for (const GlobalAlias &I : M.aliases()) {
  73. if (!ShouldCloneDefinition(&I)) {
  74. // An alias cannot act as an external reference, so we need to create
  75. // either a function or a global variable depending on the value type.
  76. // FIXME: Once pointee types are gone we can probably pick one or the
  77. // other.
  78. GlobalValue *GV;
  79. if (I.getValueType()->isFunctionTy())
  80. GV = Function::Create(cast<FunctionType>(I.getValueType()),
  81. GlobalValue::ExternalLinkage, I.getAddressSpace(),
  82. I.getName(), New.get());
  83. else
  84. GV = new GlobalVariable(*New, I.getValueType(), false,
  85. GlobalValue::ExternalLinkage, nullptr,
  86. I.getName(), nullptr, I.getThreadLocalMode(),
  87. I.getType()->getAddressSpace());
  88. VMap[&I] = GV;
  89. // We do not copy attributes (mainly because copying between different
  90. // kinds of globals is forbidden), but this is generally not required for
  91. // correctness.
  92. continue;
  93. }
  94. auto *GA = GlobalAlias::create(I.getValueType(),
  95. I.getType()->getPointerAddressSpace(),
  96. I.getLinkage(), I.getName(), New.get());
  97. GA->copyAttributesFrom(&I);
  98. VMap[&I] = GA;
  99. }
  100. // Now that all of the things that global variable initializer can refer to
  101. // have been created, loop through and copy the global variable referrers
  102. // over... We also set the attributes on the global now.
  103. //
  104. for (const GlobalVariable &G : M.globals()) {
  105. GlobalVariable *GV = cast<GlobalVariable>(VMap[&G]);
  106. SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
  107. G.getAllMetadata(MDs);
  108. for (auto MD : MDs)
  109. GV->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
  110. if (G.isDeclaration())
  111. continue;
  112. if (!ShouldCloneDefinition(&G)) {
  113. // Skip after setting the correct linkage for an external reference.
  114. GV->setLinkage(GlobalValue::ExternalLinkage);
  115. continue;
  116. }
  117. if (G.hasInitializer())
  118. GV->setInitializer(MapValue(G.getInitializer(), VMap));
  119. copyComdat(GV, &G);
  120. }
  121. // Similarly, copy over function bodies now...
  122. //
  123. for (const Function &I : M) {
  124. Function *F = cast<Function>(VMap[&I]);
  125. if (I.isDeclaration()) {
  126. // Copy over metadata for declarations since we're not doing it below in
  127. // CloneFunctionInto().
  128. SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
  129. I.getAllMetadata(MDs);
  130. for (auto MD : MDs)
  131. F->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
  132. continue;
  133. }
  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 (const Argument &J : I.args()) {
  143. DestI->setName(J.getName());
  144. VMap[&J] = &*DestI++;
  145. }
  146. SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
  147. CloneFunctionInto(F, &I, VMap, CloneFunctionChangeType::ClonedModule,
  148. Returns);
  149. if (I.hasPersonalityFn())
  150. F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap));
  151. copyComdat(F, &I);
  152. }
  153. // And aliases
  154. for (const GlobalAlias &I : M.aliases()) {
  155. // We already dealt with undefined aliases above.
  156. if (!ShouldCloneDefinition(&I))
  157. continue;
  158. GlobalAlias *GA = cast<GlobalAlias>(VMap[&I]);
  159. if (const Constant *C = I.getAliasee())
  160. GA->setAliasee(MapValue(C, VMap));
  161. }
  162. // And named metadata....
  163. for (const NamedMDNode &NMD : M.named_metadata()) {
  164. NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName());
  165. for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
  166. NewNMD->addOperand(MapMetadata(NMD.getOperand(i), VMap));
  167. }
  168. return New;
  169. }
  170. extern "C" {
  171. LLVMModuleRef LLVMCloneModule(LLVMModuleRef M) {
  172. return wrap(CloneModule(*unwrap(M)).release());
  173. }
  174. }