LLVM 24.0.0git
AMDGPUCoExecSchedStrategy.cpp
Go to the documentation of this file.
1//===- AMDGPUCoExecSchedStrategy.cpp - CoExec Scheduling Strategy ---------===//
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
10/// Coexecution-focused scheduling strategy for AMDGPU.
11//
12//===----------------------------------------------------------------------===//
13
16#include "AMDGPUIGroupLP.h"
17#include "GCNHazardRecognizer.h"
18#include "llvm/Support/Debug.h"
19
20using namespace llvm;
21using namespace llvm::AMDGPU;
22
23#define DEBUG_TYPE "machine-scheduler"
24
25// Default VGPR threshold percent for coexec scheduler.
26static constexpr unsigned DefaultCoExecVGPRThresholdPercent = 100;
27
28namespace {
29
30// Used to disable post-RA scheduling with function level granularity.
31class GCNNoopPostScheduleDAG final : public ScheduleDAGInstrs {
32public:
33 explicit GCNNoopPostScheduleDAG(MachineSchedContext *C)
34 : ScheduleDAGInstrs(*C->MF, C->MLI, /*RemoveKillFlags=*/true) {}
35
36 // Do nothing.
37 void schedule() override {}
38};
39
40} // namespace
41
43 // pickOnlyChoice() releases pending instructions and checks for new hazards.
44 SUnit *OnlyChoice = Zone.pickOnlyChoice();
45 if (!Zone.Pending.empty())
46 return nullptr;
47
48 return OnlyChoice;
49}
50
51/// Build MFMA co-exec rules from the first stage at which SALU, memory (DS and
52/// VMEM), VALU, the next MFMA and packed F32 VALU may issue. MFMA slots are
53/// cumulative: each slot allows what the previous one did and possibly more.
54static CoExecInfo buildMFMACoExecInfo(unsigned SALU, unsigned Mem,
55 unsigned VALU, unsigned MFMA,
56 unsigned PkF32, unsigned Window) {
57 assert(Window <= MaxCoExecStages && "co-execution window is too long");
58 CoExecInfo Res;
59 Res.TotalWindow = Window;
60
61 // TODO: Implement proper patterns support (for debugging purposes).
62 // Existing pattern letters are WMMA-specific and will probably be confusing
63 // if used as-is for MFMA. Inventing new MFMA-specific letters is an option,
64 // but perhaps the pattern should be instead dynamically reconstructed when
65 // needed by printing specific slots in full instead of a key for them.
66 Res.Pattern = "undefinedundefinedundefinedundefined";
67
68 for (unsigned I = 0; I < Window; ++I) {
70 if (I >= SALU)
71 Mask |= CoExecMask::SALU;
72 if (I >= Mem)
74 if (I >= VALU)
76 if (I >= MFMA)
77 Mask |= CoExecMask::WMMA;
78 if (I >= PkF32)
79 Mask |= CoExecMask::PK_F32;
80 Res.Slots[I].Mask = Mask;
81 }
82 return Res;
83}
84
85/// Get co-execution info for an MFMA instruction.
87 const GCNSubtarget &ST) {
88 const MAIInstInfo *Info = getMAIInstInfoHelper(Opcode);
89 MFMAVariant Variant = Info ? Info->Variant : MFMAVariant::Unknown;
90
91 switch (Variant) {
93 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/2, /*VALU=*/2, /*MFMA=*/4,
94 /*PkF32=*/7, /*Window=*/8);
95 }
97 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/2, /*VALU=*/2, /*MFMA=*/8,
98 /*PkF32=*/11, /*Window=*/12);
99 }
101 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/2, /*VALU=*/3, /*MFMA=*/8,
102 /*PkF32=*/11, /*Window=*/12);
103 }
105 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/2, /*VALU=*/3, /*MFMA=*/16,
106 /*PkF32=*/19, /*Window=*/20);
107 }
109 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/2, /*VALU=*/3, /*MFMA=*/4,
110 /*PkF32=*/7, /*Window=*/8);
111 }
113 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/3, /*VALU=*/3, /*MFMA=*/8,
114 /*PkF32=*/11, /*Window=*/12);
115 }
117 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/1, /*VALU=*/1, /*MFMA=*/2,
118 /*PkF32=*/4, /*Window=*/5);
119 }
121 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/1, /*VALU=*/1, /*MFMA=*/4,
122 /*PkF32=*/6, /*Window=*/7);
123 }
125 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/1, /*VALU=*/1, /*MFMA=*/8,
126 /*PkF32=*/10, /*Window=*/11);
127 }
129 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/1, /*VALU=*/1, /*MFMA=*/16,
130 /*PkF32=*/18, /*Window=*/19);
131 }
133 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/2, /*VALU=*/2, /*MFMA=*/4,
134 /*PkF32=*/6, /*Window=*/7);
135 }
137 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/2, /*VALU=*/2, /*MFMA=*/8,
138 /*PkF32=*/10, /*Window=*/11);
139 }
141 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/1, /*VALU=*/4, /*MFMA=*/2,
142 /*PkF32=*/4, /*Window=*/5);
143 }
145 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/1, /*VALU=*/10, /*MFMA=*/8,
146 /*PkF32=*/10, /*Window=*/11);
147 }
149 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/1, /*VALU=*/18, /*MFMA=*/16,
150 /*PkF32=*/18, /*Window=*/19);
151 }
153 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/1, /*VALU=*/6, /*MFMA=*/4,
154 /*PkF32=*/6, /*Window=*/7);
155 }
157 if (ST.hasGFX950Insts()) {
158 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/1, /*VALU=*/18,
159 /*MFMA=*/16, /*PkF32=*/18, /*Window=*/19);
160 }
161 return buildMFMACoExecInfo(/*SALU=*/1, /*Mem=*/1, /*VALU=*/10, /*MFMA=*/8,
162 /*PkF32=*/10, /*Window=*/11);
163 }
165 // No co-execution model: permissive 9-cycle window.
166 return CoExecInfo::build(0, 9, "AAAAAAAAA");
167 }
168 llvm_unreachable("unknown MFMA variant");
169}
170
172 const SIInstrInfo &SII) {
173 if (MI.isDebugInstr())
175
176 unsigned Opc = MI.getOpcode();
177
178 // Check for specific opcodes first.
179 if (Opc == AMDGPU::ATOMIC_FENCE || Opc == AMDGPU::S_BARRIER_WAIT ||
180 Opc == AMDGPU::S_BARRIER_SIGNAL_IMM || SII.isWaitcnt(Opc))
182
183 if (SII.isLDSDMA(MI))
185
186 if (SII.isMFMA(MI)) {
187 // TODO: Consider further sub-classifying this (XDL, XDL2x, S/DGEMM).
188 // GFX9 SPG sub-classifies MFMA into XDL, XDL2x and S/DGEMM, because only
189 // certain sub-classes can be co-executed in certain slots. For now, we
190 // simply treat them all as one to simplify the change and leave the rest
191 // to a follow-up fine-tuning.
193 }
194
195 if (SII.isWMMA(MI) || SII.isSWMMAC(MI))
197
198 if (SII.isTRANS(MI))
200
201 if (SII.getSubtarget().hasPackedFP32Ops()) {
202 switch (Opc) {
203 case AMDGPU::V_PK_ADD_F32:
204 case AMDGPU::V_PK_FMA_F32:
205 case AMDGPU::V_PK_MOV_B32:
206 case AMDGPU::V_PK_MUL_F32:
208 default:
209 break;
210 }
211 }
212
213 if (SII.isVALU(MI, /*AllowLDSDMA=*/false)) {
214 if (SII.getBlockingCycles(MI) > 1)
216
218 }
219
220 if (SII.isSMRD(MI))
222
223 if (SII.isDS(MI))
225
226 if (SII.isVMEM(MI))
228
229 if (SII.isSALU(MI))
231
233}
234
236 for (SUnit *PrioritySU : PrioritySUs) {
237 if (!PrioritySU->isTopReady())
238 return PrioritySU;
239 }
240
241 if (!LookDeep)
242 return nullptr;
243
244 unsigned MinDepth = std::numeric_limits<unsigned int>::max();
245 SUnit *TargetSU = nullptr;
246 for (auto *SU : AllSUs) {
247 if (SU->isScheduled)
248 continue;
249
250 if (SU->isTopReady())
251 continue;
252
253 if (SU->getDepth() < MinDepth) {
254 MinDepth = SU->getDepth();
255 TargetSU = SU;
256 }
257 }
258 return TargetSU;
259}
260
261void HardwareUnitInfo::insert(SUnit *SU, unsigned BlockingCycles) {
262 if (!AllSUs.insert(SU))
263 llvm_unreachable("HardwareUnit already contains SU!");
264
265 TotalCycles += BlockingCycles;
266
267 if (PrioritySUs.empty()) {
268 PrioritySUs.insert(SU);
269 return;
270 }
271 unsigned SUDepth = SU->getDepth();
272 unsigned CurrDepth = (*PrioritySUs.begin())->getDepth();
273 if (SUDepth > CurrDepth)
274 return;
275
276 if (SUDepth == CurrDepth) {
277 PrioritySUs.insert(SU);
278 return;
279 }
280
281 // SU is lower depth and should be prioritized.
282 PrioritySUs.clear();
283 PrioritySUs.insert(SU);
284}
285
286void HardwareUnitInfo::markScheduled(SUnit *SU, unsigned BlockingCycles) {
287 // We may want to ignore some HWUIs (e.g. InstructionFlavor::Other). To do so,
288 // we just clear the HWUI. However, we still have instructions which map to
289 // this HWUI. Don't bother managing the state for these HWUI.
290 if (TotalCycles == 0)
291 return;
292
293 ScheduledSUs.push_back(SU);
294 AllSUs.remove(SU);
295 PrioritySUs.remove(SU);
296
297 // BufferSize 0 is unlimited, while size 1 has no parallel buffering. In
298 // either case, each SU uses the HardwareUnit for BlockingCycles.
299 if (BufferSize <= 1 || (ScheduledSUs.size() % BufferSize == 0))
300 TotalCycles -= std::min(TotalCycles, BlockingCycles);
301
302 if (AllSUs.empty())
303 return;
304 if (PrioritySUs.empty()) {
305 for (auto SU : AllSUs) {
306 if (PrioritySUs.empty()) {
307 PrioritySUs.insert(SU);
308 continue;
309 }
310 unsigned SUDepth = SU->getDepth();
311 unsigned CurrDepth = (*PrioritySUs.begin())->getDepth();
312 if (SUDepth > CurrDepth)
313 continue;
314
315 if (SUDepth == CurrDepth) {
316 PrioritySUs.insert(SU);
317 continue;
318 }
319
320 // SU is lower depth and should be prioritized.
321 PrioritySUs.clear();
322 PrioritySUs.insert(SU);
323 }
324 }
325}
326
328 if (BufferSize == 0 || AllSUs.empty())
329 return;
330
331 // We estimate the amount of cycles it takes to free up a slot in the buffer
332 // as the average cycles per SU.
333 BufferCycles = static_cast<unsigned>(TotalCycles / AllSUs.size());
334 // A single-entry buffer does not reduce TotalCycles.
335 if (BufferSize == 1)
336 return;
337
338 // The TotalCycles is normalized against the BufferSize.
339 // This provides an estimate of the TotalCycles which is not always accurate
340 // -- particularly in cases where we have fewer instructions than the
341 // BufferSize. For example, if we have 2 instructions which each take 50
342 // cycles and a BufferSize of 16, then a TotalCycles of 51 cycles would be
343 // somewhat accurate. This normalization calculates TotalCycles as 6. However,
344 // if we have 64 of these instructions, our normalized estimate of 200 is more
345 // reasonable, given the more accurate measure is 264. Having a completely
346 // accurate measure is not very important, since this metric is mainly used to
347 // compare the relative demand per HardwareUnit across the region. The simpler
348 // estimate makes managing the metric incrementally during scheduling much
349 // simpler.
350 TotalCycles /= BufferSize;
351}
352
355 for (HardwareUnitInfo &HWUICand : HWUInfo) {
356 if (HWUICand.getType() == Flavor) {
357 return &HWUICand;
358 }
359 }
360 return nullptr;
361}
362
364 const MachineInstr *MI) {
365 unsigned ReleaseAtCycle = 0;
366 for (TargetSchedModel::ProcResIter PI = SchedModel->getWriteProcResBegin(SC),
367 PE = SchedModel->getWriteProcResEnd(SC);
368 PI != PE; ++PI) {
369 ReleaseAtCycle =
370 std::max(ReleaseAtCycle, static_cast<unsigned>(PI->ReleaseAtCycle));
371 }
372 ReleaseAtCycle = std::max(ReleaseAtCycle, SII->getBlockingCycles(*MI));
373 return ReleaseAtCycle;
374}
375
377 assert(SchedModel && SchedModel->hasInstrSchedModel());
378 if (MI->mayLoadOrStore())
379 return SchedModel->computeInstrLatency(MI, false);
380 return getMaxBlockingCycles(SchedModel->resolveSchedClass(MI), MI);
381}
382
389
392 const TargetRegisterInfo *TRI,
393 const MachineLoopInfo *LoopInfo) {
394 DAG = SchedDAG;
396 MLI = LoopInfo;
397 assert(SchedModel && SchedModel->hasInstrSchedModel());
398
399 SRI = static_cast<const SIRegisterInfo *>(TRI);
400 SII = static_cast<const SIInstrInfo *>(DAG->TII);
401
402 HWUInfo.resize(static_cast<int>(InstructionFlavor::NUM_FLAVORS));
403
404 for (unsigned I = 0; I < HWUInfo.size(); I++) {
405 HWUInfo[I].reset();
406 HWUInfo[I].setType(I);
407 }
408
409 HWUInfo[static_cast<int>(InstructionFlavor::WMMA)].setProducesCoexecWindow(
410 true);
412 .setProducesCoexecWindow(true);
413 HWUInfo[static_cast<int>(InstructionFlavor::TRANS)].setProducesCoexecWindow(
414 true);
415 HWUInfo[static_cast<int>(InstructionFlavor::DS)].setBufferSize(
417
419}
420
423 return 0;
424
425 MachineInstr *MI = SU->getInstr();
426 unsigned CarriedLatency = 0;
427 const InstructionFlavor Flavor = classifyFlavor(*MI, *SII);
428 if (Flavor == InstructionFlavor::Fence) {
429 MachineBasicBlock *MBB = MI->getParent();
430 // Scan each direct predecessor back to its nearest Fence or block start for
431 // DS instructions.
432 for (auto PredMBB : MBB->predecessors()) {
433 auto I = PredMBB->rbegin();
434 auto E = PredMBB->rend();
435 for (; I != E; I++) {
436 const InstructionFlavor ItFlavor = classifyFlavor(*I, *SII);
437 if (ItFlavor == InstructionFlavor::Fence)
438 break;
439
440 // Found carried latency.
441 if (ItFlavor == InstructionFlavor::DS)
443 }
444 }
445 }
446
448 return CarriedLatency;
449
450 for (MachineOperand &Op : MI->all_uses()) {
451 auto Reg = Op.getReg();
452 if (!Reg.isVirtual())
453 continue;
454
455 for (MachineInstr &Def : DAG->MRI.def_instructions(Reg)) {
456 // We don't have the proper modelling to accurately measure all carried
457 // latency. Just try to measure carried latency for long latency loads to
458 // avoid long stalls.
459 if (!Def.mayLoad())
460 continue;
461
462 unsigned Latency = getHWUICyclesForMI(&Def);
463
464 // Load is carried across block.
465 if (Def.getParent() != MI->getParent()) {
466 bool FoundUseInDefBlock = false;
467 for (MachineInstr &Use : DAG->MRI.use_nodbg_instructions(Reg)) {
468 if (Use.getParent() != Def.getParent())
469 continue;
470
471 SlotIndex DefIdx = DAG->getLIS()->getInstructionIndex(Def);
472 SlotIndex UseIdx = DAG->getLIS()->getInstructionIndex(Use);
473 // We have a use of this load in the def block that occurs after the
474 // load. In this case we must wait for the load in the def block, and
475 // we do not have any carried latency from this load.
476 if (SlotIndex::isEarlierInstr(DefIdx, UseIdx)) {
477 FoundUseInDefBlock = true;
478 break;
479 }
480 }
481 if (!FoundUseInDefBlock)
483
484 continue;
485 }
486
487 assert(Def.getParent() == MI->getParent());
488 // Load is in the same block.
489 SlotIndex LoadIdx = DAG->getLIS()->getInstructionIndex(Def);
490 SlotIndex UseIdx = DAG->getLIS()->getInstructionIndex(*MI);
491 // The load occurs after this use -- the latency is carried across loop
492 // backedge.
493 if (SlotIndex::isEarlierInstr(UseIdx, LoadIdx))
495 }
496 }
497 return CarriedLatency;
498}
499
501 CarriedLatencies.clear();
503
504 if (!SchedModel || !SchedModel->hasInstrSchedModel())
505 return;
506
507 // In some cases, we may end up with loads at the end of a predecssor block.
508 // In these cases, it is preferable to defer scheduling a fence which
509 // corresponds with a waitcnt for those loads until the latency of the load
510 // has cleared. Unfortunately, there is no reliable way to determine whether
511 // or not a predecessor block will end up scheduling loads at the end. Here,
512 // we inspect the dependency structure to define a rough heuristic: if we
513 // must schedule ds_loads after wmma, then we carry the latency of ds_loads
514 // to successor block fences. Currently this only checks for the loop-carried
515 // case, as this will generally have the largest impact on performance.
516 // TODO: 1. extend to different memory instructions, 2. teach carried
517 // latencies about fence legalization.
518 auto mustHaveDSAfter = [this]() {
519 if (!DAG->SUnits.size())
520 return false;
521
522 MachineBasicBlock *MBB = DAG->begin()->getParent();
523 MachineLoop *Loop = MLI->getLoopFor(MBB);
524 if (!Loop || Loop->getNumBlocks() != 1)
525 return false;
526
527 SmallVector<SUnit *, 16> RegionWMMAs;
528
529 for (auto &SU : DAG->SUnits) {
530 if (!SU.getInstr())
531 continue;
532 MachineInstr *MI = SU.getInstr();
533 const InstructionFlavor Flavor = classifyFlavor(*MI, *SII);
534 if (Flavor == InstructionFlavor::WMMA)
535 RegionWMMAs.push_back(&SU);
536 }
537
538 bool MustHaveDSAfter = RegionWMMAs.size();
539
540 for (SUnit *SU : RegionWMMAs) {
541 bool HasDSSucc = false;
542 for (auto &Succ : SU->Succs) {
543 if (!Succ.getSUnit()->getInstr())
544 continue;
545 if (classifyFlavor(*Succ.getSUnit()->getInstr(), *SII) ==
547 HasDSSucc = true;
548 break;
549 }
550 }
551
552 if (!HasDSSucc) {
553 MustHaveDSAfter = false;
554 break;
555 }
556 }
557
558 return MustHaveDSAfter;
559 };
560
561 std::optional<CarriedLatency> BlockCarriedLatency =
562 DAG->MF.getSubtarget<GCNSubtarget>().getCLOpts().block_carried_latency;
563 RegionCarriedLatency = BlockCarriedLatency ? *BlockCarriedLatency
564 : mustHaveDSAfter() ? CarriedLatency::Fence
566
567 for (auto &SU : DAG->SUnits) {
568 MachineInstr *MI = SU.getInstr();
569 const InstructionFlavor Flavor = classifyFlavor(*MI, *SII);
570 HWUInfo[static_cast<int>(Flavor)].insert(&SU, getHWUICyclesForMI(MI));
571 unsigned CarriedLatency = getCarriedLatency(&SU);
572 if (CarriedLatency)
574 }
575
576 for (auto &HWUI : HWUInfo)
577 HWUI.finalizeCycles();
578
580}
581
583 MachineBasicBlock *BB = DAG->begin()->getParent();
584 dbgs() << "\n=== Region: " << DAG->MF.getName() << " BB" << BB->getNumber()
585 << " (" << DAG->SUnits.size() << " SUs) ===\n";
586
587 dbgs() << "\nHWUI Resource Pressure:\n";
588 for (auto &HWUI : HWUInfo) {
589 if (HWUI.getTotalCycles() == 0)
590 continue;
591
592 StringRef Name = getFlavorName(HWUI.getType());
593 dbgs() << " " << Name << ": " << HWUI.getTotalCycles() << " cycles, "
594 << HWUI.size() << " instrs\n";
595 }
596 dbgs() << "\n";
597}
598
600 // Highest priority should be first.
602 // Prefer CoexecWindow producers
603 if (A.producesCoexecWindow() != B.producesCoexecWindow())
604 return A.producesCoexecWindow();
605
606 // Prefer more demanded resources
607 if (A.getTotalCycles() != B.getTotalCycles())
608 return A.getTotalCycles() > B.getTotalCycles();
609
610 // In ties -- prefer the resource with more instructions
611 if (A.size() != B.size())
612 return A.size() < B.size();
613
614 // Default to Flavor order
615 return static_cast<unsigned>(A.getType()) <
616 static_cast<unsigned>(B.getType());
617 });
618}
619
621 SUnit *SU) {
622 assert(Zone.isTop() && "effective stall comparison requires top boundary");
623 if (!SU)
624 return 0;
625
626 MachineInstr *MI = SU->getInstr();
627 unsigned CurrCycle = Zone.getCurrCycle();
628 unsigned Stall = 0;
629
630 // Query SchedModel for resource stalls (unbuffered resources).
631 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
632 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
633 for (const MCWriteProcResEntry &PE :
634 make_range(SchedModel->getWriteProcResBegin(SC),
635 SchedModel->getWriteProcResEnd(SC))) {
636 unsigned NextAvail =
637 Zone.getNextResourceCycle(SC, PE.ProcResourceIdx, PE.ReleaseAtCycle,
638 PE.AcquireAtCycle)
639 .first;
640 if (NextAvail > CurrCycle)
641 Stall = std::max(Stall, NextAvail - CurrCycle);
642 }
643 }
644
645 // Query HazardRecognizer for sequence-dependent hazard penalties.
646 if (Zone.HazardRec && Zone.HazardRec->isEnabled()) {
647 auto *HR = static_cast<GCNHazardRecognizer *>(Zone.HazardRec.get());
648 Stall = std::max(Stall, HR->getHazardWaitStates(MI));
649 }
650
651 return Stall;
652}
653
656 if (!Zone.isTop())
657 return {};
658
659 auto getBufferFullStalls = [this, &Zone](SUnit *SU) -> unsigned {
661 *SU->getInstr(), *static_cast<const SIInstrInfo *>(DAG->TII));
662 HardwareUnitInfo *HWUI = getHWUIFromFlavor(Flavor);
663
664 // A BufferSize of 0 means "unlimited" buffer, thus we will never fill it.
665 if (HWUI->getBufferSize() == 0)
666 return 0;
667
668 unsigned CurrCycle = Zone.getCurrCycle();
669 unsigned BufferReadyCycle = HWUI->getBufferAvailableCycle(CurrCycle);
670 if (BufferReadyCycle <= CurrCycle)
671 return 0;
672
673 return BufferReadyCycle - CurrCycle;
674 };
675
676 unsigned CurrCycle = Zone.getCurrCycle();
677
678 auto getFenceStalls = [this, &CurrCycle](SUnit *SU) -> unsigned {
680 *SU->getInstr(), *static_cast<const SIInstrInfo *>(DAG->TII));
681
682 if (Flavor != InstructionFlavor::Fence)
683 return 0;
684
685 HardwareUnitInfo *ConsumerHWUI = getHWUIFromFlavor(Flavor);
687
688 SUnit *LastProducer = ProducerHWUI->getLastScheduledSU();
689 if (!LastProducer)
690 return 0;
691
692 SUnit *LastConsumer = ConsumerHWUI->getLastScheduledSU();
693 unsigned LastConsumerCycle = LastConsumer ? LastConsumer->TopReadyCycle : 0;
694 unsigned LastProducerCycle = LastProducer->TopReadyCycle;
695
696 if (LastProducerCycle < LastConsumerCycle)
697 return 0;
698
699 unsigned FenceStallFinish =
700 LastProducerCycle + getHWUICyclesForMI(LastProducer->getInstr());
701 return FenceStallFinish <= CurrCycle ? 0 : FenceStallFinish - CurrCycle;
702 };
703
704 unsigned ReadyCycle = SU->TopReadyCycle;
705 StallCosts Costs;
706 Costs.Ready = ReadyCycle > CurrCycle ? ReadyCycle - CurrCycle : 0;
707 Costs.Structural = getStructuralStallCycles(Zone, SU);
708 Costs.Latency = Zone.getLatencyStallCycles(SU);
709 unsigned CarriedLatency = CarriedLatencies.lookup_or(SU->getInstr(), 0);
710 Costs.Carried = CarriedLatency > CurrCycle ? CarriedLatency - CurrCycle : 0;
711 Costs.Buffer = getBufferFullStalls(SU);
712 Costs.Fence = getFenceStalls(SU);
713 Costs.Effective = std::max({Costs.Ready, Costs.Structural, Costs.Latency,
714 Costs.Carried, Costs.Buffer, Costs.Fence});
715 return Costs;
716}
717
721 // Only implemented for top-down scheduling
722 if (!Zone.isTop())
723 return 0;
724
725 StallCosts TryCosts = getStallCosts(TryCand.SU, Zone);
726 StallCosts CandCosts = getStallCosts(Cand.SU, Zone);
727
728 LLVM_DEBUG(if (TryCosts.Effective || CandCosts.Effective) {
729 dbgs() << "Effective stalls: try=" << TryCosts.Effective
730 << " (ready=" << TryCosts.Ready << ", struct=" << TryCosts.Structural
731 << ", lat=" << TryCosts.Latency << ", carried=" << TryCosts.Carried
732 << ", buffer=" << TryCosts.Buffer << ", fence=" << TryCosts.Fence
733 << ") cand=" << CandCosts.Effective << " (ready=" << CandCosts.Ready
734 << ", struct=" << CandCosts.Structural
735 << ", lat=" << CandCosts.Latency << ", carried=" << CandCosts.Carried
736 << ", buffer=" << CandCosts.Buffer << ", fence=" << CandCosts.Fence
737 << ")\n";
738 });
739
740 return tryLess(TryCosts.Effective, CandCosts.Effective, TryCand, Cand,
742}
743
747
748 InstructionFlavor TryFlavor = classifyFlavor(*TryCand.SU->getInstr(), *SII);
749
750 InstructionFlavor CandFlavor = classifyFlavor(*Cand.SU->getInstr(), *SII);
751
752 bool TryIsMemoryPipeline = TryFlavor == InstructionFlavor::DMA ||
753 TryFlavor == InstructionFlavor::Fence;
754 bool CandIsMemoryPipeline = CandFlavor == InstructionFlavor::DMA ||
755 CandFlavor == InstructionFlavor::Fence;
756
757 if (!(TryIsMemoryPipeline || CandIsMemoryPipeline))
758 return false;
759
760 if (TryIsMemoryPipeline)
761 TryIsMemoryPipeline &= getStallCosts(TryCand.SU, Zone).Effective == 0;
762
763 if (CandIsMemoryPipeline)
764 CandIsMemoryPipeline &= getStallCosts(Cand.SU, Zone).Effective == 0;
765
766 if (TryIsMemoryPipeline == CandIsMemoryPipeline)
767 return false;
768
769 if (CandIsMemoryPipeline) {
772
773 return true;
774 }
775
777 return true;
778}
779
783
784 auto HasPrioritySU = [this, &Cand, &TryCand](unsigned ResourceIdx) {
785 const HardwareUnitInfo &HWUI = HWUInfo[ResourceIdx];
786
787 auto CandFlavor = classifyFlavor(*Cand.SU->getInstr(), *SII);
788 auto TryCandFlavor = classifyFlavor(*TryCand.SU->getInstr(), *SII);
789 bool LookDeep = (CandFlavor == InstructionFlavor::DS ||
790 TryCandFlavor == InstructionFlavor::DS) &&
792 auto *TargetSU = HWUI.getNextTargetSU(LookDeep);
793
794 // If we do not have a TargetSU for this resource, then it is not critical.
795 if (!TargetSU)
796 return false;
797
798 return true;
799 };
800
801 auto TryEnablesResource = [&Cand, &TryCand, this](unsigned ResourceIdx) {
802 const HardwareUnitInfo &HWUI = HWUInfo[ResourceIdx];
803 auto CandFlavor = classifyFlavor(*Cand.SU->getInstr(), *SII);
804
805 // We want to ensure our DS order matches WMMA order.
806 bool LookDeep = CandFlavor == InstructionFlavor::DS &&
808 auto *TargetSU = HWUI.getNextTargetSU(LookDeep);
809
810 bool CandEnables =
811 TargetSU != Cand.SU && DAG->IsReachable(TargetSU, Cand.SU);
812 bool TryCandEnables =
813 TargetSU != TryCand.SU && DAG->IsReachable(TargetSU, TryCand.SU);
814
815 if (!CandEnables && !TryCandEnables)
816 return false;
817
818 if (CandEnables && !TryCandEnables) {
821
822 return true;
823 }
824
825 if (!CandEnables && TryCandEnables) {
827 return true;
828 }
829
830 // Both enable, prefer the critical path.
831 unsigned CandHeight = Cand.SU->getHeight();
832 unsigned TryCandHeight = TryCand.SU->getHeight();
833
834 if (CandHeight > TryCandHeight) {
837
838 return true;
839 }
840
841 if (CandHeight < TryCandHeight) {
843 return true;
844 }
845
846 // Same critical path, just prefer original candidate.
849
850 return true;
851 };
852
853 for (unsigned I = 0; I < HWUInfo.size(); I++) {
854 // If we have encountered a resource that is not critical, then neither
855 // candidate enables a critical resource
856 if (!HasPrioritySU(I))
857 continue;
858
859 bool Enabled = TryEnablesResource(I);
860 // If neither has enabled the resource, continue to the next resource
861 if (Enabled)
862 return true;
863 }
864 return false;
865}
866
870 for (unsigned I = 0; I < HWUInfo.size(); I++) {
871 const HardwareUnitInfo &HWUI = HWUInfo[I];
872
873 bool CandUsesCrit = HWUI.contains(Cand.SU);
874 bool TryCandUsesCrit = HWUI.contains(TryCand.SU);
875
876 if (!CandUsesCrit && !TryCandUsesCrit)
877 continue;
878
879 if (CandUsesCrit != TryCandUsesCrit) {
880 if (CandUsesCrit) {
883 return true;
884 }
886 return true;
887 }
888
889 // Otherwise, both use the critical resource
890 // For longer latency InstructionFlavors, we should prioritize first by
891 // their enablement of critical resources
892 if (HWUI.getType() == InstructionFlavor::DS) {
893 if (tryCriticalResourceDependency(TryCand, Cand, Zone))
894 return true;
895 }
896
897 // Prioritize based on HWUI priorities.
898 SUnit *Match = HWUI.getHigherPriority(Cand.SU, TryCand.SU);
899 if (Match) {
900 if (Match == Cand.SU) {
903 return true;
904 }
906 return true;
907 }
908 }
909
910 return false;
911}
912
926
929 unsigned NumRegionInstrs) {
932 if (Direction == MISched::BottomUp || Direction == MISched::Bidirectional)
933 report_fatal_error("CoExecSchedStrategy only support TopDown scheduling.");
934 RegionPolicy.OnlyTopDown = true;
935 RegionPolicy.OnlyBottomUp = false;
936 RegionPolicy.ShouldTrackLaneMasks = true;
937}
938
940 // Coexecution scheduling strategy is only done top-down to support new
941 // resource balancing heuristics.
942 RegionPolicy.OnlyTopDown = true;
943 RegionPolicy.OnlyBottomUp = false;
944
946 Heurs.initialize(DAG, SchedModel, TRI, Context->MLI);
947
948 // Replace the default hazard recognizer with our PreRA one so that pre-RA
949 // scheduling accounts for WMMA co-execution slot constraints. This must
950 // happen after GCNSchedStrategy::initialize() because
951 // GenericScheduler::initialize() calls SchedBoundary::reset(), which deletes
952 // and recreates the hazard recognizer each region.
953 Top.HazardRec = std::make_unique<GCNHazardRecognizer>(
955}
956
958 Heurs.updateForScheduling(SU);
959 GCNSchedStrategy::schedNode(SU, IsTopNode);
960}
961
963 assert(RegionPolicy.OnlyTopDown && !RegionPolicy.OnlyBottomUp &&
964 "coexec scheduler only supports top-down scheduling");
965
966 if (DAG->top() == DAG->bottom()) {
967 assert(Top.Available.empty() && Top.Pending.empty() &&
968 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
969 return nullptr;
970 }
971
972 bool PickedPending = false;
973 SUnit *SU = nullptr;
974#ifndef NDEBUG
975 SchedCandidate *PickedCand = nullptr;
976#endif
977 do {
978 PickedPending = false;
979 SU = pickOnlyChoice(Top);
980 if (!SU) {
981 CandPolicy NoPolicy;
982 TopCand.reset(NoPolicy);
983 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand,
984 PickedPending, /*IsBottomUp=*/false);
985 assert(TopCand.Reason != NoCand && "failed to find a candidate");
986 SU = TopCand.SU;
987#ifndef NDEBUG
988 PickedCand = &TopCand;
989#endif
990 }
991 IsTopNode = true;
992 } while (SU->isScheduled);
993
994 LLVM_DEBUG(if (PickedCand) dumpPickSummary(SU, IsTopNode, *PickedCand));
995
996 if (PickedPending) {
997 unsigned ReadyCycle = SU->TopReadyCycle;
998 unsigned CurrentCycle = Top.getCurrCycle();
999 if (ReadyCycle > CurrentCycle)
1000 Top.bumpCycle(ReadyCycle);
1001
1002 // checkHazard() does not expose the exact cycle where the hazard clears.
1003 while (Top.checkHazard(SU))
1004 Top.bumpCycle(Top.getCurrCycle() + 1);
1005
1006 Top.releasePending();
1007 }
1008
1009 if (SU->isTopReady())
1010 Top.removeReady(SU);
1011 if (SU->isBottomReady())
1012 Bot.removeReady(SU);
1013
1014 LLVM_DEBUG(dbgs() << "Scheduling " << *SU << " " << *SU->getInstr());
1015
1016 assert(IsTopNode && "coexec scheduler must only schedule from top boundary");
1017 return SU;
1018}
1019
1021 SchedBoundary &Zone, const CandPolicy &ZonePolicy,
1022 const RegPressureTracker &RPTracker, SchedCandidate &Cand,
1023 bool &PickedPending, bool IsBottomUp) {
1024 assert(Zone.isTop() && "coexec scheduler only supports top boundary");
1025 assert(!IsBottomUp && "coexec scheduler only supports top-down scheduling");
1026
1027 const SIRegisterInfo *SRI = static_cast<const SIRegisterInfo *>(TRI);
1029 unsigned SGPRPressure = 0;
1030 unsigned VGPRPressure = 0;
1031 unsigned AGPRPressure = 0;
1032 PickedPending = false;
1033 if (DAG->isTrackingPressure()) {
1034 if (!useGCNTrackers()) {
1035 SGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
1036 VGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
1037 AGPRPressure = Pressure[AMDGPU::RegisterPressureSets::AGPR_32];
1038 } else {
1039 SGPRPressure = DownwardTracker.getPressure().getSGPRNum();
1040 std::tie(VGPRPressure, AGPRPressure) =
1041 getBankedPressure(DownwardTracker.getPressure());
1042 }
1043 }
1044
1045 auto EvaluateQueue = [&](ReadyQueue &Q, bool FromPending) {
1046 for (SUnit *SU : Q) {
1047 SchedCandidate TryCand(ZonePolicy);
1048 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, SRI, SGPRPressure,
1049 VGPRPressure, AGPRPressure, IsBottomUp);
1050 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
1051 tryCandidateCoexec(Cand, TryCand, ZoneArg);
1052 if (TryCand.Reason != NoCand) {
1053 if (TryCand.ResDelta == SchedResourceDelta())
1054 TryCand.initResourceDelta(Zone.DAG, SchedModel);
1055 LLVM_DEBUG(printCandidateDecision(Cand, TryCand));
1056 PickedPending = FromPending;
1057 Cand.setBest(TryCand);
1058 } else {
1059 LLVM_DEBUG(printCandidateDecision(TryCand, Cand));
1060 }
1061 }
1062 };
1063
1064 LLVM_DEBUG(dbgs() << "Available Q:\n");
1065 EvaluateQueue(Zone.Available, /*FromPending=*/false);
1066
1067 LLVM_DEBUG(dbgs() << "Pending Q:\n");
1068 EvaluateQueue(Zone.Pending, /*FromPending=*/true);
1069}
1070
1071#ifndef NDEBUG
1073 SchedCandidate &Cand) {
1074 const SIInstrInfo *SII = static_cast<const SIInstrInfo *>(DAG->TII);
1075 unsigned Cycle = IsTopNode ? Top.getCurrCycle() : Bot.getCurrCycle();
1076
1077 dbgs() << "=== Pick @ Cycle " << Cycle << " ===\n";
1078
1079 const InstructionFlavor Flavor = classifyFlavor(*SU->getInstr(), *SII);
1080 dbgs() << "Picked: " << *SU << " ";
1081 SU->getInstr()->print(dbgs(), /*IsStandalone=*/true, /*SkipOpers=*/false,
1082 /*SkipDebugLoc=*/true);
1083 dbgs() << " [" << getFlavorName(Flavor) << "]\n";
1084
1085 dbgs() << " Reason: ";
1088 else if (Cand.Reason != NoCand)
1090 else
1091 dbgs() << "Unknown";
1092 dbgs() << "\n\n";
1093
1095}
1096#endif
1097
1099 SchedCandidate &TryCand,
1100 SchedBoundary *Zone) {
1101 // Initialize the candidate if needed.
1102 if (!Cand.isValid()) {
1103 TryCand.Reason = FirstValid;
1104 return true;
1105 }
1106
1107 // Bias PhysReg Defs and copies to their uses and defined respectively.
1108 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
1109 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
1110 return TryCand.Reason != NoCand;
1111
1112 // Avoid exceeding the target's limit.
1113 if (DAG->isTrackingPressure() &&
1114 tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
1115 RegExcess, TRI, DAG->MF))
1116 return TryCand.Reason != NoCand;
1117
1118 // We only compare a subset of features when comparing nodes between
1119 // Top and Bottom boundary. Some properties are simply incomparable, in many
1120 // other instances we should only override the other boundary if something
1121 // is a clear good pick on one boundary. Skip heuristics that are more
1122 // "tie-breaking" in nature.
1123 bool SameBoundary = Zone != nullptr;
1124 if (SameBoundary) {
1125 // Compare candidates by the stall they would introduce if
1126 // scheduled in the current cycle.
1127 if (Heurs.tryEffectiveStall(TryCand, Cand, *Zone)) {
1129 return TryCand.Reason != NoCand;
1130 }
1131
1132 if (Heurs.tryMemoryPipeline(TryCand, Cand, *Zone)) {
1134 return TryCand.Reason != NoCand;
1135 }
1136
1137 Heurs.sortHWUIResources();
1138 if (Heurs.tryCriticalResource(TryCand, Cand, Zone)) {
1140 return TryCand.Reason != NoCand;
1141 }
1142
1143 if (Heurs.tryCriticalResourceDependency(TryCand, Cand, Zone)) {
1145 return TryCand.Reason != NoCand;
1146 }
1147 }
1148
1149 // Keep clustered nodes together to encourage downstream peephole
1150 // optimizations which may reduce resource requirements.
1151 //
1152 // This is a best effort to set things up for a post-RA pass. Optimizations
1153 // like generating loads of multiple registers should ideally be done within
1154 // the scheduler pass by combining the loads during DAG postprocessing.
1155 unsigned CandZoneCluster = Cand.AtTop ? TopClusterID : BotClusterID;
1156 unsigned TryCandZoneCluster = TryCand.AtTop ? TopClusterID : BotClusterID;
1157 bool CandIsClusterSucc =
1158 isTheSameCluster(CandZoneCluster, Cand.SU->ParentClusterIdx);
1159 bool TryCandIsClusterSucc =
1160 isTheSameCluster(TryCandZoneCluster, TryCand.SU->ParentClusterIdx);
1161
1162 if (tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
1163 Cluster))
1164 return TryCand.Reason != NoCand;
1165
1166 if (SameBoundary) {
1167 // Weak edges are for clustering and other constraints.
1168 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
1169 getWeakLeft(Cand.SU, Cand.AtTop), TryCand, Cand, Weak))
1170 return TryCand.Reason != NoCand;
1171 }
1172
1173 // Avoid increasing the max pressure of the entire region.
1174 if (DAG->isTrackingPressure() &&
1175 tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax, TryCand,
1176 Cand, RegMax, TRI, DAG->MF))
1177 return TryCand.Reason != NoCand;
1178
1179 if (SameBoundary) {
1180 // Avoid serializing long latency dependence chains.
1181 // For acyclic path limited loops, latency was already checked above.
1182 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
1183 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
1184 return TryCand.Reason != NoCand;
1185
1186 // Fall through to original instruction order.
1187 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum) ||
1188 (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1189 TryCand.Reason = NodeOrder;
1190 return true;
1191 }
1192 }
1193
1194 return false;
1195}
1196
1199 LLVM_DEBUG(dbgs() << "AMDGPU coexec preRA scheduler selected for "
1200 << C->MF->getName() << '\n');
1202 C, std::make_unique<AMDGPUCoExecSchedStrategy>(C));
1205 return DAG;
1206}
1207
1210 LLVM_DEBUG(dbgs() << "AMDGPU nop postRA scheduler selected for "
1211 << C->MF->getName() << '\n');
1212 return new GCNNoopPostScheduleDAG(C);
1213}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static SUnit * pickOnlyChoice(SchedBoundary &Zone)
static CoExecInfo buildMFMACoExecInfo(unsigned SALU, unsigned Mem, unsigned VALU, unsigned MFMA, unsigned PkF32, unsigned Window)
Build MFMA co-exec rules from the first stage at which SALU, memory (DS and VMEM),...
static constexpr unsigned DefaultCoExecVGPRThresholdPercent
Coexecution-focused scheduling strategy for AMDGPU.
AMDGPU Rewrite AGPR Copy MFMA
MachineBasicBlock & MBB
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
IRTranslator LLVM IR MI
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
#define LLVM_DEBUG(...)
Definition Debug.h:119
void initPolicy(MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned NumRegionInstrs) override
Optionally override the per-region scheduling policy.
SUnit * pickNode(bool &IsTopNode) override
Pick the next node to schedule, or return NULL.
void pickNodeFromQueue(SchedBoundary &Zone, const CandPolicy &ZonePolicy, const RegPressureTracker &RPTracker, SchedCandidate &Cand, bool &PickedPending, bool IsBottomUp)
void initialize(ScheduleDAGMI *DAG) override
Initialize the strategy after building the DAG for a new region.
void schedNode(SUnit *SU, bool IsTopNode) override
Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an instruction and updated scheduled/rem...
AMDGPUCoExecSchedStrategy(const MachineSchedContext *C)
void dumpPickSummary(SUnit *SU, bool IsTopNode, SchedCandidate &Cand)
bool tryCandidateCoexec(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
void updateForScheduling(SUnit *SU)
Update the state to reflect that SU is going to be scheduled.
unsigned getCarriedLatency(SUnit *SU)
Estimate the block carried latency from loads for a given SU.
HardwareUnitInfo * getHWUIFromFlavor(AMDGPU::InstructionFlavor Flavor)
Given a Flavor , find the corresponding HardwareUnit.
DenseMap< MachineInstr *, unsigned > CarriedLatencies
StallCosts getStallCosts(SUnit *SU, SchedBoundary &Zone)
void initialize(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel, const TargetRegisterInfo *TRI, const MachineLoopInfo *MLI)
void sortHWUIResources()
Sort the HardwarUnitInfo vector.
void collectRegionSummary()
Walk over the region and collect characteristics for the various heuristics.
bool tryCriticalResource(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary *Zone) const
Check for critical resource consumption.
bool tryCriticalResourceDependency(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary *Zone) const
Check for dependencies of instructions that use prioritized HardwareUnits.
bool tryEffectiveStall(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary &Zone)
AMDGPU::CarriedLatency RegionCarriedLatency
unsigned getHWUICyclesForMI(MachineInstr *MI)
Compute the blocking cycles for the appropriate HardwareUnit given an MI.
SmallVector< HardwareUnitInfo, 8 > HWUInfo
const TargetSchedModel * SchedModel
unsigned getMaxBlockingCycles(const MCSchedClassDesc *SC, const MachineInstr *MI)
bool tryMemoryPipeline(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary &Zone)
Prioritize instructions involved the memory pipeline.
unsigned getStructuralStallCycles(SchedBoundary &Zone, SUnit *SU)
GCNSchedStrategy(const MachineSchedContext *C)
SmallVector< GCNSchedStageID, 4 > SchedStages
std::pair< unsigned, unsigned > getBankedPressure(const GCNRegPressure &RP) const
void schedNode(SUnit *SU, bool IsTopNode) override
Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an instruction and updated scheduled/rem...
std::vector< unsigned > Pressure
void initialize(ScheduleDAGMI *DAG) override
Initialize the strategy after building the DAG for a new region.
void printCandidateDecision(const SchedCandidate &Current, const SchedCandidate &Preferred)
GCNManualDownwardRPTracker DownwardTracker
void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop, const RegPressureTracker &RPTracker, const SIRegisterInfo *SRI, unsigned SGPRPressure, unsigned VGPRPressure, unsigned AGPRPressure, bool IsBottomUp)
MachineSchedPolicy RegionPolicy
const TargetSchedModel * SchedModel
static const char * getReasonStr(GenericSchedulerBase::CandReason Reason)
const TargetRegisterInfo * TRI
SchedCandidate TopCand
Candidate last picked from Top boundary.
ScheduleDAGMILive * DAG
HardwareUnitInfo is a wrapper class which maps to some real hardware resource.
void markScheduled(SUnit *SU, unsigned BlockingCycles)
Update the state for SU being scheduled by removing it from the AllSUs and reducing its BlockingCycle...
SUnit * getNextTargetSU(bool LookDeep=false) const
void insert(SUnit *SU, unsigned BlockingCycles)
Insert the SU into AllSUs and account its BlockingCycles into the TotalCycles.
void finalizeCycles()
After we've collected all the region pressure for this HWUI, correct for any specifics of the behavio...
AMDGPU::InstructionFlavor getType() const
unsigned getBufferAvailableCycle(unsigned CurrCycle)
SUnit * getHigherPriority(SUnit *SU, SUnit *Other) const
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
MachineInstrBundleIterator< MachineInstr > iterator
Representation of each machine instruction.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
MachineOperand class - Representation of each machine instruction operand.
virtual void initPolicy(MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned NumRegionInstrs)
Optionally override the per-region scheduling policy.
Helpers for implementing custom MachineSchedStrategy classes.
Track the current register pressure at some position in the instruction stream, and remember the high...
const std::vector< unsigned > & getRegSetPressureAtPos() const
Get the register set pressure at the current position, which may be less than the pressure across the...
static bool isDS(const MachineInstr &MI)
static bool isVMEM(const MachineInstr &MI)
static bool isSMRD(const MachineInstr &MI)
static bool isSALU(const MachineInstr &MI)
static bool isSWMMAC(const MachineInstr &MI)
const GCNSubtarget & getSubtarget() const
unsigned getBlockingCycles(const MachineInstr &MI) const
static bool isVALU(const MachineInstr &MI, bool AllowLDSDMA)
static bool isTRANS(const MachineInstr &MI)
static bool isWaitcnt(unsigned Opcode)
static bool isMFMA(const MachineInstr &MI)
static bool isWMMA(const MachineInstr &MI)
static bool isLDSDMA(const MachineInstr &MI)
Scheduling unit. This is a node in the scheduling DAG.
unsigned TopReadyCycle
Cycle relative to start when node is ready.
unsigned NodeNum
Entry # of node in the node vector.
unsigned getHeight() const
Returns the height of this node, which is the length of the maximum path down to any node which has n...
unsigned getDepth() const
Returns the depth of this node, which is the length of the maximum path up to any node which has no p...
bool isScheduled
True once scheduled.
unsigned ParentClusterIdx
The parent cluster id.
bool hasReservedResource
Uses a reserved resource.
bool isBottomReady() const
bool isTopReady() const
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
Each Scheduling boundary is associated with ready queues.
LLVM_ABI unsigned getLatencyStallCycles(SUnit *SU)
Get the difference between the given SUnit's ready time and the current cycle.
LLVM_ABI SUnit * pickOnlyChoice()
Call this before applying any other heuristics to the Available queue.
unsigned getCurrCycle() const
Number of cycles to issue the instructions scheduled in this zone.
std::unique_ptr< ScheduleHazardRecognizer > HazardRec
LLVM_ABI std::pair< unsigned, unsigned > getNextResourceCycle(const MCSchedClassDesc *SC, unsigned PIdx, unsigned ReleaseAtCycle, unsigned AcquireAtCycle)
Compute the next cycle at which the given processor resource can be scheduled.
A ScheduleDAG for scheduling lists of MachineInstr.
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
Add a postprocessing step to the DAG builder.
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
static bool isEarlierInstr(SlotIndex A, SlotIndex B)
isEarlierInstr - Return true if A refers to an instruction earlier than B.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
const MCWriteProcResEntry * ProcResIter
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
InstructionFlavor
Classification of instructions by execution characteristics.
constexpr unsigned MaxCoExecStages
Max stages: INT8 16x16x64 = 17 cycles, round up for safety.
CoExecInfo getMFMACoExecInfo(unsigned Opcode, const GCNSubtarget &ST)
Get co-execution info for a gfx942 or gfx950 MFMA instruction.
CoExecMask CoExecMaskT
InstructionFlavor classifyFlavor(const MachineInstr &MI, const SIInstrInfo &SII)
Classify MI into the execution flavor that drives both the scheduler's slot preferences and the hazar...
StringRef getReasonName(AMDGPUSchedReason R)
MFMAVariant
Normalized MFMA or SMFMAC family, selects co-execution rules.
StringRef getFlavorName(InstructionFlavor F)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI int biasPhysReg(const SUnit *SU, bool isTop, bool BiasPRegsExtra=false)
Minimize physical register live ranges.
std::unique_ptr< ScheduleDAGMutation > createAMDGPUBarrierLatencyDAGMutation(MachineFunction *MF)
LLVM_ABI unsigned getWeakLeft(const SUnit *SU, bool isTop)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::unique_ptr< ScheduleDAGMutation > createIGroupLPDAGMutation(AMDGPU::SchedulingPhase Phase)
Phase specifes whether or not this is a reentry into the IGroupLPDAGMutation.
LLVM_ABI bool tryPressure(const PressureChange &TryP, const PressureChange &CandP, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason, const TargetRegisterInfo *TRI, const MachineFunction &MF)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
cl::opt< unsigned, false, VGPRThresholdParser > VGPRThresholdPercentOpt
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
ScheduleDAGInstrs * createGCNNoopPostMachineScheduler(MachineSchedContext *C)
LLVM_ABI bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary &Zone)
LLVM_ABI MISched::Direction getPreRADirection(const MachineFunction &MF)
Returns -misched-prera-direction.
ScheduleDAGInstrs * createGCNCoExecMachineScheduler(MachineSchedContext *C)
bool isTheSameCluster(unsigned A, unsigned B)
Return whether the input cluster ID's are the same and valid.
DWARFExpression::Operation Op
LLVM_ABI bool tryGreater(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
LLVM_ABI bool tryLess(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
Return true if this heuristic determines order.
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
Co-execution characteristics for a multi-cycle instruction.
unsigned TotalWindow
Number of cycles in the co-execution window, counting any trailing vacant stages.
StringRef Pattern
Pattern string for display (e.g., "0EIIEEIIV").
static CoExecInfo build(unsigned UnitOccupancy, unsigned TotalWindow, const char *Pattern)
Build a CoExecInfo from an occupancy and stage pattern.
CoExecSlotInfo Slots[MaxCoExecStages]
Per-stage slot info (capability mask).
Policy for scheduling the next instruction in the candidate's zone.
Store the state used by GenericScheduler heuristics, required for the lifetime of one invocation of p...
LLVM_ABI void initResourceDelta(const ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
Status of an instruction's critical resource consumption.
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition MCSchedule.h:124
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
Definition MCSchedule.h:69
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...