LLVM 24.0.0git
AMDGPUSplitModule.cpp
Go to the documentation of this file.
1//===- AMDGPUSplitModule.cpp ----------------------------------------------===//
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/// \file Implements a module splitting algorithm designed to support the
10/// FullLTO --lto-partitions option for parallel codegen.
11///
12/// The role of this module splitting pass is the same as
13/// lib/Transforms/Utils/SplitModule.cpp: load-balance the module's functions
14/// across a set of N partitions to allow for parallel codegen.
15///
16/// The similarities mostly end here, as this pass achieves load-balancing in a
17/// more elaborate fashion which is targeted towards AMDGPU modules. It can take
18/// advantage of the structure of AMDGPU modules (which are mostly
19/// self-contained) to allow for more efficient splitting without affecting
20/// codegen negatively, or causing innaccurate resource usage analysis.
21///
22/// High-level pass overview:
23/// - SplitGraph & associated classes
24/// - Graph representation of the module and of the dependencies that
25/// matter for splitting.
26/// - RecursiveSearchSplitting
27/// - Core splitting algorithm.
28/// - SplitProposal
29/// - Represents a suggested solution for splitting the input module. These
30/// solutions can be scored to determine the best one when multiple
31/// solutions are available.
32/// - Driver/pass "run" function glues everything together.
33
34#include "AMDGPUSplitModule.h"
40#include "llvm/ADT/StringRef.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/GlobalAlias.h"
46#include "llvm/IR/Instruction.h"
47#include "llvm/IR/Module.h"
49#include "llvm/IR/Value.h"
53#include "llvm/Support/Debug.h"
55#include "llvm/Support/Path.h"
56#include "llvm/Support/Timer.h"
60#include <cassert>
61#include <cmath>
62#include <utility>
63
64#ifndef NDEBUG
66#endif
67
68#define DEBUG_TYPE "amdgpu-split-module"
69
70namespace llvm {
71namespace {
72
73static cl::opt<unsigned> MaxDepth(
74 "amdgpu-module-splitting-max-depth",
75 cl::desc(
76 "maximum search depth. 0 forces a greedy approach. "
77 "warning: the algorithm is up to O(2^N), where N is the max depth."),
78 cl::init(8));
79
80static cl::opt<float> LargeFnFactor(
81 "amdgpu-module-splitting-large-threshold", cl::init(2.0f), cl::Hidden,
82 cl::desc(
83 "when max depth is reached and we can no longer branch out, this "
84 "value determines if a function is worth merging into an already "
85 "existing partition to reduce code duplication. This is a factor "
86 "of the ideal partition size, e.g. 2.0 means we consider the "
87 "function for merging if its cost (including its callees) is 2x the "
88 "size of an ideal partition."));
89
90static cl::opt<float> LargeFnOverlapForMerge(
91 "amdgpu-module-splitting-merge-threshold", cl::init(0.7f), cl::Hidden,
92 cl::desc("when a function is considered for merging into a partition that "
93 "already contains some of its callees, do the merge if at least "
94 "n% of the code it can reach is already present inside the "
95 "partition; e.g. 0.7 means only merge >70%"));
96
97static cl::opt<bool> NoExternalizeGlobals(
98 "amdgpu-module-splitting-no-externalize-globals", cl::Hidden,
99 cl::desc("disables externalization of global variable with local linkage; "
100 "may cause globals to be duplicated which increases binary size"));
101
102static cl::opt<bool> NoExternalizeOnAddrTaken(
103 "amdgpu-module-splitting-no-externalize-address-taken", cl::Hidden,
104 cl::desc(
105 "disables externalization of functions whose addresses are taken"));
106
108 ModuleDotCfgOutput("amdgpu-module-splitting-print-module-dotcfg",
110 cl::desc("output file to write out the dotgraph "
111 "representation of the input module"));
112
113static cl::opt<std::string> PartitionSummariesOutput(
114 "amdgpu-module-splitting-print-partition-summaries", cl::Hidden,
115 cl::desc("output file to write out a summary of "
116 "the partitions created for each module"));
117
118#ifndef NDEBUG
119static cl::opt<bool>
120 UseLockFile("amdgpu-module-splitting-serial-execution", cl::Hidden,
121 cl::desc("use a lock file so only one process in the system "
122 "can run this pass at once. useful to avoid mangled "
123 "debug output in multithreaded environments."));
124
125static cl::opt<bool>
126 DebugProposalSearch("amdgpu-module-splitting-debug-proposal-search",
128 cl::desc("print all proposals received and whether "
129 "they were rejected or accepted"));
130#endif
131
132struct SplitModuleTimer : NamedRegionTimer {
133 SplitModuleTimer(StringRef Name, StringRef Desc)
134 : NamedRegionTimer(Name, Desc, DEBUG_TYPE, "AMDGPU Module Splitting",
136};
137
138//===----------------------------------------------------------------------===//
139// Utils
140//===----------------------------------------------------------------------===//
141
142using CostType = InstructionCost::CostType;
143using FunctionsCostMap = DenseMap<const Function *, CostType>;
144using GetTTIFn = function_ref<const TargetTransformInfo &(Function &)>;
145static constexpr unsigned InvalidPID = -1;
146
147/// \param Num numerator
148/// \param Dem denominator
149/// \returns a printable object to print (Num/Dem) using "%0.2f".
150static auto formatRatioOf(CostType Num, CostType Dem) {
151 CostType DemOr1 = Dem ? Dem : 1;
152 return format("%0.2f", (static_cast<double>(Num) / DemOr1) * 100);
153}
154
155/// Checks whether a given function is non-copyable.
156///
157/// Non-copyable functions cannot be cloned into multiple partitions, and only
158/// one copy of the function can be present across all partitions.
159///
160/// Kernel functions and external functions fall into this category. If we were
161/// to clone them, we would end up with multiple symbol definitions and a very
162/// unhappy linker.
163static bool isNonCopyable(const Function &F) {
164 return F.hasExternalLinkage() || !F.isDefinitionExact() ||
165 AMDGPU::isEntryFunctionCC(F.getCallingConv());
166}
167
168/// Cost analysis function. Calculates the cost of each function in \p M
169///
170/// \param GetTTI Abstract getter for TargetTransformInfo.
171/// \param M Module to analyze.
172/// \param CostMap[out] Resulting Function -> Cost map.
173/// \return The module's total cost.
174static CostType calculateFunctionCosts(GetTTIFn GetTTI, Module &M,
175 FunctionsCostMap &CostMap) {
176 SplitModuleTimer SMT("calculateFunctionCosts", "cost analysis");
177
178 LLVM_DEBUG(dbgs() << "[cost analysis] calculating function costs\n");
179 CostType ModuleCost = 0;
180 [[maybe_unused]] CostType KernelCost = 0;
181
182 for (auto &Fn : M) {
183 if (Fn.isDeclaration())
184 continue;
185
186 CostType FnCost = 0;
187 const auto &TTI = GetTTI(Fn);
188 for (const auto &BB : Fn) {
189 for (const auto &I : BB) {
190 auto Cost =
193 // Assume expensive if we can't tell the cost of an instruction.
194 CostType CostVal = Cost.isValid()
195 ? Cost.getValue()
197 assert((FnCost + CostVal) >= FnCost && "Overflow!");
198 FnCost += CostVal;
199 }
200 }
201
202 assert(FnCost != 0);
203
204 CostMap[&Fn] = FnCost;
205 assert((ModuleCost + FnCost) >= ModuleCost && "Overflow!");
206 ModuleCost += FnCost;
207
208 if (AMDGPU::isEntryFunctionCC(Fn.getCallingConv()))
209 KernelCost += FnCost;
210 }
211
212 if (CostMap.empty())
213 return 0;
214
215 assert(ModuleCost);
216 LLVM_DEBUG({
217 const CostType FnCost = ModuleCost - KernelCost;
218 dbgs() << " - total module cost is " << ModuleCost << ". kernels cost "
219 << "" << KernelCost << " ("
220 << format("%0.2f", (float(KernelCost) / ModuleCost) * 100)
221 << "% of the module), functions cost " << FnCost << " ("
222 << format("%0.2f", (float(FnCost) / ModuleCost) * 100)
223 << "% of the module)\n";
224 });
225
226 return ModuleCost;
227}
228
229/// \return true if \p F can be indirectly called
230static bool canBeIndirectlyCalled(const Function &F) {
231 if (F.isDeclaration() || AMDGPU::isEntryFunctionCC(F.getCallingConv()))
232 return false;
233 return !F.hasLocalLinkage() ||
234 F.hasAddressTaken(/*PutOffender=*/nullptr,
235 /*IgnoreCallbackUses=*/false,
236 /*IgnoreAssumeLikeCalls=*/true,
237 /*IgnoreLLVMUsed=*/true,
238 /*IgnoreARCAttachedCall=*/false,
239 /*IgnoreCastedDirectCall=*/true);
240}
241
242//===----------------------------------------------------------------------===//
243// Graph-based Module Representation
244//===----------------------------------------------------------------------===//
245
246/// AMDGPUSplitModule's view of the source Module, as a graph of all components
247/// that can be split into different modules.
248///
249/// The most trivial instance of this graph is just the CallGraph of the module,
250/// but it is not guaranteed that the graph is strictly equal to the CG. It
251/// currently always is but it's designed in a way that would eventually allow
252/// us to create abstract nodes, or nodes for different entities such as global
253/// variables or any other meaningful constraint we must consider.
254///
255/// The graph is only mutable by this class, and is generally not modified
256/// after \ref SplitGraph::buildGraph runs. No consumers of the graph can
257/// mutate it.
258class SplitGraph {
259public:
260 class Node;
261
262 enum class EdgeKind : uint8_t {
263 /// The nodes are related through a direct call. This is a "strong" edge as
264 /// it means the Src will directly reference the Dst.
266 /// The nodes are related through an indirect call.
267 /// This is a "weaker" edge and is only considered when traversing the graph
268 /// starting from a kernel. We need this edge for resource usage analysis.
269 ///
270 /// The reason why we have this edge in the first place is due to how
271 /// AMDGPUResourceUsageAnalysis works. In the presence of an indirect call,
272 /// the resource usage of the kernel containing the indirect call is the
273 /// max resource usage of all functions that can be indirectly called.
275 };
276
277 /// An edge between two nodes. Edges are directional, and tagged with a
278 /// "kind".
279 struct Edge {
280 Edge(Node *Src, Node *Dst, EdgeKind Kind)
281 : Src(Src), Dst(Dst), Kind(Kind) {}
282
283 Node *Src; ///< Source
284 Node *Dst; ///< Destination
285 EdgeKind Kind;
286 };
287
288 using EdgesVec = SmallVector<const Edge *, 0>;
289 using edges_iterator = EdgesVec::const_iterator;
290 using nodes_iterator = const Node *const *;
291
292 SplitGraph(const Module &M, const FunctionsCostMap &CostMap,
293 CostType ModuleCost)
294 : M(M), CostMap(CostMap), ModuleCost(ModuleCost) {}
295
296 void buildGraph(CallGraph &CG);
297
298#ifndef NDEBUG
299 bool verifyGraph() const;
300#endif
301
302 bool empty() const { return Nodes.empty(); }
303 iterator_range<nodes_iterator> nodes() const { return Nodes; }
304 const Node &getNode(unsigned ID) const { return *Nodes[ID]; }
305
306 unsigned getNumNodes() const { return Nodes.size(); }
307 BitVector createNodesBitVector() const { return BitVector(Nodes.size()); }
308
309 const Module &getModule() const { return M; }
310
311 CostType getModuleCost() const { return ModuleCost; }
312 CostType getCost(const Function &F) const { return CostMap.at(&F); }
313
314 /// \returns the aggregated cost of all nodes in \p BV (bits set to 1 = node
315 /// IDs).
316 CostType calculateCost(const BitVector &BV) const;
317
318private:
319 /// Retrieves the node for \p GV in \p Cache, or creates a new node for it and
320 /// updates \p Cache.
321 Node &getNode(DenseMap<const GlobalValue *, Node *> &Cache,
322 const GlobalValue &GV);
323
324 // Create a new edge between two nodes and add it to both nodes.
325 const Edge &createEdge(Node &Src, Node &Dst, EdgeKind EK);
326
327 const Module &M;
328 const FunctionsCostMap &CostMap;
329 CostType ModuleCost;
330
331 // Final list of nodes with stable ordering.
333
334 SpecificBumpPtrAllocator<Node> NodesPool;
335
336 // Edges are trivially destructible objects, so as a small optimization we
337 // use a BumpPtrAllocator which avoids destructor calls but also makes
338 // allocation faster.
339 static_assert(
340 std::is_trivially_destructible_v<Edge>,
341 "Edge must be trivially destructible to use the BumpPtrAllocator");
342 BumpPtrAllocator EdgesPool;
343};
344
345/// Nodes in the SplitGraph contain both incoming, and outgoing edges.
346/// Incoming edges have this node as their Dst, and Outgoing ones have this node
347/// as their Src.
348///
349/// Edge objects are shared by both nodes in Src/Dst. They provide immediate
350/// feedback on how two nodes are related, and in which direction they are
351/// related, which is valuable information to make splitting decisions.
352///
353/// Nodes are fundamentally abstract, and any consumers of the graph should
354/// treat them as such. While a node will be a function most of the time, we
355/// could also create nodes for any other reason. In the future, we could have
356/// single nodes for multiple functions, or nodes for GVs, etc.
357class SplitGraph::Node {
358 friend class SplitGraph;
359
360public:
361 Node(unsigned ID, const GlobalValue &GV, CostType IndividualCost,
362 bool IsNonCopyable)
363 : ID(ID), GV(GV), IndividualCost(IndividualCost),
364 IsNonCopyable(IsNonCopyable), IsEntryFnCC(false), IsGraphEntry(false) {
365 if (auto *Fn = dyn_cast<Function>(&GV))
366 IsEntryFnCC = AMDGPU::isEntryFunctionCC(Fn->getCallingConv());
367 }
368
369 /// An 0-indexed ID for the node. The maximum ID (exclusive) is the number of
370 /// nodes in the graph. This ID can be used as an index in a BitVector.
371 unsigned getID() const { return ID; }
372
373 const Function &getFunction() const { return cast<Function>(GV); }
374
375 /// \returns the cost to import this component into a given module, not
376 /// accounting for any dependencies that may need to be imported as well.
377 CostType getIndividualCost() const { return IndividualCost; }
378
379 bool isNonCopyable() const { return IsNonCopyable; }
380 bool isEntryFunctionCC() const { return IsEntryFnCC; }
381
382 /// \returns whether this is an entry point in the graph. Entry points are
383 /// defined as follows: if you take all entry points in the graph, and iterate
384 /// their dependencies, you are guaranteed to visit all nodes in the graph at
385 /// least once.
386 bool isGraphEntryPoint() const { return IsGraphEntry; }
387
388 StringRef getName() const { return GV.getName(); }
389
390 bool hasAnyIncomingEdges() const { return IncomingEdges.size(); }
391 bool hasAnyIncomingEdgesOfKind(EdgeKind EK) const {
392 return any_of(IncomingEdges, [&](const auto *E) { return E->Kind == EK; });
393 }
394
395 bool hasAnyOutgoingEdges() const { return OutgoingEdges.size(); }
396 bool hasAnyOutgoingEdgesOfKind(EdgeKind EK) const {
397 return any_of(OutgoingEdges, [&](const auto *E) { return E->Kind == EK; });
398 }
399
400 iterator_range<edges_iterator> incoming_edges() const {
401 return IncomingEdges;
402 }
403
404 iterator_range<edges_iterator> outgoing_edges() const {
405 return OutgoingEdges;
406 }
407
408 bool shouldFollowIndirectCalls() const { return isEntryFunctionCC(); }
409
410 /// Visit all children of this node in a recursive fashion. Also visits Self.
411 /// If \ref shouldFollowIndirectCalls returns false, then this only follows
412 /// DirectCall edges.
413 ///
414 /// \param Visitor Visitor Function.
415 void visitAllDependencies(std::function<void(const Node &)> Visitor) const;
416
417 /// Adds the depedencies of this node in \p BV by setting the bit
418 /// corresponding to each node.
419 ///
420 /// Implemented using \ref visitAllDependencies, hence it follows the same
421 /// rules regarding dependencies traversal.
422 ///
423 /// \param[out] BV The bitvector where the bits should be set.
424 void getDependencies(BitVector &BV) const {
425 visitAllDependencies([&](const Node &N) { BV.set(N.getID()); });
426 }
427
428private:
429 void markAsGraphEntry() { IsGraphEntry = true; }
430
431 unsigned ID;
432 const GlobalValue &GV;
433 CostType IndividualCost;
434 bool IsNonCopyable : 1;
435 bool IsEntryFnCC : 1;
436 bool IsGraphEntry : 1;
437
438 // TODO: Use a single sorted vector (with all incoming/outgoing edges grouped
439 // together)
440 EdgesVec IncomingEdges;
441 EdgesVec OutgoingEdges;
442};
443
444void SplitGraph::Node::visitAllDependencies(
445 std::function<void(const Node &)> Visitor) const {
446 const bool FollowIndirect = shouldFollowIndirectCalls();
447 // FIXME: If this can access SplitGraph in the future, use a BitVector
448 // instead.
449 DenseSet<const Node *> Seen;
450 SmallVector<const Node *, 8> WorkList({this});
451 while (!WorkList.empty()) {
452 const Node *CurN = WorkList.pop_back_val();
453 if (auto [It, Inserted] = Seen.insert(CurN); !Inserted)
454 continue;
455
456 Visitor(*CurN);
457
458 for (const Edge *E : CurN->outgoing_edges()) {
459 if (!FollowIndirect && E->Kind == EdgeKind::IndirectCall)
460 continue;
461 WorkList.push_back(E->Dst);
462 }
463 }
464}
465
466/// Checks if \p I has MD_callees and if it does, parse it and put the function
467/// in \p Callees.
468///
469/// \returns true if there was metadata and it was parsed correctly. false if
470/// there was no MD or if it contained unknown entries and parsing failed.
471/// If this returns false, \p Callees will contain incomplete information
472/// and must not be used.
473static bool handleCalleesMD(const Instruction &I,
474 SetVector<Function *> &Callees) {
475 auto *MD = I.getMetadata(LLVMContext::MD_callees);
476 if (!MD)
477 return false;
478
479 for (const auto &Op : MD->operands()) {
480 Function *Callee = mdconst::extract_or_null<Function>(Op);
481 if (!Callee)
482 return false;
483 Callees.insert(Callee);
484 }
485
486 return true;
487}
488
489void SplitGraph::buildGraph(CallGraph &CG) {
490 SplitModuleTimer SMT("buildGraph", "graph construction");
492 dbgs()
493 << "[build graph] constructing graph representation of the input\n");
494
495 // FIXME(?): Is the callgraph really worth using if we have to iterate the
496 // function again whenever it fails to give us enough information?
497
498 // We build the graph by just iterating all functions in the module and
499 // working on their direct callees. At the end, all nodes should be linked
500 // together as expected.
501 DenseMap<const GlobalValue *, Node *> Cache;
502 SmallVector<const Function *> FnsWithIndirectCalls, IndirectlyCallableFns;
503 for (const Function &Fn : M) {
504 if (Fn.isDeclaration())
505 continue;
506
507 // Look at direct callees and create the necessary edges in the graph.
508 SetVector<const Function *> DirectCallees;
509 bool CallsExternal = false;
510 for (auto &CGEntry : *CG[&Fn]) {
511 auto *CGNode = CGEntry.second;
512 if (auto *Callee = CGNode->getFunction()) {
513 if (!Callee->isDeclaration())
514 DirectCallees.insert(Callee);
515 } else if (CGNode == CG.getCallsExternalNode())
516 CallsExternal = true;
517 }
518
519 // Keep track of this function if it contains an indirect call and/or if it
520 // can be indirectly called.
521 if (CallsExternal) {
522 LLVM_DEBUG(dbgs() << " [!] callgraph is incomplete for ";
523 Fn.printAsOperand(dbgs());
524 dbgs() << " - analyzing function\n");
525
526 SetVector<Function *> KnownCallees;
527 bool HasUnknownIndirectCall = false;
528 for (const auto &Inst : instructions(Fn)) {
529 // look at all calls without a direct callee.
530 const auto *CB = dyn_cast<CallBase>(&Inst);
531 if (!CB || CB->getCalledFunction())
532 continue;
533
534 // inline assembly can be ignored, unless InlineAsmIsIndirectCall is
535 // true.
536 if (CB->isInlineAsm()) {
537 LLVM_DEBUG(dbgs() << " found inline assembly\n");
538 continue;
539 }
540
541 if (handleCalleesMD(Inst, KnownCallees))
542 continue;
543 // If we failed to parse any !callees MD, or some was missing,
544 // the entire KnownCallees list is now unreliable.
545 KnownCallees.clear();
546
547 // Everything else is handled conservatively. If we fall into the
548 // conservative case don't bother analyzing further.
549 HasUnknownIndirectCall = true;
550 break;
551 }
552
553 if (HasUnknownIndirectCall) {
554 LLVM_DEBUG(dbgs() << " indirect call found\n");
555 FnsWithIndirectCalls.push_back(&Fn);
556 } else if (!KnownCallees.empty())
557 DirectCallees.insert_range(KnownCallees);
558 }
559
560 Node &N = getNode(Cache, Fn);
561 for (const auto *Callee : DirectCallees)
562 createEdge(N, getNode(Cache, *Callee), EdgeKind::DirectCall);
563
564 if (canBeIndirectlyCalled(Fn))
565 IndirectlyCallableFns.push_back(&Fn);
566 }
567
568 // Post-process functions with indirect calls.
569 for (const Function *Fn : FnsWithIndirectCalls) {
570 for (const Function *Candidate : IndirectlyCallableFns) {
571 Node &Src = getNode(Cache, *Fn);
572 Node &Dst = getNode(Cache, *Candidate);
573 createEdge(Src, Dst, EdgeKind::IndirectCall);
574 }
575 }
576
577 // Now, find all entry points.
578 SmallVector<Node *, 16> CandidateEntryPoints;
579 BitVector NodesReachableByKernels = createNodesBitVector();
580 for (Node *N : Nodes) {
581 // Functions with an Entry CC are always graph entry points too.
582 if (N->isEntryFunctionCC()) {
583 N->markAsGraphEntry();
584 N->getDependencies(NodesReachableByKernels);
585 } else if (!N->hasAnyIncomingEdgesOfKind(EdgeKind::DirectCall))
586 CandidateEntryPoints.push_back(N);
587 }
588
589 for (Node *N : CandidateEntryPoints) {
590 // This can be another entry point if it's not reachable by a kernel
591 // TODO: We could sort all of the possible new entries in a stable order
592 // (e.g. by cost), then consume them one by one until
593 // NodesReachableByKernels is all 1s. It'd allow us to avoid
594 // considering some nodes as non-entries in some specific cases.
595 if (!NodesReachableByKernels.test(N->getID()))
596 N->markAsGraphEntry();
597 }
598
599#ifndef NDEBUG
600 assert(verifyGraph());
601#endif
602}
603
604#ifndef NDEBUG
605bool SplitGraph::verifyGraph() const {
606 unsigned ExpectedID = 0;
607 // Exceptionally using a set here in case IDs are messed up.
608 DenseSet<const Node *> SeenNodes;
609 DenseSet<const Function *> SeenFunctionNodes;
610 for (const Node *N : Nodes) {
611 if (N->getID() != (ExpectedID++)) {
612 errs() << "Node IDs are incorrect!\n";
613 return false;
614 }
615
616 if (!SeenNodes.insert(N).second) {
617 errs() << "Node seen more than once!\n";
618 return false;
619 }
620
621 if (&getNode(N->getID()) != N) {
622 errs() << "getNode doesn't return the right node\n";
623 return false;
624 }
625
626 for (const Edge *E : N->IncomingEdges) {
627 if (!E->Src || !E->Dst || (E->Dst != N) ||
628 (find(E->Src->OutgoingEdges, E) == E->Src->OutgoingEdges.end())) {
629 errs() << "ill-formed incoming edges\n";
630 return false;
631 }
632 }
633
634 for (const Edge *E : N->OutgoingEdges) {
635 if (!E->Src || !E->Dst || (E->Src != N) ||
636 (find(E->Dst->IncomingEdges, E) == E->Dst->IncomingEdges.end())) {
637 errs() << "ill-formed outgoing edges\n";
638 return false;
639 }
640 }
641
642 const Function &Fn = N->getFunction();
643 if (AMDGPU::isEntryFunctionCC(Fn.getCallingConv())) {
644 if (N->hasAnyIncomingEdges()) {
645 errs() << "Kernels cannot have incoming edges\n";
646 return false;
647 }
648 }
649
650 if (Fn.isDeclaration()) {
651 errs() << "declarations shouldn't have nodes!\n";
652 return false;
653 }
654
655 auto [It, Inserted] = SeenFunctionNodes.insert(&Fn);
656 if (!Inserted) {
657 errs() << "one function has multiple nodes!\n";
658 return false;
659 }
660 }
661
662 if (ExpectedID != Nodes.size()) {
663 errs() << "Node IDs out of sync!\n";
664 return false;
665 }
666
667 if (createNodesBitVector().size() != getNumNodes()) {
668 errs() << "nodes bit vector doesn't have the right size!\n";
669 return false;
670 }
671
672 // Check we respect the promise of Node::isKernel
673 BitVector BV = createNodesBitVector();
674 for (const Node *N : nodes()) {
675 if (N->isGraphEntryPoint())
676 N->getDependencies(BV);
677 }
678
679 // Ensure each function in the module has an associated node.
680 for (const auto &Fn : M) {
681 if (!Fn.isDeclaration()) {
682 if (!SeenFunctionNodes.contains(&Fn)) {
683 errs() << "Fn has no associated node in the graph!\n";
684 return false;
685 }
686 }
687 }
688
689 if (!BV.all()) {
690 errs() << "not all nodes are reachable through the graph's entry points!\n";
691 return false;
692 }
693
694 return true;
695}
696#endif
697
698CostType SplitGraph::calculateCost(const BitVector &BV) const {
699 CostType Cost = 0;
700 for (unsigned NodeID : BV.set_bits())
701 Cost += getNode(NodeID).getIndividualCost();
702 return Cost;
703}
704
705SplitGraph::Node &
706SplitGraph::getNode(DenseMap<const GlobalValue *, Node *> &Cache,
707 const GlobalValue &GV) {
708 auto &N = Cache[&GV];
709 if (N)
710 return *N;
711
712 CostType Cost = 0;
713 bool NonCopyable = false;
714 if (const Function *Fn = dyn_cast<Function>(&GV)) {
715 NonCopyable = isNonCopyable(*Fn);
716 Cost = CostMap.at(Fn);
717 }
718 N = new (NodesPool.Allocate()) Node(Nodes.size(), GV, Cost, NonCopyable);
719 Nodes.push_back(N);
720 assert(&getNode(N->getID()) == N);
721 return *N;
722}
723
724const SplitGraph::Edge &SplitGraph::createEdge(Node &Src, Node &Dst,
725 EdgeKind EK) {
726 const Edge *E = new (EdgesPool.Allocate<Edge>(1)) Edge(&Src, &Dst, EK);
727 Src.OutgoingEdges.push_back(E);
728 Dst.IncomingEdges.push_back(E);
729 return *E;
730}
731
732//===----------------------------------------------------------------------===//
733// Split Proposals
734//===----------------------------------------------------------------------===//
735
736/// Represents a module splitting proposal.
737///
738/// Proposals are made of N BitVectors, one for each partition, where each bit
739/// set indicates that the node is present and should be copied inside that
740/// partition.
741///
742/// Proposals have several metrics attached so they can be compared/sorted,
743/// which the driver to try multiple strategies resultings in multiple proposals
744/// and choose the best one out of them.
745class SplitProposal {
746public:
747 SplitProposal(const SplitGraph &SG, unsigned MaxPartitions) : SG(&SG) {
748 Partitions.resize(MaxPartitions, {0, SG.createNodesBitVector()});
749 }
750
751 void setName(StringRef NewName) { Name = NewName; }
752 StringRef getName() const { return Name; }
753
754 const BitVector &operator[](unsigned PID) const {
755 return Partitions[PID].second;
756 }
757
758 void add(unsigned PID, const BitVector &BV) {
759 Partitions[PID].second |= BV;
760 updateScore(PID);
761 }
762
763 void print(raw_ostream &OS) const;
764 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
765
766 // Find the cheapest partition (lowest cost). In case of ties, always returns
767 // the highest partition number.
768 unsigned findCheapestPartition() const;
769
770 /// Calculate the CodeSize and Bottleneck scores.
771 void calculateScores();
772
773#ifndef NDEBUG
774 void verifyCompleteness() const;
775#endif
776
777 /// Only available after \ref calculateScores is called.
778 ///
779 /// A positive number indicating the % of code duplication that this proposal
780 /// creates. e.g. 0.2 means this proposal adds roughly 20% code size by
781 /// duplicating some functions across partitions.
782 ///
783 /// Value is always rounded up to 3 decimal places.
784 ///
785 /// A perfect score would be 0.0, and anything approaching 1.0 is very bad.
786 double getCodeSizeScore() const { return CodeSizeScore; }
787
788 /// Only available after \ref calculateScores is called.
789 ///
790 /// A number between [0, 1] which indicates how big of a bottleneck is
791 /// expected from the largest partition.
792 ///
793 /// A score of 1.0 means the biggest partition is as big as the source module,
794 /// so build time will be equal to or greater than the build time of the
795 /// initial input.
796 ///
797 /// Value is always rounded up to 3 decimal places.
798 ///
799 /// This is one of the metrics used to estimate this proposal's build time.
800 double getBottleneckScore() const { return BottleneckScore; }
801
802private:
803 void updateScore(unsigned PID) {
804 assert(SG);
805 for (auto &[PCost, Nodes] : Partitions) {
806 TotalCost -= PCost;
807 PCost = SG->calculateCost(Nodes);
808 TotalCost += PCost;
809 }
810 }
811
812 /// \see getCodeSizeScore
813 double CodeSizeScore = 0.0;
814 /// \see getBottleneckScore
815 double BottleneckScore = 0.0;
816 /// Aggregated cost of all partitions
817 CostType TotalCost = 0;
818
819 const SplitGraph *SG = nullptr;
820 std::string Name;
821
822 std::vector<std::pair<CostType, BitVector>> Partitions;
823};
824
825void SplitProposal::print(raw_ostream &OS) const {
826 assert(SG);
827
828 OS << "[proposal] " << Name << ", total cost:" << TotalCost
829 << ", code size score:" << format("%0.3f", CodeSizeScore)
830 << ", bottleneck score:" << format("%0.3f", BottleneckScore) << '\n';
831 for (const auto &[PID, Part] : enumerate(Partitions)) {
832 const auto &[Cost, NodeIDs] = Part;
833 OS << " - P" << PID << " nodes:" << NodeIDs.count() << " cost: " << Cost
834 << '|' << formatRatioOf(Cost, SG->getModuleCost()) << "%\n";
835 }
836}
837
838unsigned SplitProposal::findCheapestPartition() const {
839 assert(!Partitions.empty());
840 CostType CurCost = std::numeric_limits<CostType>::max();
841 unsigned CurPID = InvalidPID;
842 for (const auto &[Idx, Part] : enumerate(Partitions)) {
843 if (Part.first <= CurCost) {
844 CurPID = Idx;
845 CurCost = Part.first;
846 }
847 }
848 assert(CurPID != InvalidPID);
849 return CurPID;
850}
851
852void SplitProposal::calculateScores() {
853 if (Partitions.empty())
854 return;
855
856 assert(SG);
857 CostType LargestPCost = 0;
858 for (auto &[PCost, Nodes] : Partitions) {
859 if (PCost > LargestPCost)
860 LargestPCost = PCost;
861 }
862
863 CostType ModuleCost = SG->getModuleCost();
864 CodeSizeScore = double(TotalCost) / ModuleCost;
865 assert(CodeSizeScore >= 0.0);
866
867 BottleneckScore = double(LargestPCost) / ModuleCost;
868
869 CodeSizeScore = std::ceil(CodeSizeScore * 100.0) / 100.0;
870 BottleneckScore = std::ceil(BottleneckScore * 100.0) / 100.0;
871}
872
873#ifndef NDEBUG
874void SplitProposal::verifyCompleteness() const {
875 if (Partitions.empty())
876 return;
877
878 BitVector Result = Partitions[0].second;
879 for (const auto &P : drop_begin(Partitions))
880 Result |= P.second;
881 assert(Result.all() && "some nodes are missing from this proposal!");
882}
883#endif
884
885//===-- RecursiveSearchStrategy -------------------------------------------===//
886
887/// Partitioning algorithm.
888///
889/// This is a recursive search algorithm that can explore multiple possiblities.
890///
891/// When a cluster of nodes can go into more than one partition, and we haven't
892/// reached maximum search depth, we recurse and explore both options and their
893/// consequences. Both branches will yield a proposal, and the driver will grade
894/// both and choose the best one.
895///
896/// If max depth is reached, we will use some heuristics to make a choice. Most
897/// of the time we will just use the least-pressured (cheapest) partition, but
898/// if a cluster is particularly big and there is a good amount of overlap with
899/// an existing partition, we will choose that partition instead.
900class RecursiveSearchSplitting {
901public:
902 using SubmitProposalFn = function_ref<void(SplitProposal)>;
903
904 RecursiveSearchSplitting(const SplitGraph &SG, unsigned NumParts,
905 SubmitProposalFn SubmitProposal);
906
907 void run();
908
909private:
910 struct WorkListEntry {
911 WorkListEntry(const BitVector &BV) : Cluster(BV) {}
912
913 unsigned NumNonEntryNodes = 0;
914 CostType TotalCost = 0;
915 CostType CostExcludingGraphEntryPoints = 0;
916 BitVector Cluster;
917 };
918
919 /// Collects all graph entry points's clusters and sort them so the most
920 /// expensive clusters are viewed first. This will merge clusters together if
921 /// they share a non-copyable dependency.
922 void setupWorkList();
923
924 /// Recursive function that assigns the worklist item at \p Idx into a
925 /// partition of \p SP.
926 ///
927 /// \p Depth is the current search depth. When this value is equal to
928 /// \ref MaxDepth, we can no longer recurse.
929 ///
930 /// This function only recurses if there is more than one possible assignment,
931 /// otherwise it is iterative to avoid creating a call stack that is as big as
932 /// \ref WorkList.
933 void pickPartition(unsigned Depth, unsigned Idx, SplitProposal SP);
934
935 /// \return A pair: first element is the PID of the partition that has the
936 /// most similarities with \p Entry, or \ref InvalidPID if no partition was
937 /// found with at least one element in common. The second element is the
938 /// aggregated cost of all dependencies in common between \p Entry and that
939 /// partition.
940 std::pair<unsigned, CostType>
941 findMostSimilarPartition(const WorkListEntry &Entry, const SplitProposal &SP);
942
943 const SplitGraph &SG;
944 unsigned NumParts;
945 SubmitProposalFn SubmitProposal;
946
947 // A Cluster is considered large when its cost, excluding entry points,
948 // exceeds this value.
949 CostType LargeClusterThreshold = 0;
950 unsigned NumProposalsSubmitted = 0;
951 SmallVector<WorkListEntry> WorkList;
952};
953
954RecursiveSearchSplitting::RecursiveSearchSplitting(
955 const SplitGraph &SG, unsigned NumParts, SubmitProposalFn SubmitProposal)
956 : SG(SG), NumParts(NumParts), SubmitProposal(SubmitProposal) {
957 // arbitrary max value as a safeguard. Anything above 10 will already be
958 // slow, this is just a max value to prevent extreme resource exhaustion or
959 // unbounded run time.
960 if (MaxDepth > 16)
961 report_fatal_error("[amdgpu-split-module] search depth of " +
962 Twine(MaxDepth) + " is too high!");
963 LargeClusterThreshold =
964 (LargeFnFactor != 0.0)
965 ? CostType(((SG.getModuleCost() / NumParts) * LargeFnFactor))
966 : std::numeric_limits<CostType>::max();
967 LLVM_DEBUG(dbgs() << "[recursive search] large cluster threshold set at "
968 << LargeClusterThreshold << "\n");
969}
970
971void RecursiveSearchSplitting::run() {
972 {
973 SplitModuleTimer SMT("recursive_search_prepare", "preparing worklist");
974 setupWorkList();
975 }
976
977 {
978 SplitModuleTimer SMT("recursive_search_pick", "partitioning");
979 SplitProposal SP(SG, NumParts);
980 pickPartition(/*BranchDepth=*/0, /*Idx=*/0, std::move(SP));
981 }
982}
983
984void RecursiveSearchSplitting::setupWorkList() {
985 // e.g. if A and B are two worklist item, and they both call a non copyable
986 // dependency C, this does:
987 // A=C
988 // B=C
989 // => NodeEC will create a single group (A, B, C) and we create a new
990 // WorkList entry for that group.
991
992 EquivalenceClasses<unsigned> NodeEC;
993 for (const SplitGraph::Node *N : SG.nodes()) {
994 if (!N->isGraphEntryPoint())
995 continue;
996
997 NodeEC.insert(N->getID());
998 N->visitAllDependencies([&](const SplitGraph::Node &Dep) {
999 if (&Dep != N && Dep.isNonCopyable())
1000 NodeEC.unionSets(N->getID(), Dep.getID());
1001 });
1002 }
1003
1004 for (const auto &Node : NodeEC) {
1005 if (!Node->isLeader())
1006 continue;
1007
1008 BitVector Cluster = SG.createNodesBitVector();
1009 for (unsigned M : NodeEC.members(*Node)) {
1010 const SplitGraph::Node &N = SG.getNode(M);
1011 if (N.isGraphEntryPoint())
1012 N.getDependencies(Cluster);
1013 }
1014 WorkList.emplace_back(std::move(Cluster));
1015 }
1016
1017 // Calculate costs and other useful information.
1018 for (WorkListEntry &Entry : WorkList) {
1019 for (unsigned NodeID : Entry.Cluster.set_bits()) {
1020 const SplitGraph::Node &N = SG.getNode(NodeID);
1021 const CostType Cost = N.getIndividualCost();
1022
1023 Entry.TotalCost += Cost;
1024 if (!N.isGraphEntryPoint()) {
1025 Entry.CostExcludingGraphEntryPoints += Cost;
1026 ++Entry.NumNonEntryNodes;
1027 }
1028 }
1029 }
1030
1031 stable_sort(WorkList, [](const WorkListEntry &A, const WorkListEntry &B) {
1032 if (A.TotalCost != B.TotalCost)
1033 return A.TotalCost > B.TotalCost;
1034
1035 if (A.CostExcludingGraphEntryPoints != B.CostExcludingGraphEntryPoints)
1036 return A.CostExcludingGraphEntryPoints > B.CostExcludingGraphEntryPoints;
1037
1038 if (A.NumNonEntryNodes != B.NumNonEntryNodes)
1039 return A.NumNonEntryNodes > B.NumNonEntryNodes;
1040
1041 return A.Cluster.count() > B.Cluster.count();
1042 });
1043
1044 LLVM_DEBUG({
1045 dbgs() << "[recursive search] worklist:\n";
1046 for (const auto &[Idx, Entry] : enumerate(WorkList)) {
1047 dbgs() << " - [" << Idx << "]: ";
1048 for (unsigned NodeID : Entry.Cluster.set_bits())
1049 dbgs() << NodeID << " ";
1050 dbgs() << "(total_cost:" << Entry.TotalCost
1051 << ", cost_excl_entries:" << Entry.CostExcludingGraphEntryPoints
1052 << ")\n";
1053 }
1054 });
1055}
1056
1057void RecursiveSearchSplitting::pickPartition(unsigned Depth, unsigned Idx,
1058 SplitProposal SP) {
1059 while (Idx < WorkList.size()) {
1060 // Step 1: Determine candidate PIDs.
1061 //
1062 const WorkListEntry &Entry = WorkList[Idx];
1063 const BitVector &Cluster = Entry.Cluster;
1064
1065 // Default option is to do load-balancing, AKA assign to least pressured
1066 // partition.
1067 const unsigned CheapestPID = SP.findCheapestPartition();
1068 assert(CheapestPID != InvalidPID);
1069
1070 // Explore assigning to the kernel that contains the most dependencies in
1071 // common.
1072 const auto [MostSimilarPID, SimilarDepsCost] =
1073 findMostSimilarPartition(Entry, SP);
1074
1075 // We can chose to explore only one path if we only have one valid path, or
1076 // if we reached maximum search depth and can no longer branch out.
1077 unsigned SinglePIDToTry = InvalidPID;
1078 if (MostSimilarPID == InvalidPID) // no similar PID found
1079 SinglePIDToTry = CheapestPID;
1080 else if (MostSimilarPID == CheapestPID) // both landed on the same PID
1081 SinglePIDToTry = CheapestPID;
1082 else if (Depth >= MaxDepth) {
1083 // We have to choose one path. Use a heuristic to guess which one will be
1084 // more appropriate.
1085 if (Entry.CostExcludingGraphEntryPoints > LargeClusterThreshold) {
1086 // Check if the amount of code in common makes it worth it.
1087 assert(SimilarDepsCost && Entry.CostExcludingGraphEntryPoints);
1088 const double Ratio = static_cast<double>(SimilarDepsCost) /
1089 Entry.CostExcludingGraphEntryPoints;
1090 assert(Ratio >= 0.0 && Ratio <= 1.0);
1091 if (Ratio > LargeFnOverlapForMerge) {
1092 // For debug, just print "L", so we'll see "L3=P3" for instance, which
1093 // will mean we reached max depth and chose P3 based on this
1094 // heuristic.
1095 LLVM_DEBUG(dbgs() << 'L');
1096 SinglePIDToTry = MostSimilarPID;
1097 }
1098 } else
1099 SinglePIDToTry = CheapestPID;
1100 }
1101
1102 // Step 2: Explore candidates.
1103
1104 // When we only explore one possible path, and thus branch depth doesn't
1105 // increase, do not recurse, iterate instead.
1106 if (SinglePIDToTry != InvalidPID) {
1107 LLVM_DEBUG(dbgs() << Idx << "=P" << SinglePIDToTry << ' ');
1108 // Only one path to explore, don't clone SP, don't increase depth.
1109 SP.add(SinglePIDToTry, Cluster);
1110 ++Idx;
1111 continue;
1112 }
1113
1114 assert(MostSimilarPID != InvalidPID);
1115
1116 // We explore multiple paths: recurse at increased depth, then stop this
1117 // function.
1118
1119 LLVM_DEBUG(dbgs() << '\n');
1120
1121 // lb = load balancing = put in cheapest partition
1122 {
1123 SplitProposal BranchSP = SP;
1124 LLVM_DEBUG(dbgs().indent(Depth)
1125 << " [lb] " << Idx << "=P" << CheapestPID << "? ");
1126 BranchSP.add(CheapestPID, Cluster);
1127 pickPartition(Depth + 1, Idx + 1, std::move(BranchSP));
1128 }
1129
1130 // ms = most similar = put in partition with the most in common
1131 {
1132 SplitProposal BranchSP = SP;
1133 LLVM_DEBUG(dbgs().indent(Depth)
1134 << " [ms] " << Idx << "=P" << MostSimilarPID << "? ");
1135 BranchSP.add(MostSimilarPID, Cluster);
1136 pickPartition(Depth + 1, Idx + 1, std::move(BranchSP));
1137 }
1138
1139 return;
1140 }
1141
1142 // Step 3: If we assigned all WorkList items, submit the proposal.
1143
1144 assert(Idx == WorkList.size());
1145 assert(NumProposalsSubmitted <= (2u << MaxDepth) &&
1146 "Search got out of bounds?");
1147 SP.setName("recursive_search (depth=" + std::to_string(Depth) + ") #" +
1148 std::to_string(NumProposalsSubmitted++));
1149 LLVM_DEBUG(dbgs() << '\n');
1150 SubmitProposal(std::move(SP));
1151}
1152
1153std::pair<unsigned, CostType>
1154RecursiveSearchSplitting::findMostSimilarPartition(const WorkListEntry &Entry,
1155 const SplitProposal &SP) {
1156 if (!Entry.NumNonEntryNodes)
1157 return {InvalidPID, 0};
1158
1159 // We take the partition that is the most similar using Cost as a metric.
1160 // So we take the set of nodes in common, compute their aggregated cost, and
1161 // pick the partition with the highest cost in common.
1162 unsigned ChosenPID = InvalidPID;
1163 CostType ChosenCost = 0;
1164 for (unsigned PID = 0; PID < NumParts; ++PID) {
1165 BitVector BV = SP[PID];
1166 BV &= Entry.Cluster; // FIXME: & doesn't work between BVs?!
1167
1168 if (BV.none())
1169 continue;
1170
1171 const CostType Cost = SG.calculateCost(BV);
1172
1173 if (ChosenPID == InvalidPID || ChosenCost < Cost ||
1174 (ChosenCost == Cost && PID > ChosenPID)) {
1175 ChosenPID = PID;
1176 ChosenCost = Cost;
1177 }
1178 }
1179
1180 return {ChosenPID, ChosenCost};
1181}
1182
1183//===----------------------------------------------------------------------===//
1184// DOTGraph Printing Support
1185//===----------------------------------------------------------------------===//
1186
1187const SplitGraph::Node *mapEdgeToDst(const SplitGraph::Edge *E) {
1188 return E->Dst;
1189}
1190
1191using SplitGraphEdgeDstIterator =
1192 mapped_iterator<SplitGraph::edges_iterator, decltype(&mapEdgeToDst)>;
1193
1194} // namespace
1195
1196template <> struct GraphTraits<SplitGraph> {
1197 using NodeRef = const SplitGraph::Node *;
1198 using nodes_iterator = SplitGraph::nodes_iterator;
1199 using ChildIteratorType = SplitGraphEdgeDstIterator;
1200
1201 using EdgeRef = const SplitGraph::Edge *;
1202 using ChildEdgeIteratorType = SplitGraph::edges_iterator;
1203
1204 static NodeRef getEntryNode(NodeRef N) { return N; }
1205
1207 return {Ref->outgoing_edges().begin(), mapEdgeToDst};
1208 }
1210 return {Ref->outgoing_edges().end(), mapEdgeToDst};
1211 }
1212
1213 static nodes_iterator nodes_begin(const SplitGraph &G) {
1214 return G.nodes().begin();
1215 }
1216 static nodes_iterator nodes_end(const SplitGraph &G) {
1217 return G.nodes().end();
1218 }
1219};
1220
1221template <> struct DOTGraphTraits<SplitGraph> : public DefaultDOTGraphTraits {
1222 DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {}
1223
1224 static std::string getGraphName(const SplitGraph &SG) {
1225 return SG.getModule().getName().str();
1226 }
1227
1228 std::string getNodeLabel(const SplitGraph::Node *N, const SplitGraph &SG) {
1229 return N->getName().str();
1230 }
1231
1232 static std::string getNodeDescription(const SplitGraph::Node *N,
1233 const SplitGraph &SG) {
1234 std::string Result;
1235 if (N->isEntryFunctionCC())
1236 Result += "entry-fn-cc ";
1237 if (N->isNonCopyable())
1238 Result += "non-copyable ";
1239 Result += "cost:" + std::to_string(N->getIndividualCost());
1240 return Result;
1241 }
1242
1243 static std::string getNodeAttributes(const SplitGraph::Node *N,
1244 const SplitGraph &SG) {
1245 return N->hasAnyIncomingEdges() ? "" : "color=\"red\"";
1246 }
1247
1248 static std::string getEdgeAttributes(const SplitGraph::Node *N,
1249 SplitGraphEdgeDstIterator EI,
1250 const SplitGraph &SG) {
1251
1252 switch ((*EI.getCurrent())->Kind) {
1253 case SplitGraph::EdgeKind::DirectCall:
1254 return "";
1255 case SplitGraph::EdgeKind::IndirectCall:
1256 return "style=\"dashed\"";
1257 }
1258 llvm_unreachable("Unknown SplitGraph::EdgeKind enum");
1259 }
1260};
1261
1262//===----------------------------------------------------------------------===//
1263// Driver
1264//===----------------------------------------------------------------------===//
1265
1266namespace {
1267
1268// If we didn't externalize GVs, then local GVs need to be conservatively
1269// imported into every module (including their initializers), and then cleaned
1270// up afterwards.
1271static bool needsConservativeImport(const GlobalValue *GV) {
1272 if (const auto *Var = dyn_cast<GlobalVariable>(GV))
1273 return Var->hasLocalLinkage();
1274 if (const auto *GA = dyn_cast<GlobalAlias>(GV))
1275 return GA->hasLocalLinkage();
1276 return false;
1277}
1278
1279/// Prints a summary of the partition \p N, represented by module \p M, to \p
1280/// OS.
1281static void printPartitionSummary(raw_ostream &OS, unsigned N, const Module &M,
1282 unsigned PartCost, unsigned ModuleCost) {
1283 OS << "*** Partition P" << N << " ***\n";
1284
1285 for (const auto &Fn : M) {
1286 if (!Fn.isDeclaration())
1287 OS << " - [function] " << Fn.getName() << "\n";
1288 }
1289
1290 for (const auto &GV : M.globals()) {
1291 if (GV.hasInitializer())
1292 OS << " - [global] " << GV.getName() << "\n";
1293 }
1294
1295 OS << "Partition contains " << formatRatioOf(PartCost, ModuleCost)
1296 << "% of the source\n";
1297}
1298
1299static void evaluateProposal(SplitProposal &Best, SplitProposal New) {
1300 SplitModuleTimer SMT("proposal_evaluation", "proposal ranking algorithm");
1301
1302 LLVM_DEBUG({
1303 New.verifyCompleteness();
1304 if (DebugProposalSearch)
1305 New.print(dbgs());
1306 });
1307
1308 const double CurBScore = Best.getBottleneckScore();
1309 const double CurCSScore = Best.getCodeSizeScore();
1310 const double NewBScore = New.getBottleneckScore();
1311 const double NewCSScore = New.getCodeSizeScore();
1312
1313 // TODO: Improve this
1314 // We can probably lower the precision of the comparison at first
1315 // e.g. if we have
1316 // - (Current): BScore: 0.489 CSCore 1.105
1317 // - (New): BScore: 0.475 CSCore 1.305
1318 // Currently we'd choose the new one because the bottleneck score is
1319 // lower, but the new one duplicates more code. It may be worth it to
1320 // discard the new proposal as the impact on build time is negligible.
1321
1322 // Compare them
1323 bool IsBest = false;
1324 if (NewBScore < CurBScore)
1325 IsBest = true;
1326 else if (NewBScore == CurBScore)
1327 IsBest = (NewCSScore < CurCSScore); // Use code size as tie breaker.
1328
1329 if (IsBest)
1330 Best = std::move(New);
1331
1332 LLVM_DEBUG(if (DebugProposalSearch) {
1333 if (IsBest)
1334 dbgs() << "[search] new best proposal!\n";
1335 else
1336 dbgs() << "[search] discarding - not profitable\n";
1337 });
1338}
1339
1340/// Trivial helper to create an identical copy of \p M.
1341static std::unique_ptr<Module> cloneAll(const Module &M) {
1342 ValueToValueMapTy VMap;
1343 return CloneModule(M, VMap, [&](const GlobalValue *GV) { return true; });
1344}
1345
1346/// Writes \p SG as a DOTGraph to \ref ModuleDotCfgDir if requested.
1347static void writeDOTGraph(const SplitGraph &SG) {
1348 if (ModuleDotCfgOutput.empty())
1349 return;
1350
1351 std::error_code EC;
1352 raw_fd_ostream OS(ModuleDotCfgOutput, EC);
1353 if (EC) {
1354 errs() << "[" DEBUG_TYPE "]: cannot open '" << ModuleDotCfgOutput
1355 << "' - DOTGraph will not be printed\n";
1356 }
1357 WriteGraph(OS, SG, /*ShortName=*/false,
1358 /*Title=*/SG.getModule().getName());
1359}
1360
1361static void splitAMDGPUModule(
1362 GetTTIFn GetTTI, Module &M, unsigned NumParts,
1363 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1364 CallGraph CG(M);
1365
1366 // Externalize functions whose address are taken.
1367 //
1368 // This is needed because partitioning is purely based on calls, but sometimes
1369 // a kernel/function may just look at the address of another local function
1370 // and not do anything (no calls). After partitioning, that local function may
1371 // end up in a different module (so it's just a declaration in the module
1372 // where its address is taken), which emits a "undefined hidden symbol" linker
1373 // error.
1374 //
1375 // Additionally, it guides partitioning to not duplicate this function if it's
1376 // called directly at some point.
1377 //
1378 // TODO: Could we be smarter about this ? This makes all functions whose
1379 // addresses are taken non-copyable. We should probably model this type of
1380 // constraint in the graph and use it to guide splitting, instead of
1381 // externalizing like this. Maybe non-copyable should really mean "keep one
1382 // visible copy, then internalize all other copies" for some functions?
1383 if (!NoExternalizeOnAddrTaken) {
1384 for (auto &Fn : M) {
1385 if (Fn.hasLocalLinkage() && Fn.hasAddressTaken()) {
1386 LLVM_DEBUG(dbgs() << "[externalize] "; Fn.printAsOperand(dbgs());
1387 dbgs() << " because its address is taken\n");
1389 }
1390 }
1391 }
1392
1393 // Externalize local GVs, which avoids duplicating their initializers, which
1394 // in turns helps keep code size in check.
1395 if (!NoExternalizeGlobals) {
1396 for (auto &GV : M.globals()) {
1397 if (GV.hasLocalLinkage())
1398 LLVM_DEBUG(dbgs() << "[externalize] GV " << GV.getName() << '\n');
1400 }
1401 }
1402
1403 for (auto &GA : M.aliases()) {
1404 if (GA.hasLocalLinkage()) {
1405 LLVM_DEBUG(dbgs() << "[externalize] alias " << GA.getName() << '\n');
1407 }
1408 }
1409
1410 // Start by calculating the cost of every function in the module, as well as
1411 // the module's overall cost.
1412 FunctionsCostMap FnCosts;
1413 const CostType ModuleCost = calculateFunctionCosts(GetTTI, M, FnCosts);
1414
1415 // Build the SplitGraph, which represents the module's functions and models
1416 // their dependencies accurately.
1417 SplitGraph SG(M, FnCosts, ModuleCost);
1418 SG.buildGraph(CG);
1419
1420 if (SG.empty()) {
1421 LLVM_DEBUG(
1422 dbgs()
1423 << "[!] no nodes in graph, input is empty - no splitting possible\n");
1424 ModuleCallback(cloneAll(M));
1425 return;
1426 }
1427
1428 LLVM_DEBUG({
1429 dbgs() << "[graph] nodes:\n";
1430 for (const SplitGraph::Node *N : SG.nodes()) {
1431 dbgs() << " - [" << N->getID() << "]: " << N->getName() << " "
1432 << (N->isGraphEntryPoint() ? "(entry)" : "") << " "
1433 << (N->isNonCopyable() ? "(noncopyable)" : "") << "\n";
1434 }
1435 });
1436
1437 writeDOTGraph(SG);
1438
1439 LLVM_DEBUG(dbgs() << "[search] testing splitting strategies\n");
1440
1441 std::optional<SplitProposal> Proposal;
1442 const auto EvaluateProposal = [&](SplitProposal SP) {
1443 SP.calculateScores();
1444 if (!Proposal)
1445 Proposal = std::move(SP);
1446 else
1447 evaluateProposal(*Proposal, std::move(SP));
1448 };
1449
1450 // TODO: It would be very easy to create new strategies by just adding a base
1451 // class to RecursiveSearchSplitting and abstracting it away.
1452 RecursiveSearchSplitting(SG, NumParts, EvaluateProposal).run();
1453 LLVM_DEBUG(if (Proposal) dbgs() << "[search done] selected proposal: "
1454 << Proposal->getName() << "\n";);
1455
1456 if (!Proposal) {
1457 LLVM_DEBUG(dbgs() << "[!] no proposal made, no splitting possible!\n");
1458 ModuleCallback(cloneAll(M));
1459 return;
1460 }
1461
1462 LLVM_DEBUG(Proposal->print(dbgs()););
1463
1464 std::optional<raw_fd_ostream> SummariesOS;
1465 if (!PartitionSummariesOutput.empty()) {
1466 std::error_code EC;
1467 SummariesOS.emplace(PartitionSummariesOutput, EC);
1468 if (EC)
1469 errs() << "[" DEBUG_TYPE "]: cannot open '" << PartitionSummariesOutput
1470 << "' - Partition summaries will not be printed\n";
1471 }
1472
1473 // One module will import all GlobalValues that are not Functions
1474 // and are not subject to conservative import.
1475 bool ImportAllGVs = true;
1476
1477 for (unsigned PID = 0; PID < NumParts; ++PID) {
1478 SplitModuleTimer SMT2("modules_creation",
1479 "creating modules for each partition");
1480 LLVM_DEBUG(dbgs() << "[split] creating new modules\n");
1481
1482 DenseSet<const Function *> FnsInPart;
1483 for (unsigned NodeID : (*Proposal)[PID].set_bits())
1484 FnsInPart.insert(&SG.getNode(NodeID).getFunction());
1485
1486 // Don't create empty modules.
1487 if (FnsInPart.empty()) {
1488 LLVM_DEBUG(dbgs() << "[split] P" << PID
1489 << " is empty, not creating module\n");
1490 continue;
1491 }
1492
1493 ValueToValueMapTy VMap;
1494 CostType PartCost = 0;
1495 std::unique_ptr<Module> MPart(
1496 CloneModule(M, VMap, [&](const GlobalValue *GV) {
1497 // Functions go in their assigned partition.
1498 if (const auto *Fn = dyn_cast<Function>(GV)) {
1499 if (FnsInPart.contains(Fn)) {
1500 PartCost += SG.getCost(*Fn);
1501 return true;
1502 }
1503 return false;
1504 }
1505
1506 // Aliases should not be separated from their underlying object.
1507 if (const auto *GA = dyn_cast<GlobalAlias>(GV)) {
1508 if (const auto *Fn = dyn_cast<Function>(GA->getAliaseeObject()))
1509 return FnsInPart.contains(Fn);
1510 }
1511
1512 // Everything else goes in the first non-empty module we create.
1513 return ImportAllGVs || needsConservativeImport(GV);
1514 }));
1515
1516 ImportAllGVs = false;
1517
1518 // Clean-up conservatively imported GVs without any users.
1519 for (auto &GV : make_early_inc_range(MPart->global_values())) {
1520 if (needsConservativeImport(&GV) && GV.use_empty())
1521 GV.eraseFromParent();
1522 }
1523
1524 if (SummariesOS)
1525 printPartitionSummary(*SummariesOS, PID, *MPart, PartCost, ModuleCost);
1526
1527 LLVM_DEBUG(
1528 printPartitionSummary(dbgs(), PID, *MPart, PartCost, ModuleCost));
1529
1530 ModuleCallback(std::move(MPart));
1531 }
1532}
1533} // namespace
1534
1537 SplitModuleTimer SMT(
1538 "total", "total pass runtime (incl. potentially waiting for lockfile)");
1539
1541 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1542 const auto TTIGetter = [&FAM](Function &F) -> const TargetTransformInfo & {
1543 return FAM.getResult<TargetIRAnalysis>(F);
1544 };
1545
1546 bool Done = false;
1547#ifndef NDEBUG
1548 if (UseLockFile) {
1549 SmallString<128> LockFilePath;
1550 sys::path::system_temp_directory(/*ErasedOnReboot=*/true, LockFilePath);
1551 sys::path::append(LockFilePath, "amdgpu-split-module-debug");
1552 LLVM_DEBUG(dbgs() << DEBUG_TYPE " using lockfile '" << LockFilePath
1553 << "'\n");
1554
1555 while (true) {
1556 llvm::LockFileManager Lock(LockFilePath.str());
1557 bool Owned;
1558 if (Error Err = Lock.tryLock().moveInto(Owned)) {
1559 consumeError(std::move(Err));
1560 LLVM_DEBUG(
1561 dbgs() << "[amdgpu-split-module] unable to acquire lockfile, debug "
1562 "output may be mangled by other processes\n");
1563 } else if (!Owned) {
1564 switch (Lock.waitForUnlockFor(std::chrono::seconds(90))) {
1566 break;
1568 continue; // try again to get the lock.
1570 LLVM_DEBUG(
1571 dbgs()
1572 << "[amdgpu-split-module] unable to acquire lockfile, debug "
1573 "output may be mangled by other processes\n");
1574 Lock.unsafeUnlock();
1575 break; // give up
1576 }
1577 }
1578
1579 splitAMDGPUModule(TTIGetter, M, N, ModuleCallback);
1580 Done = true;
1581 break;
1582 }
1583 }
1584#endif
1585
1586 if (!Done)
1587 splitAMDGPUModule(TTIGetter, M, N, ModuleCallback);
1588
1589 // We can change linkage/visibilities in the input, consider that nothing is
1590 // preserved just to be safe. This pass runs last anyway.
1591 return PreservedAnalyses::none();
1592}
1593} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
function_ref< const TargetTransformInfo *(Function &)> GetTTIFn
Unify divergent function exit nodes
This file defines the BumpPtrAllocator interface.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
static InstructionCost getCost(Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
Definition CostModel.cpp:73
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
#define DEBUG_TYPE
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
#define P(N)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This header defines classes/functions to handle pass execution timing information with interfaces for...
static StringRef getName(Value *V)
std::pair< BasicBlock *, BasicBlock * > Edge
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const BasicSubtargetSubTypeKV * find(StringRef S, ArrayRef< BasicSubtargetSubTypeKV > A)
Find KV in array using binary search.
This pass exposes codegen information to IR-level passes.
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static InstructionCost getMax()
Class that manages the creation of a lock file to aid implicit coordination between different process...
std::error_code unsafeUnlock() override
Remove the lock file.
WaitForUnlockResult waitForUnlockFor(std::chrono::seconds MaxSeconds) override
For a shared lock, wait until the owner releases the lock.
Expected< bool > tryLock() override
Tries to acquire the lock without blocking.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_CodeSize
Instruction code size.
@ TCC_Expensive
The cost of a 'div' instruction on x86.
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
template class LLVM_TEMPLATE_ABI opt< bool >
template class LLVM_TEMPLATE_ABI opt< unsigned >
initializer< Ty > init(const Ty &Val)
template class LLVM_TEMPLATE_ABI opt< std::string >
LLVM_ABI void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
Op::Description Desc
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void externalizeGlobal(GlobalValue &GV)
If GV has local linkage, promote it to external + hidden visibility so it can be referenced across mo...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
@ Success
The lock was released successfully.
@ OwnerDied
Owner died while holding the lock.
@ Timeout
Reached timeout while waiting for the owner to release the lock.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
TargetTransformInfo TTI
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
LLVM_ABI std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define N
static std::string getEdgeAttributes(const SplitGraph::Node *N, SplitGraphEdgeDstIterator EI, const SplitGraph &SG)
static std::string getGraphName(const SplitGraph &SG)
static std::string getNodeAttributes(const SplitGraph::Node *N, const SplitGraph &SG)
static std::string getNodeDescription(const SplitGraph::Node *N, const SplitGraph &SG)
std::string getNodeLabel(const SplitGraph::Node *N, const SplitGraph &SG)
DefaultDOTGraphTraits(bool simple=false)
static NodeRef getEntryNode(NodeRef N)
SplitGraph::nodes_iterator nodes_iterator
SplitGraph::edges_iterator ChildEdgeIteratorType
SplitGraphEdgeDstIterator ChildIteratorType
static nodes_iterator nodes_end(const SplitGraph &G)
static ChildIteratorType child_begin(NodeRef Ref)
static nodes_iterator nodes_begin(const SplitGraph &G)
static ChildIteratorType child_end(NodeRef Ref)