68#define DEBUG_TYPE "amdgpu-split-module"
73struct SplitModuleTimer : NamedRegionTimer {
74 SplitModuleTimer(StringRef Name, StringRef
Desc)
75 : NamedRegionTimer(Name,
Desc,
DEBUG_TYPE,
"AMDGPU Module Splitting",
84using FunctionsCostMap = DenseMap<const Function *, CostType>;
86static constexpr unsigned InvalidPID = -1;
91static auto formatRatioOf(CostType Num, CostType Dem) {
92 CostType DemOr1 = Dem ? Dem : 1;
93 return format(
"%0.2f", (
static_cast<double>(Num) / DemOr1) * 100);
104static bool isNonCopyable(
const Function &
F) {
105 return F.hasExternalLinkage() || !
F.isDefinitionExact() ||
116 FunctionsCostMap &CostMap) {
117 SplitModuleTimer SMT(
"calculateFunctionCosts",
"cost analysis");
119 LLVM_DEBUG(
dbgs() <<
"[cost analysis] calculating function costs\n");
120 CostType ModuleCost = 0;
121 [[maybe_unused]] CostType KernelCost = 0;
124 if (Fn.isDeclaration())
128 const auto &
TTI = GetTTI(Fn);
129 for (
const auto &BB : Fn) {
130 for (
const auto &
I : BB) {
135 CostType CostVal = Cost.isValid()
138 assert((FnCost + CostVal) >= FnCost &&
"Overflow!");
145 CostMap[&Fn] = FnCost;
146 assert((ModuleCost + FnCost) >= ModuleCost &&
"Overflow!");
147 ModuleCost += FnCost;
150 KernelCost += FnCost;
158 const CostType FnCost = ModuleCost - KernelCost;
159 dbgs() <<
" - total module cost is " << ModuleCost <<
". kernels cost "
160 <<
"" << KernelCost <<
" ("
161 <<
format(
"%0.2f", (
float(KernelCost) / ModuleCost) * 100)
162 <<
"% of the module), functions cost " << FnCost <<
" ("
163 <<
format(
"%0.2f", (
float(FnCost) / ModuleCost) * 100)
164 <<
"% of the module)\n";
171static bool canBeIndirectlyCalled(
const Function &
F) {
174 return !
F.hasLocalLinkage() ||
175 F.hasAddressTaken(
nullptr,
203 enum class EdgeKind :
uint8_t {
222 : Src(Src), Dst(Dst), Kind(Kind) {}
229 using EdgesVec = SmallVector<const Edge *, 0>;
231 using nodes_iterator =
const Node *
const *;
233 SplitGraph(
const Module &M,
const FunctionsCostMap &CostMap,
235 : M(M), CostMap(CostMap), ModuleCost(ModuleCost) {}
237 void buildGraph(CallGraph &CG);
240 bool verifyGraph()
const;
243 bool empty()
const {
return Nodes.empty(); }
245 const Node &
getNode(
unsigned ID)
const {
return *Nodes[ID]; }
247 unsigned getNumNodes()
const {
return Nodes.size(); }
248 BitVector createNodesBitVector()
const {
return BitVector(Nodes.size()); }
250 const Module &getModule()
const {
return M; }
252 CostType getModuleCost()
const {
return ModuleCost; }
257 CostType calculateCost(
const BitVector &BV)
const;
262 Node &
getNode(DenseMap<const GlobalValue *, Node *> &Cache,
263 const GlobalValue &GV);
266 const Edge &createEdge(
Node &Src,
Node &Dst, EdgeKind EK);
269 const FunctionsCostMap &CostMap;
275 SpecificBumpPtrAllocator<Node> NodesPool;
281 std::is_trivially_destructible_v<Edge>,
282 "Edge must be trivially destructible to use the BumpPtrAllocator");
298class SplitGraph::Node {
299 friend class SplitGraph;
302 Node(
unsigned ID,
const GlobalValue &GV, CostType IndividualCost,
304 : ID(ID), GV(GV), IndividualCost(IndividualCost),
305 IsNonCopyable(IsNonCopyable), IsEntryFnCC(
false), IsGraphEntry(
false) {
312 unsigned getID()
const {
return ID; }
318 CostType getIndividualCost()
const {
return IndividualCost; }
320 bool isNonCopyable()
const {
return IsNonCopyable; }
321 bool isEntryFunctionCC()
const {
return IsEntryFnCC; }
327 bool isGraphEntryPoint()
const {
return IsGraphEntry; }
329 StringRef
getName()
const {
return GV.getName(); }
331 bool hasAnyIncomingEdges()
const {
return IncomingEdges.size(); }
332 bool hasAnyIncomingEdgesOfKind(EdgeKind EK)
const {
333 return any_of(IncomingEdges, [&](
const auto *
E) {
return E->Kind == EK; });
337 return OutgoingEdges;
340 bool shouldFollowIndirectCalls()
const {
return isEntryFunctionCC(); }
347 void visitAllDependencies(std::function<
void(
const Node &)> Visitor)
const;
356 void getDependencies(BitVector &BV)
const {
357 visitAllDependencies([&](
const Node &
N) { BV.set(
N.getID()); });
361 void markAsGraphEntry() { IsGraphEntry =
true; }
364 const GlobalValue &GV;
365 CostType IndividualCost;
366 bool IsNonCopyable : 1;
367 bool IsEntryFnCC : 1;
368 bool IsGraphEntry : 1;
372 EdgesVec IncomingEdges;
373 EdgesVec OutgoingEdges;
376void SplitGraph::Node::visitAllDependencies(
377 std::function<
void(
const Node &)> Visitor)
const {
378 const bool FollowIndirect = shouldFollowIndirectCalls();
381 DenseSet<const Node *> Seen;
382 SmallVector<const Node *, 8> WorkList({
this});
383 while (!WorkList.empty()) {
384 const Node *CurN = WorkList.pop_back_val();
385 if (
auto [It, Inserted] = Seen.insert(CurN); !Inserted)
390 for (
const Edge *
E : CurN->outgoing_edges()) {
391 if (!FollowIndirect &&
E->Kind == EdgeKind::IndirectCall)
393 WorkList.push_back(
E->Dst);
405static bool handleCalleesMD(
const Instruction &
I,
406 SetVector<Function *> &Callees) {
407 auto *MD =
I.getMetadata(LLVMContext::MD_callees);
411 for (
const auto &Op : MD->operands()) {
412 Function *Callee = mdconst::extract_or_null<Function>(Op);
415 Callees.insert(Callee);
421void SplitGraph::buildGraph(CallGraph &CG) {
422 SplitModuleTimer SMT(
"buildGraph",
"graph construction");
425 <<
"[build graph] constructing graph representation of the input\n");
433 DenseMap<const GlobalValue *, Node *> Cache;
434 SmallVector<const Function *> FnsWithIndirectCalls, IndirectlyCallableFns;
435 for (
const Function &Fn : M) {
436 if (Fn.isDeclaration())
440 SetVector<const Function *> DirectCallees;
441 bool CallsExternal =
false;
442 for (
auto &CGEntry : *CG[&Fn]) {
443 auto *CGNode = CGEntry.second;
444 if (
auto *Callee = CGNode->getFunction()) {
445 if (!Callee->isDeclaration())
446 DirectCallees.insert(Callee);
447 }
else if (CGNode == CG.getCallsExternalNode())
448 CallsExternal =
true;
454 LLVM_DEBUG(dbgs() <<
" [!] callgraph is incomplete for ";
455 Fn.printAsOperand(dbgs());
456 dbgs() <<
" - analyzing function\n");
458 SetVector<Function *> KnownCallees;
459 bool HasUnknownIndirectCall =
false;
463 if (!CB || CB->getCalledFunction())
468 if (CB->isInlineAsm()) {
469 LLVM_DEBUG(dbgs() <<
" found inline assembly\n");
473 if (handleCalleesMD(Inst, KnownCallees))
477 KnownCallees.clear();
481 HasUnknownIndirectCall =
true;
485 if (HasUnknownIndirectCall) {
486 LLVM_DEBUG(dbgs() <<
" indirect call found\n");
487 FnsWithIndirectCalls.push_back(&Fn);
488 }
else if (!KnownCallees.empty())
489 DirectCallees.insert_range(KnownCallees);
493 for (
const auto *Callee : DirectCallees)
494 createEdge(
N,
getNode(Cache, *Callee), EdgeKind::DirectCall);
496 if (canBeIndirectlyCalled(Fn))
497 IndirectlyCallableFns.push_back(&Fn);
501 for (
const Function *Fn : FnsWithIndirectCalls) {
502 for (
const Function *Candidate : IndirectlyCallableFns) {
505 createEdge(Src, Dst, EdgeKind::IndirectCall);
510 SmallVector<Node *, 16> CandidateEntryPoints;
511 BitVector NodesReachableByKernels = createNodesBitVector();
512 for (
Node *
N : Nodes) {
514 if (
N->isEntryFunctionCC()) {
515 N->markAsGraphEntry();
516 N->getDependencies(NodesReachableByKernels);
517 }
else if (!
N->hasAnyIncomingEdgesOfKind(EdgeKind::DirectCall))
518 CandidateEntryPoints.push_back(
N);
521 BitVector ReachableNodes = NodesReachableByKernels;
522 for (
Node *
N : CandidateEntryPoints) {
528 if (!NodesReachableByKernels.test(
N->getID())) {
529 N->markAsGraphEntry();
530 N->getDependencies(ReachableNodes);
540 SmallVector<Node *> PostOrder;
541 BitVector Visited = ReachableNodes;
542 SmallVector<std::pair<Node *, edges_iterator>> Stack;
543 for (
Node *Root : Nodes) {
544 if (Visited.test(Root->getID()))
546 Visited.set(Root->getID());
547 Stack.emplace_back(Root, Root->outgoing_edges().begin());
548 while (!Stack.empty()) {
549 auto &[
N, It] = Stack.back();
550 if (It ==
N->outgoing_edges().end()) {
551 PostOrder.push_back(
N);
555 const Edge *
E = *It++;
556 if (
E->Kind != EdgeKind::DirectCall || Visited.test(
E->Dst->getID()))
558 Visited.set(
E->Dst->getID());
559 Stack.emplace_back(
E->Dst,
E->Dst->outgoing_edges().begin());
563 for (
Node *
N : reverse(PostOrder)) {
564 if (ReachableNodes.test(
N->getID()))
566 N->markAsGraphEntry();
567 N->getDependencies(ReachableNodes);
576bool SplitGraph::verifyGraph()
const {
577 unsigned ExpectedID = 0;
579 DenseSet<const Node *> SeenNodes;
580 DenseSet<const Function *> SeenFunctionNodes;
581 for (
const Node *
N : Nodes) {
582 if (
N->getID() != (ExpectedID++)) {
583 errs() <<
"Node IDs are incorrect!\n";
587 if (!SeenNodes.insert(
N).second) {
588 errs() <<
"Node seen more than once!\n";
593 errs() <<
"getNode doesn't return the right node\n";
597 for (
const Edge *
E :
N->IncomingEdges) {
598 if (!
E->Src || !
E->Dst || (
E->Dst !=
N) ||
599 (
find(
E->Src->OutgoingEdges,
E) ==
E->Src->OutgoingEdges.end())) {
600 errs() <<
"ill-formed incoming edges\n";
605 for (
const Edge *
E :
N->OutgoingEdges) {
606 if (!
E->Src || !
E->Dst || (
E->Src !=
N) ||
607 (
find(
E->Dst->IncomingEdges,
E) ==
E->Dst->IncomingEdges.end())) {
608 errs() <<
"ill-formed outgoing edges\n";
613 const Function &Fn =
N->getFunction();
614 if (AMDGPU::isEntryFunctionCC(Fn.getCallingConv())) {
615 if (
N->hasAnyIncomingEdges()) {
616 errs() <<
"Kernels cannot have incoming edges\n";
621 if (Fn.isDeclaration()) {
622 errs() <<
"declarations shouldn't have nodes!\n";
626 auto [It, Inserted] = SeenFunctionNodes.insert(&Fn);
628 errs() <<
"one function has multiple nodes!\n";
633 if (ExpectedID != Nodes.size()) {
634 errs() <<
"Node IDs out of sync!\n";
638 if (createNodesBitVector().size() != getNumNodes()) {
639 errs() <<
"nodes bit vector doesn't have the right size!\n";
644 BitVector BV = createNodesBitVector();
646 if (
N->isGraphEntryPoint())
647 N->getDependencies(BV);
651 for (
const auto &Fn : M) {
652 if (!Fn.isDeclaration()) {
653 if (!SeenFunctionNodes.contains(&Fn)) {
654 errs() <<
"Fn has no associated node in the graph!\n";
661 errs() <<
"not all nodes are reachable through the graph's entry points!\n";
669CostType SplitGraph::calculateCost(
const BitVector &BV)
const {
671 for (
unsigned NodeID : BV.set_bits())
672 Cost +=
getNode(NodeID).getIndividualCost();
677SplitGraph::getNode(DenseMap<const GlobalValue *, Node *> &Cache,
678 const GlobalValue &GV) {
679 auto &
N = Cache[&GV];
684 bool NonCopyable =
false;
686 NonCopyable = isNonCopyable(*Fn);
687 Cost = CostMap.at(Fn);
689 N =
new (NodesPool.Allocate())
Node(Nodes.size(), GV, Cost, NonCopyable);
695const SplitGraph::Edge &SplitGraph::createEdge(
Node &Src,
Node &Dst,
697 const Edge *
E =
new (EdgesPool.Allocate<Edge>(1))
Edge(&Src, &Dst, EK);
698 Src.OutgoingEdges.push_back(
E);
699 Dst.IncomingEdges.push_back(
E);
718 SplitProposal(
const SplitGraph &SG,
unsigned MaxPartitions) : SG(&SG) {
719 Partitions.resize(MaxPartitions, {0, SG.createNodesBitVector()});
722 void setName(StringRef NewName) { Name = NewName; }
723 StringRef
getName()
const {
return Name; }
725 const BitVector &operator[](
unsigned PID)
const {
726 return Partitions[PID].second;
729 void add(
unsigned PID,
const BitVector &BV) {
730 Partitions[PID].second |= BV;
734 void print(raw_ostream &OS)
const;
739 unsigned findCheapestPartition()
const;
742 void calculateScores();
745 void verifyCompleteness()
const;
757 double getCodeSizeScore()
const {
return CodeSizeScore; }
771 double getBottleneckScore()
const {
return BottleneckScore; }
774 void updateScore(
unsigned PID) {
776 for (
auto &[PCost, Nodes] : Partitions) {
778 PCost = SG->calculateCost(Nodes);
784 double CodeSizeScore = 0.0;
786 double BottleneckScore = 0.0;
788 CostType TotalCost = 0;
790 const SplitGraph *SG =
nullptr;
793 std::vector<std::pair<CostType, BitVector>> Partitions;
796void SplitProposal::print(raw_ostream &OS)
const {
799 OS <<
"[proposal] " << Name <<
", total cost:" << TotalCost
800 <<
", code size score:" << format(
"%0.3f", CodeSizeScore)
801 <<
", bottleneck score:" << format(
"%0.3f", BottleneckScore) <<
'\n';
802 for (
const auto &[PID, Part] : enumerate(Partitions)) {
803 const auto &[Cost, NodeIDs] = Part;
804 OS <<
" - P" << PID <<
" nodes:" << NodeIDs.count() <<
" cost: " << Cost
805 <<
'|' << formatRatioOf(Cost, SG->getModuleCost()) <<
"%\n";
809unsigned SplitProposal::findCheapestPartition()
const {
810 assert(!Partitions.empty());
811 CostType CurCost = std::numeric_limits<CostType>::max();
812 unsigned CurPID = InvalidPID;
813 for (
const auto &[Idx, Part] : enumerate(Partitions)) {
814 if (Part.first <= CurCost) {
816 CurCost = Part.first;
819 assert(CurPID != InvalidPID);
823void SplitProposal::calculateScores() {
824 if (Partitions.empty())
828 CostType LargestPCost = 0;
829 for (
auto &[PCost, Nodes] : Partitions) {
830 if (PCost > LargestPCost)
831 LargestPCost = PCost;
834 CostType ModuleCost = SG->getModuleCost();
835 CodeSizeScore = double(TotalCost) / ModuleCost;
836 assert(CodeSizeScore >= 0.0);
838 BottleneckScore = double(LargestPCost) / ModuleCost;
840 CodeSizeScore = std::ceil(CodeSizeScore * 100.0) / 100.0;
841 BottleneckScore = std::ceil(BottleneckScore * 100.0) / 100.0;
845void SplitProposal::verifyCompleteness()
const {
846 if (Partitions.empty())
849 BitVector Result = Partitions[0].second;
850 for (
const auto &
P : drop_begin(Partitions))
852 assert(Result.all() &&
"some nodes are missing from this proposal!");
871class RecursiveSearchSplitting {
873 using SubmitProposalFn = function_ref<void(SplitProposal)>;
875 RecursiveSearchSplitting(
const AMDGPUOptions &CLOpts,
const SplitGraph &SG,
876 unsigned NumParts, SubmitProposalFn SubmitProposal);
881 struct WorkListEntry {
882 WorkListEntry(
const BitVector &BV) : Cluster(BV) {}
884 unsigned NumNonEntryNodes = 0;
885 CostType TotalCost = 0;
886 CostType CostExcludingGraphEntryPoints = 0;
893 void setupWorkList();
904 void pickPartition(
unsigned Depth,
unsigned Idx, SplitProposal SP);
911 std::pair<unsigned, CostType>
912 findMostSimilarPartition(
const WorkListEntry &Entry,
const SplitProposal &SP);
914 const AMDGPUOptions &CLOpts;
915 const SplitGraph &SG;
917 SubmitProposalFn SubmitProposal;
921 CostType LargeClusterThreshold = 0;
922 unsigned NumProposalsSubmitted = 0;
923 SmallVector<WorkListEntry> WorkList;
926RecursiveSearchSplitting::RecursiveSearchSplitting(
927 const AMDGPUOptions &CLOpts,
const SplitGraph &SG,
unsigned NumParts,
928 SubmitProposalFn SubmitProposal)
930 SubmitProposal(SubmitProposal) {
934 if (CLOpts.module_splitting_max_depth > 16)
935 report_fatal_error(
"[amdgpu-split-module] search depth of " +
936 Twine(CLOpts.module_splitting_max_depth) +
938 float LargeFnFactor = CLOpts.module_splitting_large_threshold;
939 LargeClusterThreshold =
940 (LargeFnFactor != 0.0)
941 ? CostType(((SG.getModuleCost() /
NumParts) * LargeFnFactor))
942 : std::numeric_limits<CostType>::max();
943 LLVM_DEBUG(dbgs() <<
"[recursive search] large cluster threshold set at "
944 << LargeClusterThreshold <<
"\n");
947void RecursiveSearchSplitting::run() {
949 SplitModuleTimer SMT(
"recursive_search_prepare",
"preparing worklist");
954 SplitModuleTimer SMT(
"recursive_search_pick",
"partitioning");
956 pickPartition(0, 0, std::move(SP));
960void RecursiveSearchSplitting::setupWorkList() {
968 EquivalenceClasses<unsigned> NodeEC;
969 for (
const SplitGraph::Node *
N : SG.nodes()) {
970 if (!
N->isGraphEntryPoint())
973 NodeEC.insert(
N->getID());
974 N->visitAllDependencies([&](
const SplitGraph::Node &Dep) {
975 if (&Dep !=
N && Dep.isNonCopyable())
976 NodeEC.unionSets(
N->getID(), Dep.getID());
980 for (
const auto &
Node : NodeEC) {
981 if (!
Node->isLeader())
984 BitVector Cluster = SG.createNodesBitVector();
985 for (
unsigned M : NodeEC.members(*
Node)) {
986 const SplitGraph::Node &
N = SG.getNode(M);
987 if (
N.isGraphEntryPoint())
988 N.getDependencies(Cluster);
990 WorkList.emplace_back(std::move(Cluster));
994 for (WorkListEntry &Entry : WorkList) {
995 for (
unsigned NodeID : Entry.Cluster.set_bits()) {
996 const SplitGraph::Node &
N = SG.getNode(NodeID);
997 const CostType Cost =
N.getIndividualCost();
999 Entry.TotalCost += Cost;
1000 if (!
N.isGraphEntryPoint()) {
1001 Entry.CostExcludingGraphEntryPoints += Cost;
1002 ++Entry.NumNonEntryNodes;
1007 stable_sort(WorkList, [](
const WorkListEntry &
A,
const WorkListEntry &
B) {
1008 if (
A.TotalCost !=
B.TotalCost)
1009 return A.TotalCost >
B.TotalCost;
1011 if (
A.CostExcludingGraphEntryPoints !=
B.CostExcludingGraphEntryPoints)
1012 return A.CostExcludingGraphEntryPoints >
B.CostExcludingGraphEntryPoints;
1014 if (
A.NumNonEntryNodes !=
B.NumNonEntryNodes)
1015 return A.NumNonEntryNodes >
B.NumNonEntryNodes;
1017 return A.Cluster.count() >
B.Cluster.count();
1021 dbgs() <<
"[recursive search] worklist:\n";
1022 for (
const auto &[Idx, Entry] : enumerate(WorkList)) {
1023 dbgs() <<
" - [" << Idx <<
"]: ";
1024 for (
unsigned NodeID : Entry.Cluster.set_bits())
1025 dbgs() << NodeID <<
" ";
1026 dbgs() <<
"(total_cost:" << Entry.TotalCost
1027 <<
", cost_excl_entries:" << Entry.CostExcludingGraphEntryPoints
1033void RecursiveSearchSplitting::pickPartition(
unsigned Depth,
unsigned Idx,
1035 while (Idx < WorkList.size()) {
1038 const WorkListEntry &Entry = WorkList[Idx];
1039 const BitVector &Cluster = Entry.Cluster;
1043 const unsigned CheapestPID = SP.findCheapestPartition();
1044 assert(CheapestPID != InvalidPID);
1048 const auto [MostSimilarPID, SimilarDepsCost] =
1049 findMostSimilarPartition(Entry, SP);
1053 unsigned SinglePIDToTry = InvalidPID;
1054 if (MostSimilarPID == InvalidPID)
1055 SinglePIDToTry = CheapestPID;
1056 else if (MostSimilarPID == CheapestPID)
1057 SinglePIDToTry = CheapestPID;
1058 else if (Depth >= CLOpts.module_splitting_max_depth) {
1061 if (Entry.CostExcludingGraphEntryPoints > LargeClusterThreshold) {
1063 assert(SimilarDepsCost && Entry.CostExcludingGraphEntryPoints);
1064 const double Ratio =
static_cast<double>(SimilarDepsCost) /
1065 Entry.CostExcludingGraphEntryPoints;
1066 assert(Ratio >= 0.0 && Ratio <= 1.0);
1067 if (Ratio > CLOpts.module_splitting_merge_threshold) {
1072 SinglePIDToTry = MostSimilarPID;
1075 SinglePIDToTry = CheapestPID;
1082 if (SinglePIDToTry != InvalidPID) {
1083 LLVM_DEBUG(dbgs() << Idx <<
"=P" << SinglePIDToTry <<
' ');
1085 SP.add(SinglePIDToTry, Cluster);
1090 assert(MostSimilarPID != InvalidPID);
1099 SplitProposal BranchSP = SP;
1101 <<
" [lb] " << Idx <<
"=P" << CheapestPID <<
"? ");
1102 BranchSP.add(CheapestPID, Cluster);
1103 pickPartition(Depth + 1, Idx + 1, std::move(BranchSP));
1108 SplitProposal BranchSP = SP;
1110 <<
" [ms] " << Idx <<
"=P" << MostSimilarPID <<
"? ");
1111 BranchSP.add(MostSimilarPID, Cluster);
1112 pickPartition(Depth + 1, Idx + 1, std::move(BranchSP));
1120 assert(Idx == WorkList.size());
1121 assert(NumProposalsSubmitted <= (2u << CLOpts.module_splitting_max_depth) &&
1122 "Search got out of bounds?");
1123 SP.setName(
"recursive_search (depth=" + std::to_string(Depth) +
") #" +
1124 std::to_string(NumProposalsSubmitted++));
1126 SubmitProposal(std::move(SP));
1129std::pair<unsigned, CostType>
1130RecursiveSearchSplitting::findMostSimilarPartition(
const WorkListEntry &Entry,
1131 const SplitProposal &SP) {
1132 if (!Entry.NumNonEntryNodes)
1133 return {InvalidPID, 0};
1138 unsigned ChosenPID = InvalidPID;
1139 CostType ChosenCost = 0;
1140 for (
unsigned PID = 0; PID <
NumParts; ++PID) {
1141 BitVector BV = SP[PID];
1142 BV &= Entry.Cluster;
1147 const CostType Cost = SG.calculateCost(BV);
1149 if (ChosenPID == InvalidPID || ChosenCost < Cost ||
1150 (ChosenCost == Cost && PID > ChosenPID)) {
1156 return {ChosenPID, ChosenCost};
1163const SplitGraph::Node *mapEdgeToDst(
const SplitGraph::Edge *
E) {
1167using SplitGraphEdgeDstIterator =
1168 mapped_iterator<SplitGraph::edges_iterator,
decltype(&mapEdgeToDst)>;
1183 return {
Ref->outgoing_edges().begin(), mapEdgeToDst};
1186 return {
Ref->outgoing_edges().end(), mapEdgeToDst};
1190 return G.nodes().begin();
1193 return G.nodes().end();
1201 return SG.getModule().getName().str();
1205 return N->getName().str();
1209 const SplitGraph &SG) {
1211 if (
N->isEntryFunctionCC())
1212 Result +=
"entry-fn-cc ";
1213 if (
N->isNonCopyable())
1214 Result +=
"non-copyable ";
1215 Result +=
"cost:" + std::to_string(
N->getIndividualCost());
1220 const SplitGraph &SG) {
1221 return N->hasAnyIncomingEdges() ?
"" :
"color=\"red\"";
1225 SplitGraphEdgeDstIterator EI,
1226 const SplitGraph &SG) {
1228 switch ((*EI.getCurrent())->Kind) {
1229 case SplitGraph::EdgeKind::DirectCall:
1231 case SplitGraph::EdgeKind::IndirectCall:
1232 return "style=\"dashed\"";
1247static bool needsConservativeImport(
const GlobalValue *GV) {
1249 return Var->hasLocalLinkage();
1251 return GA->hasLocalLinkage();
1257static void printPartitionSummary(raw_ostream &OS,
unsigned N,
const Module &M,
1258 unsigned PartCost,
unsigned ModuleCost) {
1259 OS <<
"*** Partition P" <<
N <<
" ***\n";
1261 for (
const auto &Fn : M) {
1262 if (!Fn.isDeclaration())
1263 OS <<
" - [function] " << Fn.getName() <<
"\n";
1266 for (
const auto &GV :
M.globals()) {
1267 if (GV.hasInitializer())
1268 OS <<
" - [global] " << GV.getName() <<
"\n";
1271 OS <<
"Partition contains " << formatRatioOf(PartCost, ModuleCost)
1272 <<
"% of the source\n";
1275static void evaluateProposal(
const AMDGPUOptions &CLOpts, SplitProposal &Best,
1276 SplitProposal New) {
1277 SplitModuleTimer SMT(
"proposal_evaluation",
"proposal ranking algorithm");
1280 New.verifyCompleteness();
1281 if (CLOpts.module_splitting_debug_proposal_search)
1285 const double CurBScore = Best.getBottleneckScore();
1286 const double CurCSScore = Best.getCodeSizeScore();
1287 const double NewBScore =
New.getBottleneckScore();
1288 const double NewCSScore =
New.getCodeSizeScore();
1300 bool IsBest =
false;
1301 if (NewBScore < CurBScore)
1303 else if (NewBScore == CurBScore)
1304 IsBest = (NewCSScore < CurCSScore);
1307 Best = std::move(New);
1309 LLVM_DEBUG(
if (CLOpts.module_splitting_debug_proposal_search) {
1311 dbgs() <<
"[search] new best proposal!\n";
1313 dbgs() <<
"[search] discarding - not profitable\n";
1318static std::unique_ptr<Module> cloneAll(
const Module &M) {
1320 return CloneModule(M, VMap, [&](
const GlobalValue *GV) {
return true; });
1324static void writeDOTGraph(
const AMDGPUOptions &CLOpts,
const SplitGraph &SG) {
1325 StringRef ModuleDotCfgOutput = CLOpts.module_splitting_print_module_dotcfg;
1326 if (ModuleDotCfgOutput.empty())
1330 raw_fd_ostream OS(ModuleDotCfgOutput, EC);
1332 errs() <<
"[" DEBUG_TYPE "]: cannot open '" << ModuleDotCfgOutput
1333 <<
"' - DOTGraph will not be printed\n";
1336 SG.getModule().getName());
1339static void splitAMDGPUModule(
1341 function_ref<
void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1361 if (CLOpts.module_splitting_externalize_address_taken) {
1362 for (
auto &Fn : M) {
1363 if (Fn.hasLocalLinkage() && Fn.hasAddressTaken()) {
1365 dbgs() <<
" because its address is taken\n");
1373 if (CLOpts.module_splitting_externalize_globals) {
1374 for (
auto &GV :
M.globals()) {
1375 if (GV.hasLocalLinkage())
1376 LLVM_DEBUG(
dbgs() <<
"[externalize] GV " << GV.getName() <<
'\n');
1381 for (
auto &GA :
M.aliases()) {
1382 if (GA.hasLocalLinkage()) {
1383 LLVM_DEBUG(
dbgs() <<
"[externalize] alias " << GA.getName() <<
'\n');
1390 FunctionsCostMap FnCosts;
1391 const CostType ModuleCost = calculateFunctionCosts(GetTTI, M, FnCosts);
1395 SplitGraph SG(M, FnCosts, ModuleCost);
1401 <<
"[!] no nodes in graph, input is empty - no splitting possible\n");
1402 ModuleCallback(cloneAll(M));
1407 dbgs() <<
"[graph] nodes:\n";
1408 for (
const SplitGraph::Node *
N : SG.nodes()) {
1409 dbgs() <<
" - [" <<
N->getID() <<
"]: " <<
N->getName() <<
" "
1410 << (
N->isGraphEntryPoint() ?
"(entry)" :
"") <<
" "
1411 << (
N->isNonCopyable() ?
"(noncopyable)" :
"") <<
"\n";
1415 writeDOTGraph(CLOpts, SG);
1419 std::optional<SplitProposal> Proposal;
1420 const auto EvaluateProposal = [&](SplitProposal
SP) {
1421 SP.calculateScores();
1423 Proposal = std::move(SP);
1425 evaluateProposal(CLOpts, *Proposal, std::move(SP));
1430 RecursiveSearchSplitting(CLOpts, SG,
NumParts, EvaluateProposal).run();
1431 LLVM_DEBUG(
if (Proposal)
dbgs() <<
"[search done] selected proposal: "
1432 << Proposal->getName() <<
"\n";);
1435 LLVM_DEBUG(
dbgs() <<
"[!] no proposal made, no splitting possible!\n");
1436 ModuleCallback(cloneAll(M));
1442 std::optional<raw_fd_ostream> SummariesOS;
1443 StringRef PartitionSummariesOutput =
1444 CLOpts.module_splitting_print_partition_summaries;
1445 if (!PartitionSummariesOutput.empty()) {
1447 SummariesOS.emplace(PartitionSummariesOutput, EC);
1449 errs() <<
"[" DEBUG_TYPE "]: cannot open '" << PartitionSummariesOutput
1450 <<
"' - Partition summaries will not be printed\n";
1455 bool ImportAllGVs =
true;
1457 for (
unsigned PID = 0; PID <
NumParts; ++PID) {
1458 SplitModuleTimer SMT2(
"modules_creation",
1459 "creating modules for each partition");
1462 DenseSet<const Function *> FnsInPart;
1463 for (
unsigned NodeID : (*Proposal)[PID].set_bits())
1464 FnsInPart.insert(&SG.getNode(NodeID).getFunction());
1467 if (FnsInPart.empty()) {
1469 <<
" is empty, not creating module\n");
1474 CostType PartCost = 0;
1475 std::unique_ptr<Module> MPart(
1479 if (FnsInPart.contains(Fn)) {
1480 PartCost += SG.getCost(*Fn);
1489 return FnsInPart.contains(Fn);
1493 return ImportAllGVs || needsConservativeImport(GV);
1496 ImportAllGVs =
false;
1500 if (needsConservativeImport(&GV) && GV.use_empty())
1501 GV.eraseFromParent();
1505 printPartitionSummary(*SummariesOS, PID, *MPart, PartCost, ModuleCost);
1508 printPartitionSummary(
dbgs(), PID, *MPart, PartCost, ModuleCost));
1510 ModuleCallback(std::move(MPart));
1517 SplitModuleTimer SMT(
1518 "total",
"total pass runtime (incl. potentially waiting for lockfile)");
1526 const AMDGPUOptions &CLOpts =
1527 M.getContext().getLibraryOptions().get<AMDGPUOptions>();
1530 if (CLOpts.module_splitting_serial_execution) {
1543 dbgs() <<
"[amdgpu-split-module] unable to acquire lockfile, debug "
1544 "output may be mangled by other processes\n");
1545 }
else if (!Owned) {
1554 <<
"[amdgpu-split-module] unable to acquire lockfile, debug "
1555 "output may be mangled by other processes\n");
1561 splitAMDGPUModule(CLOpts, TTIGetter, M, N, ModuleCallback);
1569 splitAMDGPUModule(CLOpts, TTIGetter, M, N, ModuleCallback);
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.
static InstructionCost getCost(const AnalysisOptions &Opts, Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
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.
Machine Check Debug Module
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 implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
static const BasicSubtargetSubTypeKV * find(StringRef S, ArrayRef< BasicSubtargetSubTypeKV > A)
Find KV in array using binary search.
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.
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.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
StringRef str() const
Explicit conversion to StringRef.
Analysis pass providing the TargetTransformInfo.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
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.
This is an optimization pass for GlobalISel generic memory operations.
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...
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="")
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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.
@ 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.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
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.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
static std::string getEdgeAttributes(const SplitGraph::Node *N, SplitGraphEdgeDstIterator EI, const SplitGraph &SG)
static std::string getGraphName(const SplitGraph &SG)
DOTGraphTraits(bool IsSimple=false)
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)
const SplitGraph::Edge * EdgeRef
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)
const SplitGraph::Node * NodeRef
static ChildIteratorType child_end(NodeRef Ref)