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