Skip to content

Commit 0487db1

Browse files
authored
MachineScheduler: Improve instruction clustering (#137784)
The existing way of managing clustered nodes was done through adding weak edges between the neighbouring cluster nodes, which is a sort of ordered queue. And this will be later recorded as `NextClusterPred` or `NextClusterSucc` in `ScheduleDAGMI`. But actually the instruction may be picked not in the exact order of the queue. For example, we have a queue of cluster nodes A B C. But during scheduling, node B might be picked first, then it will be very likely that we only cluster B and C for Top-Down scheduling (leaving A alone). Another issue is: ``` if (!ReorderWhileClustering && SUa->NodeNum > SUb->NodeNum) std::swap(SUa, SUb); if (!DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) ``` may break the cluster queue. For example, we want to cluster nodes (order as in `MemOpRecords`): 1 3 2. 1(SUa) will be pred of 3(SUb) normally. But when it comes to (3, 2), As 3(SUa) > 2(SUb), we would reorder the two nodes, which makes 2 be pred of 3. This makes both 1 and 2 become preds of 3, but there is no edge between 1 and 2. Thus we get a broken cluster chain. To fix both issues, we introduce an unordered set in the change. This could help improve clustering in some hard case. One key reason the change causes so many test check changes is: As the cluster candidates are not ordered now, the candidates might be picked in different order from before. The most affected targets are: AMDGPU, AArch64, RISCV. For RISCV, it seems to me most are just minor instruction reorder, don't see obvious regression. For AArch64, there were some combining of ldr into ldp being affected. With two cases being regressed and two being improved. This has more deeper reason that machine scheduler cannot cluster them well both before and after the change, and the load combine algorithm later is also not smart enough. For AMDGPU, some cases have more v_dual instructions used while some are regressed. It seems less critical. Seems like test `v_vselect_v32bf16` gets more buffer_load being claused.
1 parent dba4188 commit 0487db1

File tree

104 files changed

+26015
-25829
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

104 files changed

+26015
-25829
lines changed

llvm/include/llvm/CodeGen/MachineScheduler.h

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -304,10 +304,6 @@ class LLVM_ABI ScheduleDAGMI : public ScheduleDAGInstrs {
304304
/// The bottom of the unscheduled zone.
305305
MachineBasicBlock::iterator CurrentBottom;
306306

307-
/// Record the next node in a scheduled cluster.
308-
const SUnit *NextClusterPred = nullptr;
309-
const SUnit *NextClusterSucc = nullptr;
310-
311307
#if LLVM_ENABLE_ABI_BREAKING_CHECKS
312308
/// The number of instructions scheduled so far. Used to cut off the
313309
/// scheduler at the point determined by misched-cutoff.
@@ -368,10 +364,6 @@ class LLVM_ABI ScheduleDAGMI : public ScheduleDAGInstrs {
368364
/// live ranges and region boundary iterators.
369365
void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos);
370366

371-
const SUnit *getNextClusterPred() const { return NextClusterPred; }
372-
373-
const SUnit *getNextClusterSucc() const { return NextClusterSucc; }
374-
375367
void viewGraph(const Twine &Name, const Twine &Title) override;
376368
void viewGraph() override;
377369

@@ -1295,6 +1287,9 @@ class LLVM_ABI GenericScheduler : public GenericSchedulerBase {
12951287
SchedBoundary Top;
12961288
SchedBoundary Bot;
12971289

1290+
ClusterInfo *TopCluster;
1291+
ClusterInfo *BotCluster;
1292+
12981293
/// Candidate last picked from Top boundary.
12991294
SchedCandidate TopCand;
13001295
/// Candidate last picked from Bot boundary.
@@ -1335,6 +1330,9 @@ class LLVM_ABI PostGenericScheduler : public GenericSchedulerBase {
13351330
/// Candidate last picked from Bot boundary.
13361331
SchedCandidate BotCand;
13371332

1333+
ClusterInfo *TopCluster;
1334+
ClusterInfo *BotCluster;
1335+
13381336
public:
13391337
PostGenericScheduler(const MachineSchedContext *C)
13401338
: GenericSchedulerBase(C), Top(SchedBoundary::TopQID, "TopQ"),

llvm/include/llvm/CodeGen/ScheduleDAG.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
#include "llvm/ADT/BitVector.h"
1919
#include "llvm/ADT/PointerIntPair.h"
20+
#include "llvm/ADT/SmallSet.h"
2021
#include "llvm/ADT/SmallVector.h"
2122
#include "llvm/ADT/iterator.h"
2223
#include "llvm/CodeGen/MachineInstr.h"
@@ -235,6 +236,10 @@ class TargetRegisterInfo;
235236
LLVM_ABI void dump(const TargetRegisterInfo *TRI = nullptr) const;
236237
};
237238

239+
/// Keep record of which SUnit are in the same cluster group.
240+
typedef SmallSet<SUnit *, 8> ClusterInfo;
241+
constexpr unsigned InvalidClusterId = ~0u;
242+
238243
/// Scheduling unit. This is a node in the scheduling DAG.
239244
class SUnit {
240245
private:
@@ -275,6 +280,8 @@ class TargetRegisterInfo;
275280
unsigned TopReadyCycle = 0; ///< Cycle relative to start when node is ready.
276281
unsigned BotReadyCycle = 0; ///< Cycle relative to end when node is ready.
277282

283+
unsigned ParentClusterIdx = InvalidClusterId; ///< The parent cluster id.
284+
278285
private:
279286
unsigned Depth = 0; ///< Node depth.
280287
unsigned Height = 0; ///< Node height.

llvm/include/llvm/CodeGen/ScheduleDAGInstrs.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,8 @@ namespace llvm {
181181
/// case of a huge region that gets reduced).
182182
SUnit *BarrierChain = nullptr;
183183

184+
SmallVector<ClusterInfo> Clusters;
185+
184186
public:
185187
/// A list of SUnits, used in Value2SUsMap, during DAG construction.
186188
/// Note: to gain speed it might be worth investigating an optimized
@@ -384,6 +386,14 @@ namespace llvm {
384386
/// equivalent edge already existed (false indicates failure).
385387
bool addEdge(SUnit *SuccSU, const SDep &PredDep);
386388

389+
/// Returns the array of the clusters.
390+
SmallVector<ClusterInfo> &getClusters() { return Clusters; }
391+
392+
/// Get the specific cluster, return nullptr for InvalidClusterId.
393+
ClusterInfo *getCluster(unsigned Idx) {
394+
return Idx != InvalidClusterId ? &Clusters[Idx] : nullptr;
395+
}
396+
387397
protected:
388398
void initSUnits();
389399
void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx);

llvm/lib/CodeGen/MachineScheduler.cpp

Lines changed: 52 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include "llvm/ADT/ArrayRef.h"
1616
#include "llvm/ADT/BitVector.h"
1717
#include "llvm/ADT/DenseMap.h"
18+
#include "llvm/ADT/EquivalenceClasses.h"
1819
#include "llvm/ADT/PriorityQueue.h"
1920
#include "llvm/ADT/STLExtras.h"
2021
#include "llvm/ADT/SmallVector.h"
@@ -943,8 +944,6 @@ void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
943944

944945
if (SuccEdge->isWeak()) {
945946
--SuccSU->WeakPredsLeft;
946-
if (SuccEdge->isCluster())
947-
NextClusterSucc = SuccSU;
948947
return;
949948
}
950949
#ifndef NDEBUG
@@ -967,12 +966,6 @@ void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
967966

968967
/// releaseSuccessors - Call releaseSucc on each of SU's successors.
969968
void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
970-
// Reset the next successor, For example, we want to cluster A B C.
971-
// After A is picked, we will set B as next cluster succ, but if we pick
972-
// D instead of B after A, then we need to reset the next cluster succ because
973-
// we have decided to not pick the cluster candidate B during pickNode().
974-
// Leaving B as the NextClusterSucc just make things messy.
975-
NextClusterSucc = nullptr;
976969
for (SDep &Succ : SU->Succs)
977970
releaseSucc(SU, &Succ);
978971
}
@@ -986,8 +979,6 @@ void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
986979

987980
if (PredEdge->isWeak()) {
988981
--PredSU->WeakSuccsLeft;
989-
if (PredEdge->isCluster())
990-
NextClusterPred = PredSU;
991982
return;
992983
}
993984
#ifndef NDEBUG
@@ -1010,7 +1001,6 @@ void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
10101001

10111002
/// releasePredecessors - Call releasePred on each of SU's predecessors.
10121003
void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
1013-
NextClusterPred = nullptr;
10141004
for (SDep &Pred : SU->Preds)
10151005
releasePred(SU, &Pred);
10161006
}
@@ -1184,11 +1174,8 @@ findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
11841174
}
11851175

11861176
/// Identify DAG roots and setup scheduler queues.
1187-
void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
1188-
ArrayRef<SUnit*> BotRoots) {
1189-
NextClusterSucc = nullptr;
1190-
NextClusterPred = nullptr;
1191-
1177+
void ScheduleDAGMI::initQueues(ArrayRef<SUnit *> TopRoots,
1178+
ArrayRef<SUnit *> BotRoots) {
11921179
// Release all DAG roots for scheduling, not including EntrySU/ExitSU.
11931180
//
11941181
// Nodes with unreleased weak edges can still be roots.
@@ -2116,6 +2103,7 @@ void BaseMemOpClusterMutation::clusterNeighboringMemOps(
21162103
ScheduleDAGInstrs *DAG) {
21172104
// Keep track of the current cluster length and bytes for each SUnit.
21182105
DenseMap<unsigned, std::pair<unsigned, unsigned>> SUnit2ClusterInfo;
2106+
EquivalenceClasses<SUnit *> Clusters;
21192107

21202108
// At this point, `MemOpRecords` array must hold atleast two mem ops. Try to
21212109
// cluster mem ops collected within `MemOpRecords` array.
@@ -2155,13 +2143,15 @@ void BaseMemOpClusterMutation::clusterNeighboringMemOps(
21552143

21562144
SUnit *SUa = MemOpa.SU;
21572145
SUnit *SUb = MemOpb.SU;
2146+
21582147
if (!ReorderWhileClustering && SUa->NodeNum > SUb->NodeNum)
21592148
std::swap(SUa, SUb);
21602149

21612150
// FIXME: Is this check really required?
21622151
if (!DAG->addEdge(SUb, SDep(SUa, SDep::Cluster)))
21632152
continue;
21642153

2154+
Clusters.unionSets(SUa, SUb);
21652155
LLVM_DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
21662156
<< SUb->NodeNum << ")\n");
21672157
++NumClustered;
@@ -2201,6 +2191,21 @@ void BaseMemOpClusterMutation::clusterNeighboringMemOps(
22012191
<< ", Curr cluster bytes: " << CurrentClusterBytes
22022192
<< "\n");
22032193
}
2194+
2195+
// Add cluster group information.
2196+
// Iterate over all of the equivalence sets.
2197+
auto &AllClusters = DAG->getClusters();
2198+
for (const EquivalenceClasses<SUnit *>::ECValue *I : Clusters) {
2199+
if (!I->isLeader())
2200+
continue;
2201+
ClusterInfo Group;
2202+
unsigned ClusterIdx = AllClusters.size();
2203+
for (SUnit *MemberI : Clusters.members(*I)) {
2204+
MemberI->ParentClusterIdx = ClusterIdx;
2205+
Group.insert(MemberI);
2206+
}
2207+
AllClusters.push_back(Group);
2208+
}
22042209
}
22052210

22062211
void BaseMemOpClusterMutation::collectMemOpRecords(
@@ -3688,6 +3693,9 @@ void GenericScheduler::initialize(ScheduleDAGMI *dag) {
36883693
}
36893694
TopCand.SU = nullptr;
36903695
BotCand.SU = nullptr;
3696+
3697+
TopCluster = nullptr;
3698+
BotCluster = nullptr;
36913699
}
36923700

36933701
/// Initialize the per-region scheduling policy.
@@ -3997,13 +4005,11 @@ bool GenericScheduler::tryCandidate(SchedCandidate &Cand,
39974005
// This is a best effort to set things up for a post-RA pass. Optimizations
39984006
// like generating loads of multiple registers should ideally be done within
39994007
// the scheduler pass by combining the loads during DAG postprocessing.
4000-
const SUnit *CandNextClusterSU =
4001-
Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
4002-
const SUnit *TryCandNextClusterSU =
4003-
TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
4004-
if (tryGreater(TryCand.SU == TryCandNextClusterSU,
4005-
Cand.SU == CandNextClusterSU,
4006-
TryCand, Cand, Cluster))
4008+
const ClusterInfo *CandCluster = Cand.AtTop ? TopCluster : BotCluster;
4009+
const ClusterInfo *TryCandCluster = TryCand.AtTop ? TopCluster : BotCluster;
4010+
if (tryGreater(TryCandCluster && TryCandCluster->contains(TryCand.SU),
4011+
CandCluster && CandCluster->contains(Cand.SU), TryCand, Cand,
4012+
Cluster))
40074013
return TryCand.Reason != NoCand;
40084014

40094015
if (SameBoundary) {
@@ -4262,11 +4268,25 @@ void GenericScheduler::reschedulePhysReg(SUnit *SU, bool isTop) {
42624268
void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
42634269
if (IsTopNode) {
42644270
SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
4271+
TopCluster = DAG->getCluster(SU->ParentClusterIdx);
4272+
LLVM_DEBUG(if (TopCluster) {
4273+
dbgs() << " Top Cluster: ";
4274+
for (auto *N : *TopCluster)
4275+
dbgs() << N->NodeNum << '\t';
4276+
dbgs() << '\n';
4277+
});
42654278
Top.bumpNode(SU);
42664279
if (SU->hasPhysRegUses)
42674280
reschedulePhysReg(SU, true);
42684281
} else {
42694282
SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
4283+
BotCluster = DAG->getCluster(SU->ParentClusterIdx);
4284+
LLVM_DEBUG(if (BotCluster) {
4285+
dbgs() << " Bot Cluster: ";
4286+
for (auto *N : *BotCluster)
4287+
dbgs() << N->NodeNum << '\t';
4288+
dbgs() << '\n';
4289+
});
42704290
Bot.bumpNode(SU);
42714291
if (SU->hasPhysRegDefs)
42724292
reschedulePhysReg(SU, false);
@@ -4303,6 +4323,8 @@ void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
43034323
if (!Bot.HazardRec) {
43044324
Bot.HazardRec = DAG->TII->CreateTargetMIHazardRecognizer(Itin, DAG);
43054325
}
4326+
TopCluster = nullptr;
4327+
BotCluster = nullptr;
43064328
}
43074329

43084330
void PostGenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
@@ -4367,14 +4389,12 @@ bool PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
43674389
return TryCand.Reason != NoCand;
43684390

43694391
// Keep clustered nodes together.
4370-
const SUnit *CandNextClusterSU =
4371-
Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
4372-
const SUnit *TryCandNextClusterSU =
4373-
TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
4374-
if (tryGreater(TryCand.SU == TryCandNextClusterSU,
4375-
Cand.SU == CandNextClusterSU, TryCand, Cand, Cluster))
4392+
const ClusterInfo *CandCluster = Cand.AtTop ? TopCluster : BotCluster;
4393+
const ClusterInfo *TryCandCluster = TryCand.AtTop ? TopCluster : BotCluster;
4394+
if (tryGreater(TryCandCluster && TryCandCluster->contains(TryCand.SU),
4395+
CandCluster && CandCluster->contains(Cand.SU), TryCand, Cand,
4396+
Cluster))
43764397
return TryCand.Reason != NoCand;
4377-
43784398
// Avoid critical resource consumption and balance the schedule.
43794399
if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
43804400
TryCand, Cand, ResourceReduce))
@@ -4571,9 +4591,11 @@ SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
45714591
void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
45724592
if (IsTopNode) {
45734593
SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
4594+
TopCluster = DAG->getCluster(SU->ParentClusterIdx);
45744595
Top.bumpNode(SU);
45754596
} else {
45764597
SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
4598+
BotCluster = DAG->getCluster(SU->ParentClusterIdx);
45774599
Bot.bumpNode(SU);
45784600
}
45794601
}

llvm/lib/CodeGen/MacroFusion.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,11 @@ bool llvm::fuseInstructionPair(ScheduleDAGInstrs &DAG, SUnit &FirstSU,
6161
for (SDep &SI : SecondSU.Preds)
6262
if (SI.isCluster())
6363
return false;
64+
65+
unsigned FirstCluster = FirstSU.ParentClusterIdx;
66+
unsigned SecondCluster = SecondSU.ParentClusterIdx;
67+
assert(FirstCluster == InvalidClusterId && SecondCluster == InvalidClusterId);
68+
6469
// Though the reachability checks above could be made more generic,
6570
// perhaps as part of ScheduleDAGInstrs::addEdge(), since such edges are valid,
6671
// the extra computation cost makes it less interesting in general cases.
@@ -70,6 +75,14 @@ bool llvm::fuseInstructionPair(ScheduleDAGInstrs &DAG, SUnit &FirstSU,
7075
if (!DAG.addEdge(&SecondSU, SDep(&FirstSU, SDep::Cluster)))
7176
return false;
7277

78+
auto &Clusters = DAG.getClusters();
79+
80+
FirstSU.ParentClusterIdx = Clusters.size();
81+
SecondSU.ParentClusterIdx = Clusters.size();
82+
83+
SmallSet<SUnit *, 8> Cluster{{&FirstSU, &SecondSU}};
84+
Clusters.push_back(Cluster);
85+
7386
// TODO - If we want to chain more than two instructions, we need to create
7487
// artifical edges to make dependencies from the FirstSU also dependent
7588
// on other chained instructions, and other chained instructions also

llvm/lib/CodeGen/ScheduleDAG.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,9 @@ LLVM_DUMP_METHOD void ScheduleDAG::dumpNodeName(const SUnit &SU) const {
365365
LLVM_DUMP_METHOD void ScheduleDAG::dumpNodeAll(const SUnit &SU) const {
366366
dumpNode(SU);
367367
SU.dumpAttributes();
368+
if (SU.ParentClusterIdx != InvalidClusterId)
369+
dbgs() << " Parent Cluster Index: " << SU.ParentClusterIdx << '\n';
370+
368371
if (SU.Preds.size() > 0) {
369372
dbgs() << " Predecessors:\n";
370373
for (const SDep &Dep : SU.Preds) {

llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -589,12 +589,11 @@ bool GCNMaxILPSchedStrategy::tryCandidate(SchedCandidate &Cand,
589589
// This is a best effort to set things up for a post-RA pass. Optimizations
590590
// like generating loads of multiple registers should ideally be done within
591591
// the scheduler pass by combining the loads during DAG postprocessing.
592-
const SUnit *CandNextClusterSU =
593-
Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
594-
const SUnit *TryCandNextClusterSU =
595-
TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
596-
if (tryGreater(TryCand.SU == TryCandNextClusterSU,
597-
Cand.SU == CandNextClusterSU, TryCand, Cand, Cluster))
592+
const ClusterInfo *CandCluster = Cand.AtTop ? TopCluster : BotCluster;
593+
const ClusterInfo *TryCandCluster = TryCand.AtTop ? TopCluster : BotCluster;
594+
if (tryGreater(TryCandCluster && TryCandCluster->contains(TryCand.SU),
595+
CandCluster && CandCluster->contains(Cand.SU), TryCand, Cand,
596+
Cluster))
598597
return TryCand.Reason != NoCand;
599598

600599
// Avoid increasing the max critical pressure in the scheduled region.
@@ -664,12 +663,11 @@ bool GCNMaxMemoryClauseSchedStrategy::tryCandidate(SchedCandidate &Cand,
664663

665664
// MaxMemoryClause-specific: We prioritize clustered instructions as we would
666665
// get more benefit from clausing these memory instructions.
667-
const SUnit *CandNextClusterSU =
668-
Cand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
669-
const SUnit *TryCandNextClusterSU =
670-
TryCand.AtTop ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
671-
if (tryGreater(TryCand.SU == TryCandNextClusterSU,
672-
Cand.SU == CandNextClusterSU, TryCand, Cand, Cluster))
666+
const ClusterInfo *CandCluster = Cand.AtTop ? TopCluster : BotCluster;
667+
const ClusterInfo *TryCandCluster = TryCand.AtTop ? TopCluster : BotCluster;
668+
if (tryGreater(TryCandCluster && TryCandCluster->contains(TryCand.SU),
669+
CandCluster && CandCluster->contains(Cand.SU), TryCand, Cand,
670+
Cluster))
673671
return TryCand.Reason != NoCand;
674672

675673
// We only compare a subset of features when comparing nodes between

0 commit comments

Comments
 (0)