SplitModule.cpp 9.8 KB

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