SplitModule.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. //===- SplitModule.cpp - Split a module into partitions -------------------===//
  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 defines the function llvm::SplitModule, which splits a module
  10. // into multiple linkable partitions. It can be used to implement parallel code
  11. // generation for link-time optimization.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/SplitModule.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/EquivalenceClasses.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/IR/Comdat.h"
  21. #include "llvm/IR/Constant.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/Function.h"
  24. #include "llvm/IR/GlobalAlias.h"
  25. #include "llvm/IR/GlobalObject.h"
  26. #include "llvm/IR/GlobalIndirectSymbol.h"
  27. #include "llvm/IR/GlobalValue.h"
  28. #include "llvm/IR/GlobalVariable.h"
  29. #include "llvm/IR/Instruction.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/IR/User.h"
  32. #include "llvm/IR/Value.h"
  33. #include "llvm/Support/Casting.h"
  34. #include "llvm/Support/Debug.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include "llvm/Support/MD5.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Transforms/Utils/Cloning.h"
  39. #include "llvm/Transforms/Utils/ValueMapper.h"
  40. #include <algorithm>
  41. #include <cassert>
  42. #include <iterator>
  43. #include <memory>
  44. #include <queue>
  45. #include <utility>
  46. #include <vector>
  47. using namespace llvm;
  48. #define DEBUG_TYPE "split-module"
  49. namespace {
  50. using ClusterMapType = EquivalenceClasses<const GlobalValue *>;
  51. using ComdatMembersType = DenseMap<const Comdat *, const GlobalValue *>;
  52. using ClusterIDMapType = DenseMap<const GlobalValue *, unsigned>;
  53. } // end anonymous namespace
  54. static void addNonConstUser(ClusterMapType &GVtoClusterMap,
  55. const GlobalValue *GV, const User *U) {
  56. assert((!isa<Constant>(U) || isa<GlobalValue>(U)) && "Bad user");
  57. if (const Instruction *I = dyn_cast<Instruction>(U)) {
  58. const GlobalValue *F = I->getParent()->getParent();
  59. GVtoClusterMap.unionSets(GV, F);
  60. } else if (isa<GlobalIndirectSymbol>(U) || isa<Function>(U) ||
  61. isa<GlobalVariable>(U)) {
  62. GVtoClusterMap.unionSets(GV, cast<GlobalValue>(U));
  63. } else {
  64. llvm_unreachable("Underimplemented use case");
  65. }
  66. }
  67. // Adds all GlobalValue users of V to the same cluster as GV.
  68. static void addAllGlobalValueUsers(ClusterMapType &GVtoClusterMap,
  69. const GlobalValue *GV, const Value *V) {
  70. for (auto *U : V->users()) {
  71. SmallVector<const User *, 4> Worklist;
  72. Worklist.push_back(U);
  73. while (!Worklist.empty()) {
  74. const User *UU = Worklist.pop_back_val();
  75. // For each constant that is not a GV (a pure const) recurse.
  76. if (isa<Constant>(UU) && !isa<GlobalValue>(UU)) {
  77. Worklist.append(UU->user_begin(), UU->user_end());
  78. continue;
  79. }
  80. addNonConstUser(GVtoClusterMap, GV, UU);
  81. }
  82. }
  83. }
  84. // Find partitions for module in the way that no locals need to be
  85. // globalized.
  86. // Try to balance pack those partitions into N files since this roughly equals
  87. // thread balancing for the backend codegen step.
  88. static void findPartitions(Module *M, ClusterIDMapType &ClusterIDMap,
  89. unsigned N) {
  90. // At this point module should have the proper mix of globals and locals.
  91. // As we attempt to partition this module, we must not change any
  92. // locals to globals.
  93. LLVM_DEBUG(dbgs() << "Partition module with (" << M->size()
  94. << ")functions\n");
  95. ClusterMapType GVtoClusterMap;
  96. ComdatMembersType ComdatMembers;
  97. auto recordGVSet = [&GVtoClusterMap, &ComdatMembers](GlobalValue &GV) {
  98. if (GV.isDeclaration())
  99. return;
  100. if (!GV.hasName())
  101. GV.setName("__llvmsplit_unnamed");
  102. // Comdat groups must not be partitioned. For comdat groups that contain
  103. // locals, record all their members here so we can keep them together.
  104. // Comdat groups that only contain external globals are already handled by
  105. // the MD5-based partitioning.
  106. if (const Comdat *C = GV.getComdat()) {
  107. auto &Member = ComdatMembers[C];
  108. if (Member)
  109. GVtoClusterMap.unionSets(Member, &GV);
  110. else
  111. Member = &GV;
  112. }
  113. // For aliases we should not separate them from their aliasees regardless
  114. // of linkage.
  115. if (auto *GIS = dyn_cast<GlobalIndirectSymbol>(&GV)) {
  116. if (const GlobalObject *Base = GIS->getBaseObject())
  117. GVtoClusterMap.unionSets(&GV, Base);
  118. }
  119. if (const Function *F = dyn_cast<Function>(&GV)) {
  120. for (const BasicBlock &BB : *F) {
  121. BlockAddress *BA = BlockAddress::lookup(&BB);
  122. if (!BA || !BA->isConstantUsed())
  123. continue;
  124. addAllGlobalValueUsers(GVtoClusterMap, F, BA);
  125. }
  126. }
  127. if (GV.hasLocalLinkage())
  128. addAllGlobalValueUsers(GVtoClusterMap, &GV, &GV);
  129. };
  130. llvm::for_each(M->functions(), recordGVSet);
  131. llvm::for_each(M->globals(), recordGVSet);
  132. llvm::for_each(M->aliases(), recordGVSet);
  133. // Assigned all GVs to merged clusters while balancing number of objects in
  134. // each.
  135. auto CompareClusters = [](const std::pair<unsigned, unsigned> &a,
  136. const std::pair<unsigned, unsigned> &b) {
  137. if (a.second || b.second)
  138. return a.second > b.second;
  139. else
  140. return a.first > b.first;
  141. };
  142. std::priority_queue<std::pair<unsigned, unsigned>,
  143. std::vector<std::pair<unsigned, unsigned>>,
  144. decltype(CompareClusters)>
  145. BalancinQueue(CompareClusters);
  146. // Pre-populate priority queue with N slot blanks.
  147. for (unsigned i = 0; i < N; ++i)
  148. BalancinQueue.push(std::make_pair(i, 0));
  149. using SortType = std::pair<unsigned, ClusterMapType::iterator>;
  150. SmallVector<SortType, 64> Sets;
  151. SmallPtrSet<const GlobalValue *, 32> Visited;
  152. // To guarantee determinism, we have to sort SCC according to size.
  153. // When size is the same, use leader's name.
  154. for (ClusterMapType::iterator I = GVtoClusterMap.begin(),
  155. E = GVtoClusterMap.end(); I != E; ++I)
  156. if (I->isLeader())
  157. Sets.push_back(
  158. std::make_pair(std::distance(GVtoClusterMap.member_begin(I),
  159. GVtoClusterMap.member_end()), I));
  160. llvm::sort(Sets, [](const SortType &a, const SortType &b) {
  161. if (a.first == b.first)
  162. return a.second->getData()->getName() > b.second->getData()->getName();
  163. else
  164. return a.first > b.first;
  165. });
  166. for (auto &I : Sets) {
  167. unsigned CurrentClusterID = BalancinQueue.top().first;
  168. unsigned CurrentClusterSize = BalancinQueue.top().second;
  169. BalancinQueue.pop();
  170. LLVM_DEBUG(dbgs() << "Root[" << CurrentClusterID << "] cluster_size("
  171. << I.first << ") ----> " << I.second->getData()->getName()
  172. << "\n");
  173. for (ClusterMapType::member_iterator MI =
  174. GVtoClusterMap.findLeader(I.second);
  175. MI != GVtoClusterMap.member_end(); ++MI) {
  176. if (!Visited.insert(*MI).second)
  177. continue;
  178. LLVM_DEBUG(dbgs() << "----> " << (*MI)->getName()
  179. << ((*MI)->hasLocalLinkage() ? " l " : " e ") << "\n");
  180. Visited.insert(*MI);
  181. ClusterIDMap[*MI] = CurrentClusterID;
  182. CurrentClusterSize++;
  183. }
  184. // Add this set size to the number of entries in this cluster.
  185. BalancinQueue.push(std::make_pair(CurrentClusterID, CurrentClusterSize));
  186. }
  187. }
  188. static void externalize(GlobalValue *GV) {
  189. if (GV->hasLocalLinkage()) {
  190. GV->setLinkage(GlobalValue::ExternalLinkage);
  191. GV->setVisibility(GlobalValue::HiddenVisibility);
  192. }
  193. // Unnamed entities must be named consistently between modules. setName will
  194. // give a distinct name to each such entity.
  195. if (!GV->hasName())
  196. GV->setName("__llvmsplit_unnamed");
  197. }
  198. // Returns whether GV should be in partition (0-based) I of N.
  199. static bool isInPartition(const GlobalValue *GV, unsigned I, unsigned N) {
  200. if (auto *GIS = dyn_cast<GlobalIndirectSymbol>(GV))
  201. if (const GlobalObject *Base = GIS->getBaseObject())
  202. GV = Base;
  203. StringRef Name;
  204. if (const Comdat *C = GV->getComdat())
  205. Name = C->getName();
  206. else
  207. Name = GV->getName();
  208. // Partition by MD5 hash. We only need a few bits for evenness as the number
  209. // of partitions will generally be in the 1-2 figure range; the low 16 bits
  210. // are enough.
  211. MD5 H;
  212. MD5::MD5Result R;
  213. H.update(Name);
  214. H.final(R);
  215. return (R[0] | (R[1] << 8)) % N == I;
  216. }
  217. void llvm::SplitModule(
  218. std::unique_ptr<Module> M, unsigned N,
  219. function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback,
  220. bool PreserveLocals) {
  221. if (!PreserveLocals) {
  222. for (Function &F : *M)
  223. externalize(&F);
  224. for (GlobalVariable &GV : M->globals())
  225. externalize(&GV);
  226. for (GlobalAlias &GA : M->aliases())
  227. externalize(&GA);
  228. for (GlobalIFunc &GIF : M->ifuncs())
  229. externalize(&GIF);
  230. }
  231. // This performs splitting without a need for externalization, which might not
  232. // always be possible.
  233. ClusterIDMapType ClusterIDMap;
  234. findPartitions(M.get(), ClusterIDMap, N);
  235. // FIXME: We should be able to reuse M as the last partition instead of
  236. // cloning it.
  237. for (unsigned I = 0; I < N; ++I) {
  238. ValueToValueMapTy VMap;
  239. std::unique_ptr<Module> MPart(
  240. CloneModule(*M, VMap, [&](const GlobalValue *GV) {
  241. if (ClusterIDMap.count(GV))
  242. return (ClusterIDMap[GV] == I);
  243. else
  244. return isInPartition(GV, I, N);
  245. }));
  246. if (I != 0)
  247. MPart->setModuleInlineAsm("");
  248. ModuleCallback(std::move(MPart));
  249. }
  250. }