1 //===- GCNIterativeScheduler.cpp ------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "GCNIterativeScheduler.h"
11 #include "AMDGPUSubtarget.h"
12 #include "GCNRegPressure.h"
13 #include "GCNSchedStrategy.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/CodeGen/LiveIntervals.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/RegisterPressure.h"
21 #include "llvm/CodeGen/ScheduleDAG.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
30 #include <type_traits>
35 #define DEBUG_TYPE "machine-scheduler"
39 std::vector<const SUnit *> makeMinRegSchedule(ArrayRef<const SUnit *> TopRoots,
40 const ScheduleDAG &DAG);
42 std::vector<const SUnit*> makeGCNILPScheduler(ArrayRef<const SUnit*> BotRoots,
43 const ScheduleDAG &DAG);
46 // shim accessors for different order containers
47 static inline MachineInstr *getMachineInstr(MachineInstr *MI) {
50 static inline MachineInstr *getMachineInstr(const SUnit *SU) {
51 return SU->getInstr();
53 static inline MachineInstr *getMachineInstr(const SUnit &SU) {
57 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
59 static void printRegion(raw_ostream &OS,
60 MachineBasicBlock::iterator Begin,
61 MachineBasicBlock::iterator End,
62 const LiveIntervals *LIS,
64 std::numeric_limits<unsigned>::max()) {
65 auto BB = Begin->getParent();
66 OS << BB->getParent()->getName() << ":" << printMBBReference(*BB) << ' '
67 << BB->getName() << ":\n";
69 MaxInstNum = std::max(MaxInstNum, 1u);
70 for (; I != End && MaxInstNum; ++I, --MaxInstNum) {
71 if (!I->isDebugValue() && LIS)
72 OS << LIS->getInstructionIndex(*I);
78 if (!I->isDebugValue() && LIS)
79 OS << LIS->getInstructionIndex(*I);
82 if (End != BB->end()) { // print boundary inst if present
84 if (LIS) OS << LIS->getInstructionIndex(*End) << '\t';
90 static void printLivenessInfo(raw_ostream &OS,
91 MachineBasicBlock::iterator Begin,
92 MachineBasicBlock::iterator End,
93 const LiveIntervals *LIS) {
94 const auto BB = Begin->getParent();
95 const auto &MRI = BB->getParent()->getRegInfo();
97 const auto LiveIns = getLiveRegsBefore(*Begin, *LIS);
99 getRegPressure(MRI, LiveIns).print(OS);
101 const auto BottomMI = End == BB->end() ? std::prev(End) : End;
102 const auto LiveOuts = getLiveRegsAfter(*BottomMI, *LIS);
104 getRegPressure(MRI, LiveOuts).print(OS);
108 void GCNIterativeScheduler::printRegions(raw_ostream &OS) const {
109 const auto &ST = MF.getSubtarget<SISubtarget>();
110 for (const auto R : Regions) {
111 OS << "Region to schedule ";
112 printRegion(OS, R->Begin, R->End, LIS, 1);
113 printLivenessInfo(OS, R->Begin, R->End, LIS);
115 R->MaxPressure.print(OS, &ST);
120 void GCNIterativeScheduler::printSchedResult(raw_ostream &OS,
122 const GCNRegPressure &RP) const {
123 OS << "\nAfter scheduling ";
124 printRegion(OS, R->Begin, R->End, LIS);
125 printSchedRP(OS, R->MaxPressure, RP);
130 void GCNIterativeScheduler::printSchedRP(raw_ostream &OS,
131 const GCNRegPressure &Before,
132 const GCNRegPressure &After) const {
133 const auto &ST = MF.getSubtarget<SISubtarget>();
135 Before.print(OS, &ST);
137 After.print(OS, &ST);
141 // DAG builder helper
142 class GCNIterativeScheduler::BuildDAG {
143 GCNIterativeScheduler &Sch;
144 SmallVector<SUnit *, 8> TopRoots;
146 SmallVector<SUnit*, 8> BotRoots;
148 BuildDAG(const Region &R, GCNIterativeScheduler &_Sch)
150 auto BB = R.Begin->getParent();
151 Sch.BaseClass::startBlock(BB);
152 Sch.BaseClass::enterRegion(BB, R.Begin, R.End, R.NumRegionInstrs);
154 Sch.buildSchedGraph(Sch.AA, nullptr, nullptr, nullptr,
155 /*TrackLaneMask*/true);
156 Sch.Topo.InitDAGTopologicalSorting();
157 Sch.findRootsAndBiasEdges(TopRoots, BotRoots);
161 Sch.BaseClass::exitRegion();
162 Sch.BaseClass::finishBlock();
165 ArrayRef<const SUnit *> getTopRoots() const {
168 ArrayRef<SUnit*> getBottomRoots() const {
173 class GCNIterativeScheduler::OverrideLegacyStrategy {
174 GCNIterativeScheduler &Sch;
176 std::unique_ptr<MachineSchedStrategy> SaveSchedImpl;
177 GCNRegPressure SaveMaxRP;
180 OverrideLegacyStrategy(Region &R,
181 MachineSchedStrategy &OverrideStrategy,
182 GCNIterativeScheduler &_Sch)
185 , SaveSchedImpl(std::move(_Sch.SchedImpl))
186 , SaveMaxRP(R.MaxPressure) {
187 Sch.SchedImpl.reset(&OverrideStrategy);
188 auto BB = R.Begin->getParent();
189 Sch.BaseClass::startBlock(BB);
190 Sch.BaseClass::enterRegion(BB, R.Begin, R.End, R.NumRegionInstrs);
193 ~OverrideLegacyStrategy() {
194 Sch.BaseClass::exitRegion();
195 Sch.BaseClass::finishBlock();
196 Sch.SchedImpl.release();
197 Sch.SchedImpl = std::move(SaveSchedImpl);
201 assert(Sch.RegionBegin == Rgn.Begin && Sch.RegionEnd == Rgn.End);
202 DEBUG(dbgs() << "\nScheduling ";
203 printRegion(dbgs(), Rgn.Begin, Rgn.End, Sch.LIS, 2));
204 Sch.BaseClass::schedule();
206 // Unfortunatelly placeDebugValues incorrectly modifies RegionEnd, restore
207 Sch.RegionEnd = Rgn.End;
208 //assert(Rgn.End == Sch.RegionEnd);
209 Rgn.Begin = Sch.RegionBegin;
210 Rgn.MaxPressure.clear();
213 void restoreOrder() {
214 assert(Sch.RegionBegin == Rgn.Begin && Sch.RegionEnd == Rgn.End);
215 // DAG SUnits are stored using original region's order
216 // so just use SUnits as the restoring schedule
217 Sch.scheduleRegion(Rgn, Sch.SUnits, SaveMaxRP);
223 // just a stub to make base class happy
224 class SchedStrategyStub : public MachineSchedStrategy {
226 bool shouldTrackPressure() const override { return false; }
227 bool shouldTrackLaneMasks() const override { return false; }
228 void initialize(ScheduleDAGMI *DAG) override {}
229 SUnit *pickNode(bool &IsTopNode) override { return nullptr; }
230 void schedNode(SUnit *SU, bool IsTopNode) override {}
231 void releaseTopNode(SUnit *SU) override {}
232 void releaseBottomNode(SUnit *SU) override {}
235 } // end anonymous namespace
237 GCNIterativeScheduler::GCNIterativeScheduler(MachineSchedContext *C,
239 : BaseClass(C, llvm::make_unique<SchedStrategyStub>())
245 // returns max pressure for a region
247 GCNIterativeScheduler::getRegionPressure(MachineBasicBlock::iterator Begin,
248 MachineBasicBlock::iterator End)
250 // For the purpose of pressure tracking bottom inst of the region should
251 // be also processed. End is either BB end, BB terminator inst or sched
253 auto const BBEnd = Begin->getParent()->end();
254 auto const BottomMI = End == BBEnd ? std::prev(End) : End;
256 // scheduleRegions walks bottom to top, so its likely we just get next
257 // instruction to track
258 auto AfterBottomMI = std::next(BottomMI);
259 if (AfterBottomMI == BBEnd ||
260 &*AfterBottomMI != UPTracker.getLastTrackedMI()) {
261 UPTracker.reset(*BottomMI);
263 assert(UPTracker.isValid());
266 for (auto I = BottomMI; I != Begin; --I)
267 UPTracker.recede(*I);
269 UPTracker.recede(*Begin);
271 assert(UPTracker.isValid() ||
272 (dbgs() << "Tracked region ",
273 printRegion(dbgs(), Begin, End, LIS), false));
274 return UPTracker.moveMaxPressure();
277 // returns max pressure for a tentative schedule
278 template <typename Range> GCNRegPressure
279 GCNIterativeScheduler::getSchedulePressure(const Region &R,
280 Range &&Schedule) const {
281 auto const BBEnd = R.Begin->getParent()->end();
282 GCNUpwardRPTracker RPTracker(*LIS);
283 if (R.End != BBEnd) {
284 // R.End points to the boundary instruction but the
285 // schedule doesn't include it
286 RPTracker.reset(*R.End);
287 RPTracker.recede(*R.End);
289 // R.End doesn't point to the boundary instruction
290 RPTracker.reset(*std::prev(BBEnd));
292 for (auto I = Schedule.end(), B = Schedule.begin(); I != B;) {
293 RPTracker.recede(*getMachineInstr(*--I));
295 return RPTracker.moveMaxPressure();
298 void GCNIterativeScheduler::enterRegion(MachineBasicBlock *BB, // overriden
299 MachineBasicBlock::iterator Begin,
300 MachineBasicBlock::iterator End,
301 unsigned NumRegionInstrs) {
302 BaseClass::enterRegion(BB, Begin, End, NumRegionInstrs);
303 if (NumRegionInstrs > 2) {
305 new (Alloc.Allocate())
306 Region { Begin, End, NumRegionInstrs,
307 getRegionPressure(Begin, End), nullptr });
311 void GCNIterativeScheduler::schedule() { // overriden
314 printLivenessInfo(dbgs(), RegionBegin, RegionEnd, LIS);
315 if (!Regions.empty() && Regions.back()->Begin == RegionBegin) {
316 dbgs() << "Max RP: ";
317 Regions.back()->MaxPressure.print(dbgs(), &MF.getSubtarget<SISubtarget>());
323 void GCNIterativeScheduler::finalizeSchedule() { // overriden
327 case SCHEDULE_MINREGONLY: scheduleMinReg(); break;
328 case SCHEDULE_MINREGFORCED: scheduleMinReg(true); break;
329 case SCHEDULE_LEGACYMAXOCCUPANCY: scheduleLegacyMaxOccupancy(); break;
330 case SCHEDULE_ILP: scheduleILP(false); break;
334 // Detach schedule from SUnits and interleave it with debug values.
335 // Returned schedule becomes independent of DAG state.
336 std::vector<MachineInstr*>
337 GCNIterativeScheduler::detachSchedule(ScheduleRef Schedule) const {
338 std::vector<MachineInstr*> Res;
339 Res.reserve(Schedule.size() * 2);
342 Res.push_back(FirstDbgValue);
344 const auto DbgB = DbgValues.begin(), DbgE = DbgValues.end();
345 for (auto SU : Schedule) {
346 Res.push_back(SU->getInstr());
347 const auto &D = std::find_if(DbgB, DbgE, [SU](decltype(*DbgB) &P) {
348 return P.second == SU->getInstr();
351 Res.push_back(D->first);
356 void GCNIterativeScheduler::setBestSchedule(Region &R,
357 ScheduleRef Schedule,
358 const GCNRegPressure &MaxRP) {
359 R.BestSchedule.reset(
360 new TentativeSchedule{ detachSchedule(Schedule), MaxRP });
363 void GCNIterativeScheduler::scheduleBest(Region &R) {
364 assert(R.BestSchedule.get() && "No schedule specified");
365 scheduleRegion(R, R.BestSchedule->Schedule, R.BestSchedule->MaxPressure);
366 R.BestSchedule.reset();
369 // minimal required region scheduler, works for ranges of SUnits*,
370 // SUnits or MachineIntrs*
371 template <typename Range>
372 void GCNIterativeScheduler::scheduleRegion(Region &R, Range &&Schedule,
373 const GCNRegPressure &MaxRP) {
374 assert(RegionBegin == R.Begin && RegionEnd == R.End);
375 assert(LIS != nullptr);
377 const auto SchedMaxRP = getSchedulePressure(R, Schedule);
379 auto BB = R.Begin->getParent();
381 for (const auto &I : Schedule) {
382 auto MI = getMachineInstr(I);
386 if (!MI->isDebugValue())
387 LIS->handleMove(*MI, true);
389 if (!MI->isDebugValue()) {
390 // Reset read - undef flags and update them later.
391 for (auto &Op : MI->operands())
392 if (Op.isReg() && Op.isDef())
393 Op.setIsUndef(false);
395 RegisterOperands RegOpers;
396 RegOpers.collect(*MI, *TRI, MRI, /*ShouldTrackLaneMasks*/true,
397 /*IgnoreDead*/false);
398 // Adjust liveness and add missing dead+read-undef flags.
399 auto SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
400 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
402 Top = std::next(MI->getIterator());
404 RegionBegin = getMachineInstr(Schedule.front());
406 // Schedule consisting of MachineInstr* is considered 'detached'
407 // and already interleaved with debug values
408 if (!std::is_same<decltype(*Schedule.begin()), MachineInstr*>::value) {
410 // Unfortunatelly placeDebugValues incorrectly modifies RegionEnd, restore
411 //assert(R.End == RegionEnd);
415 R.Begin = RegionBegin;
416 R.MaxPressure = MaxRP;
419 const auto RegionMaxRP = getRegionPressure(R);
420 const auto &ST = MF.getSubtarget<SISubtarget>();
422 assert((SchedMaxRP == RegionMaxRP && (MaxRP.empty() || SchedMaxRP == MaxRP))
423 || (dbgs() << "Max RP mismatch!!!\n"
424 "RP for schedule (calculated): ",
425 SchedMaxRP.print(dbgs(), &ST),
426 dbgs() << "RP for schedule (reported): ",
427 MaxRP.print(dbgs(), &ST),
428 dbgs() << "RP after scheduling: ",
429 RegionMaxRP.print(dbgs(), &ST),
433 // Sort recorded regions by pressure - highest at the front
434 void GCNIterativeScheduler::sortRegionsByPressure(unsigned TargetOcc) {
435 const auto &ST = MF.getSubtarget<SISubtarget>();
436 std::sort(Regions.begin(), Regions.end(),
437 [&ST, TargetOcc](const Region *R1, const Region *R2) {
438 return R2->MaxPressure.less(ST, R1->MaxPressure, TargetOcc);
442 ///////////////////////////////////////////////////////////////////////////////
443 // Legacy MaxOccupancy Strategy
445 // Tries to increase occupancy applying minreg scheduler for a sequence of
446 // most demanding regions. Obtained schedules are saved as BestSchedule for a
448 // TargetOcc is the best achievable occupancy for a kernel.
449 // Returns better occupancy on success or current occupancy on fail.
450 // BestSchedules aren't deleted on fail.
451 unsigned GCNIterativeScheduler::tryMaximizeOccupancy(unsigned TargetOcc) {
452 // TODO: assert Regions are sorted descending by pressure
453 const auto &ST = MF.getSubtarget<SISubtarget>();
454 const auto Occ = Regions.front()->MaxPressure.getOccupancy(ST);
455 DEBUG(dbgs() << "Trying to to improve occupancy, target = " << TargetOcc
456 << ", current = " << Occ << '\n');
458 auto NewOcc = TargetOcc;
459 for (auto R : Regions) {
460 if (R->MaxPressure.getOccupancy(ST) >= NewOcc)
463 DEBUG(printRegion(dbgs(), R->Begin, R->End, LIS, 3);
464 printLivenessInfo(dbgs(), R->Begin, R->End, LIS));
466 BuildDAG DAG(*R, *this);
467 const auto MinSchedule = makeMinRegSchedule(DAG.getTopRoots(), *this);
468 const auto MaxRP = getSchedulePressure(*R, MinSchedule);
469 DEBUG(dbgs() << "Occupancy improvement attempt:\n";
470 printSchedRP(dbgs(), R->MaxPressure, MaxRP));
472 NewOcc = std::min(NewOcc, MaxRP.getOccupancy(ST));
476 setBestSchedule(*R, MinSchedule, MaxRP);
478 DEBUG(dbgs() << "New occupancy = " << NewOcc
479 << ", prev occupancy = " << Occ << '\n');
480 return std::max(NewOcc, Occ);
483 void GCNIterativeScheduler::scheduleLegacyMaxOccupancy(
484 bool TryMaximizeOccupancy) {
485 const auto &ST = MF.getSubtarget<SISubtarget>();
486 auto TgtOcc = ST.getOccupancyWithLocalMemSize(MF);
488 sortRegionsByPressure(TgtOcc);
489 auto Occ = Regions.front()->MaxPressure.getOccupancy(ST);
491 if (TryMaximizeOccupancy && Occ < TgtOcc)
492 Occ = tryMaximizeOccupancy(TgtOcc);
494 // This is really weird but for some magic scheduling regions twice
495 // gives performance improvement
496 const int NumPasses = Occ < TgtOcc ? 2 : 1;
498 TgtOcc = std::min(Occ, TgtOcc);
499 DEBUG(dbgs() << "Scheduling using default scheduler, "
500 "target occupancy = " << TgtOcc << '\n');
501 GCNMaxOccupancySchedStrategy LStrgy(Context);
503 for (int I = 0; I < NumPasses; ++I) {
504 // running first pass with TargetOccupancy = 0 mimics previous scheduling
505 // approach and is a performance magic
506 LStrgy.setTargetOccupancy(I == 0 ? 0 : TgtOcc);
507 for (auto R : Regions) {
508 OverrideLegacyStrategy Ovr(*R, LStrgy, *this);
511 const auto RP = getRegionPressure(*R);
512 DEBUG(printSchedRP(dbgs(), R->MaxPressure, RP));
514 if (RP.getOccupancy(ST) < TgtOcc) {
515 DEBUG(dbgs() << "Didn't fit into target occupancy O" << TgtOcc);
516 if (R->BestSchedule.get() &&
517 R->BestSchedule->MaxPressure.getOccupancy(ST) >= TgtOcc) {
518 DEBUG(dbgs() << ", scheduling minimal register\n");
521 DEBUG(dbgs() << ", restoring\n");
523 assert(R->MaxPressure.getOccupancy(ST) >= TgtOcc);
530 ///////////////////////////////////////////////////////////////////////////////
531 // Minimal Register Strategy
533 void GCNIterativeScheduler::scheduleMinReg(bool force) {
534 const auto &ST = MF.getSubtarget<SISubtarget>();
535 const auto TgtOcc = ST.getOccupancyWithLocalMemSize(MF);
536 sortRegionsByPressure(TgtOcc);
538 auto MaxPressure = Regions.front()->MaxPressure;
539 for (auto R : Regions) {
540 if (!force && R->MaxPressure.less(ST, MaxPressure, TgtOcc))
543 BuildDAG DAG(*R, *this);
544 const auto MinSchedule = makeMinRegSchedule(DAG.getTopRoots(), *this);
546 const auto RP = getSchedulePressure(*R, MinSchedule);
547 DEBUG(if (R->MaxPressure.less(ST, RP, TgtOcc)) {
548 dbgs() << "\nWarning: Pressure becomes worse after minreg!";
549 printSchedRP(dbgs(), R->MaxPressure, RP);
552 if (!force && MaxPressure.less(ST, RP, TgtOcc))
555 scheduleRegion(*R, MinSchedule, RP);
556 DEBUG(printSchedResult(dbgs(), R, RP));
562 ///////////////////////////////////////////////////////////////////////////////
563 // ILP scheduler port
565 void GCNIterativeScheduler::scheduleILP(
566 bool TryMaximizeOccupancy) {
567 const auto &ST = MF.getSubtarget<SISubtarget>();
568 auto TgtOcc = std::min(ST.getOccupancyWithLocalMemSize(MF),
569 ST.getWavesPerEU(MF.getFunction()).second);
571 sortRegionsByPressure(TgtOcc);
572 auto Occ = Regions.front()->MaxPressure.getOccupancy(ST);
574 if (TryMaximizeOccupancy && Occ < TgtOcc)
575 Occ = tryMaximizeOccupancy(TgtOcc);
577 TgtOcc = std::min(Occ, TgtOcc);
578 DEBUG(dbgs() << "Scheduling using default scheduler, "
579 "target occupancy = " << TgtOcc << '\n');
581 for (auto R : Regions) {
582 BuildDAG DAG(*R, *this);
583 const auto ILPSchedule = makeGCNILPScheduler(DAG.getBottomRoots(), *this);
585 const auto RP = getSchedulePressure(*R, ILPSchedule);
586 DEBUG(printSchedRP(dbgs(), R->MaxPressure, RP));
588 if (RP.getOccupancy(ST) < TgtOcc) {
589 DEBUG(dbgs() << "Didn't fit into target occupancy O" << TgtOcc);
590 if (R->BestSchedule.get() &&
591 R->BestSchedule->MaxPressure.getOccupancy(ST) >= TgtOcc) {
592 DEBUG(dbgs() << ", scheduling minimal register\n");
596 scheduleRegion(*R, ILPSchedule, RP);
597 DEBUG(printSchedResult(dbgs(), R, RP));