LLVM 24.0.0git
GCNSchedStrategy.cpp
Go to the documentation of this file.
1//===-- GCNSchedStrategy.cpp - GCN Scheduler 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/// This contains a MachineSchedStrategy implementation for maximizing wave
11/// occupancy on GCN hardware.
12///
13/// This pass will apply multiple scheduling stages to the same function.
14/// Regions are first recorded in GCNScheduleDAGMILive::schedule. The actual
15/// entry point for the scheduling of those regions is
16/// GCNScheduleDAGMILive::runSchedStages.
17
18/// Generally, the reason for having multiple scheduling stages is to account
19/// for the kernel-wide effect of register usage on occupancy. Usually, only a
20/// few scheduling regions will have register pressure high enough to limit
21/// occupancy for the kernel, so constraints can be relaxed to improve ILP in
22/// other regions.
23///
24//===----------------------------------------------------------------------===//
25
26#include "GCNSchedStrategy.h"
27#include "AMDGPUIGroupLP.h"
28#include "GCNHazardRecognizer.h"
29#include "GCNRegPressure.h"
32#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/STLExtras.h"
41#include "llvm/MC/LaneBitmask.h"
42#include "llvm/MC/MCSchedule.h"
45
46#define DEBUG_TYPE "machine-scheduler"
47
48using namespace llvm;
49
51 "amdgpu-disable-unclustered-high-rp-reschedule", cl::Hidden,
52 cl::desc("Disable unclustered high register pressure "
53 "reduction scheduling stage."),
54 cl::init(false));
55
57 "amdgpu-disable-clustered-low-occupancy-reschedule", cl::Hidden,
58 cl::desc("Disable clustered low occupancy "
59 "rescheduling for ILP scheduling stage."),
60 cl::init(false));
61
63 "amdgpu-schedule-metric-bias", cl::Hidden,
65 "Sets the bias which adds weight to occupancy vs latency. Set it to "
66 "100 to chase the occupancy only."),
67 cl::init(10));
68
69static cl::opt<bool>
70 RelaxedOcc("amdgpu-schedule-relaxed-occupancy", cl::Hidden,
71 cl::desc("Relax occupancy targets for kernels which are memory "
72 "bound (amdgpu-membound-threshold), or "
73 "Wave Limited (amdgpu-limit-wave-threshold)."),
74 cl::init(false));
75
77 "amdgpu-use-amdgpu-trackers", cl::Hidden,
78 cl::desc("Use the AMDGPU specific RPTrackers during scheduling"),
79 cl::init(false));
80
82 "amdgpu-scheduler-pending-queue-limit", cl::Hidden,
84 "Max (Available+Pending) size to inspect pending queue (0 disables)"),
85 cl::init(256));
86
87#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
88#define DUMP_MAX_REG_PRESSURE
90 "amdgpu-print-max-reg-pressure-regusage-before-scheduler", cl::Hidden,
91 cl::desc("Print a list of live registers along with their def/uses at the "
92 "point of maximum register pressure before scheduling."),
93 cl::init(false));
94
96 "amdgpu-print-max-reg-pressure-regusage-after-scheduler", cl::Hidden,
97 cl::desc("Print a list of live registers along with their def/uses at the "
98 "point of maximum register pressure after scheduling."),
99 cl::init(false));
100#endif
101
103 "amdgpu-disable-rewrite-mfma-form-sched-stage", cl::Hidden,
104 cl::desc("Disable rewrite mfma rewrite scheduling stage"), cl::init(true));
105
106namespace {
107
108struct VGPRThresholdParser : public cl::parser<unsigned> {
109 VGPRThresholdParser(cl::Option &O) : cl::parser<unsigned>(O) {}
110
111 bool parse(cl::Option &O, StringRef ArgName, StringRef Arg, unsigned &Value) {
112 if (Arg.getAsInteger(0, Value))
113 return O.error("'" + Arg + "' value invalid for uint argument!");
114
115 if (Value > 100)
116 return O.error("'" + Arg + "' value must be in the range [0, 100]!");
117
118 return false;
119 }
120};
121
122} // end anonymous namespace
123
125 "amdgpu-vgpr-threshold-percent", cl::Hidden,
126 cl::desc("Percent of VGPR limits that we should use as RP threshold "
127 "during scheduling. We have two limits relevant to scheduling: "
128 "Critical (avoid decreasing occupancy), Excess (avoid spilling). "
129 "This flag scales both limits back by an equal percent: (0 = use "
130 " default calculation, 1-100 = use percentage), default: 0"),
131 cl::init(0));
132
133const unsigned ScheduleMetrics::ScaleFactor = 100;
134
141
144
145 MF = &DAG->MF;
146
147 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
148
150 Context->RegClassInfo->getNumAllocatableRegs(&AMDGPU::SGPR_32RegClass);
152 Context->RegClassInfo->getNumAllocatableRegs(&AMDGPU::VGPR_32RegClass);
153
155 // Set the initial TargetOccupnacy to the maximum occupancy that we can
156 // achieve for this function. This effectively sets a lower bound on the
157 // 'Critical' register limits in the scheduler.
158 // Allow for lower occupancy targets if kernel is wave limited or memory
159 // bound, and using the relaxed occupancy feature.
163 std::min(ST.getMaxNumSGPRs(TargetOccupancy, true), SGPRExcessLimit);
164
165 if (!KnownExcessRP) {
166 VGPRCriticalLimit = std::min(
167 ST.getMaxNumVGPRs(TargetOccupancy, MFI.getDynamicVGPRBlockSize()),
169 } else {
170 // This is similar to ST.getMaxNumVGPRs(TargetOccupancy) result except
171 // returns a reasonably small number for targets with lots of VGPRs, such
172 // as GFX10 and GFX11.
173 LLVM_DEBUG(dbgs() << "Region is known to spill, use alternative "
174 "VGPRCriticalLimit calculation method.\n");
175 unsigned DynamicVGPRBlockSize = MFI.getDynamicVGPRBlockSize();
176 unsigned Granule =
177 AMDGPU::IsaInfo::getVGPRAllocGranule(ST, DynamicVGPRBlockSize);
178 unsigned Addressable =
179 AMDGPU::IsaInfo::getAddressableNumVGPRs(ST, DynamicVGPRBlockSize);
180 unsigned VGPRBudget = alignDown(Addressable / TargetOccupancy, Granule);
181 VGPRBudget = std::max(VGPRBudget, Granule);
182 VGPRCriticalLimit = std::min(VGPRBudget, VGPRExcessLimit);
183 }
184 // Apply VGPR excess threshold percentage if specified.
185 if (VGPRThresholdPercentOpt > 0) {
186 [[maybe_unused]] unsigned OriginalVGPRExcessLimit = VGPRExcessLimit;
187 [[maybe_unused]] unsigned OriginalVGPRCriticalLimit = VGPRCriticalLimit;
191 LLVM_DEBUG(dbgs() << "Applied VGPR excess threshold "
192 << VGPRThresholdPercentOpt << "%, VGPRExcessLimit: "
193 << OriginalVGPRExcessLimit << " -> " << VGPRExcessLimit
194 << ". VGPRCriticalLimit: " << OriginalVGPRCriticalLimit
195 << " -> " << VGPRCriticalLimit << '\n');
196 } else {
200 }
201
202 // Subtract error margin and bias from register limits and avoid overflow.
205 LLVM_DEBUG(dbgs() << "VGPRCriticalLimit = " << VGPRCriticalLimit
206 << ", VGPRExcessLimit = " << VGPRExcessLimit
207 << ", SGPRCriticalLimit = " << SGPRCriticalLimit
208 << ", SGPRExcessLimit = " << SGPRExcessLimit << "\n\n");
209}
210
211/// Checks whether \p SU can use the cached DAG pressure diffs to compute the
212/// current register pressure.
213///
214/// This works for the common case, but it has a few exceptions that have been
215/// observed through trial and error:
216/// - Explicit physical register operands
217/// - Subregister definitions
218///
219/// In both of those cases, PressureDiff doesn't represent the actual pressure,
220/// and querying LiveIntervals through the RegPressureTracker is needed to get
221/// an accurate value.
222///
223/// We should eventually only use PressureDiff for maximum performance, but this
224/// already allows 80% of SUs to take the fast path without changing scheduling
225/// at all. Further changes would either change scheduling, or require a lot
226/// more logic to recover an accurate pressure estimate from the PressureDiffs.
227static bool canUsePressureDiffs(const SUnit &SU) {
228 if (!SU.isInstr())
229 return false;
230
231 // Cannot use pressure diffs for subregister defs or with physregs, it's
232 // imprecise in both cases.
233 for (const auto &Op : SU.getInstr()->operands()) {
234 if (!Op.isReg() || Op.isImplicit())
235 continue;
236 if (Op.getReg().isPhysical() ||
237 (Op.isDef() && Op.getSubReg() != AMDGPU::NoSubRegister))
238 return false;
239 }
240 return true;
241}
242
244 bool AtTop, const RegPressureTracker &RPTracker, SUnit *SU,
245 std::vector<unsigned> &Pressure, std::vector<unsigned> &MaxPressure,
247 ScheduleDAGMI *DAG, const SIRegisterInfo *SRI) {
248 // getDownwardPressure() and getUpwardPressure() make temporary changes to
249 // the tracker, so we need to pass those function a non-const copy.
250 RegPressureTracker &TempTracker = const_cast<RegPressureTracker &>(RPTracker);
251 if (!useGCNTrackers()) {
252 AtTop
253 ? TempTracker.getDownwardPressure(SU->getInstr(), Pressure, MaxPressure)
254 : TempTracker.getUpwardPressure(SU->getInstr(), Pressure, MaxPressure);
255
256 return;
257 }
258
259 // GCNTrackers
260 Pressure.resize(4, 0);
261 MachineInstr *MI = SU->getInstr();
262 GCNRegPressure NewPressure;
263 if (AtTop) {
264 GCNDownwardRPTracker TempDownwardTracker(DownwardTracker);
265 NewPressure = TempDownwardTracker.bumpDownwardPressure(MI, SRI);
266 } else {
267 GCNUpwardRPTracker TempUpwardTracker(UpwardTracker);
268 TempUpwardTracker.recede(*MI);
269 NewPressure = TempUpwardTracker.getPressure();
270 }
271 Pressure[AMDGPU::RegisterPressureSets::SReg_32] = NewPressure.getSGPRNum();
272 Pressure[AMDGPU::RegisterPressureSets::VGPR_32] =
273 NewPressure.getArchVGPRNum();
274 Pressure[AMDGPU::RegisterPressureSets::AGPR_32] = NewPressure.getAGPRNum();
275}
276
278 SUnit *SU) const {
279 // Only implemented for top-down scheduling currently.
280 if (!Zone.isTop() || !SU)
281 return 0;
282
283 MachineInstr *MI = SU->getInstr();
284 unsigned CurrCycle = Zone.getCurrCycle();
285 unsigned Stall = 0;
286
287 // Query SchedModel for resource stalls (unbuffered resources).
288 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
289 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
290 for (const MCWriteProcResEntry &PE :
291 make_range(SchedModel->getWriteProcResBegin(SC),
292 SchedModel->getWriteProcResEnd(SC))) {
293 unsigned NextAvail =
294 Zone.getNextResourceCycle(SC, PE.ProcResourceIdx, PE.ReleaseAtCycle,
295 PE.AcquireAtCycle)
296 .first;
297 if (NextAvail > CurrCycle)
298 Stall = std::max(Stall, NextAvail - CurrCycle);
299 }
300 }
301
302 // Query HazardRecognizer for sequence-dependent hazard penalties.
303 // AMDGPU currently installs GCNHazardRecognizer for MI scheduling only in
304 // the post-RA configuration without vreg liveness.
305 if (!DAG->hasVRegLiveness() && Zone.HazardRec &&
306 Zone.HazardRec->isEnabled()) {
307 auto *HR = static_cast<GCNHazardRecognizer *>(Zone.HazardRec);
308 Stall = std::max(Stall, HR->getHazardWaitStates(MI));
309 }
310
311 return Stall;
312}
313
315 bool AtTop,
316 const RegPressureTracker &RPTracker,
317 const SIRegisterInfo *SRI,
318 unsigned SGPRPressure,
319 unsigned VGPRPressure, bool IsBottomUp) {
320 Cand.SU = SU;
321 Cand.AtTop = AtTop;
322
323 if (!DAG->isTrackingPressure())
324 return;
325
326 Pressure.clear();
327 MaxPressure.clear();
328
329 // We try to use the cached PressureDiffs in the ScheduleDAG whenever
330 // possible over querying the RegPressureTracker.
331 //
332 // RegPressureTracker will make a lot of LIS queries which are very
333 // expensive, it is considered a slow function in this context.
334 //
335 // PressureDiffs are precomputed and cached, and getPressureDiff is just a
336 // trivial lookup into an array. It is pretty much free.
337 //
338 // In EXPENSIVE_CHECKS, we always query RPTracker to verify the results of
339 // PressureDiffs.
340 if (AtTop || !canUsePressureDiffs(*SU) || useGCNTrackers()) {
341 getRegisterPressures(AtTop, RPTracker, SU, Pressure, MaxPressure,
343 } else {
344 // Reserve 4 slots.
345 Pressure.resize(4, 0);
346 Pressure[AMDGPU::RegisterPressureSets::SReg_32] = SGPRPressure;
347 Pressure[AMDGPU::RegisterPressureSets::VGPR_32] = VGPRPressure;
348
349 for (const auto &Diff : DAG->getPressureDiff(SU)) {
350 if (!Diff.isValid())
351 continue;
352 // PressureDiffs is always bottom-up so if we're working top-down we need
353 // to invert its sign.
354 Pressure[Diff.getPSet()] +=
355 (IsBottomUp ? Diff.getUnitInc() : -Diff.getUnitInc());
356 }
357
358#ifdef EXPENSIVE_CHECKS
359 std::vector<unsigned> CheckPressure, CheckMaxPressure;
360 getRegisterPressures(AtTop, RPTracker, SU, CheckPressure, CheckMaxPressure,
362 if (Pressure[AMDGPU::RegisterPressureSets::SReg_32] !=
363 CheckPressure[AMDGPU::RegisterPressureSets::SReg_32] ||
364 Pressure[AMDGPU::RegisterPressureSets::VGPR_32] !=
365 CheckPressure[AMDGPU::RegisterPressureSets::VGPR_32]) {
366 errs() << "Register Pressure is inaccurate when calculated through "
367 "PressureDiff\n"
368 << "SGPR got " << Pressure[AMDGPU::RegisterPressureSets::SReg_32]
369 << ", expected "
370 << CheckPressure[AMDGPU::RegisterPressureSets::SReg_32] << "\n"
371 << "VGPR got " << Pressure[AMDGPU::RegisterPressureSets::VGPR_32]
372 << ", expected "
373 << CheckPressure[AMDGPU::RegisterPressureSets::VGPR_32] << "\n";
374 report_fatal_error("inaccurate register pressure calculation");
375 }
376#endif
377 }
378
379 unsigned NewSGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
380 unsigned NewVGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
381
382 // If two instructions increase the pressure of different register sets
383 // by the same amount, the generic scheduler will prefer to schedule the
384 // instruction that increases the set with the least amount of registers,
385 // which in our case would be SGPRs. This is rarely what we want, so
386 // when we report excess/critical register pressure, we do it either
387 // only for VGPRs or only for SGPRs.
388
389 // FIXME: Better heuristics to determine whether to prefer SGPRs or VGPRs.
390 const unsigned MaxVGPRPressureInc = 16;
391 bool ShouldTrackVGPRs = VGPRPressure + MaxVGPRPressureInc >= VGPRExcessLimit;
392 bool ShouldTrackSGPRs = !ShouldTrackVGPRs && SGPRPressure >= SGPRExcessLimit;
393
394 // FIXME: We have to enter REG-EXCESS before we reach the actual threshold
395 // to increase the likelihood we don't go over the limits. We should improve
396 // the analysis to look through dependencies to find the path with the least
397 // register pressure.
398
399 // We only need to update the RPDelta for instructions that increase register
400 // pressure. Instructions that decrease or keep reg pressure the same will be
401 // marked as RegExcess in tryCandidate() when they are compared with
402 // instructions that increase the register pressure.
403 if (ShouldTrackVGPRs && NewVGPRPressure >= VGPRExcessLimit) {
404 HasHighPressure = true;
405 Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
406 Cand.RPDelta.Excess.setUnitInc(NewVGPRPressure - VGPRExcessLimit);
407 }
408
409 if (ShouldTrackSGPRs && NewSGPRPressure >= SGPRExcessLimit) {
410 HasHighPressure = true;
411 Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::SReg_32);
412 Cand.RPDelta.Excess.setUnitInc(NewSGPRPressure - SGPRExcessLimit);
413 }
414
415 // Register pressure is considered 'CRITICAL' if it is approaching a value
416 // that would reduce the wave occupancy for the execution unit. When
417 // register pressure is 'CRITICAL', increasing SGPR and VGPR pressure both
418 // has the same cost, so we don't need to prefer one over the other.
419
420 int SGPRDelta = NewSGPRPressure - SGPRCriticalLimit;
421 int VGPRDelta = NewVGPRPressure - VGPRCriticalLimit;
422
423 if (SGPRDelta >= 0 || VGPRDelta >= 0) {
424 HasHighPressure = true;
425 if (SGPRDelta > VGPRDelta) {
426 Cand.RPDelta.CriticalMax =
427 PressureChange(AMDGPU::RegisterPressureSets::SReg_32);
428 Cand.RPDelta.CriticalMax.setUnitInc(SGPRDelta);
429 } else {
430 Cand.RPDelta.CriticalMax =
431 PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
432 Cand.RPDelta.CriticalMax.setUnitInc(VGPRDelta);
433 }
434 }
435}
436
438 const TargetSchedModel *SchedModel) {
439 bool HasBufferedModel =
440 SchedModel->hasInstrSchedModel() && SchedModel->getMicroOpBufferSize();
441 unsigned Combined = Zone.Available.size() + Zone.Pending.size();
442 return Combined <= PendingQueueLimit && HasBufferedModel;
443}
444
446 const TargetSchedModel *SchedModel) {
447 // pickOnlyChoice() releases pending instructions and checks for new hazards.
448 SUnit *OnlyChoice = Zone.pickOnlyChoice();
449 if (!shouldCheckPending(Zone, SchedModel) || Zone.Pending.empty())
450 return OnlyChoice;
451
452 return nullptr;
453}
454
456 const SchedCandidate &Preferred) {
457 LLVM_DEBUG({
458 dbgs() << "Prefer:\t\t";
459 DAG->dumpNode(*Preferred.SU);
460
461 if (Current.SU) {
462 dbgs() << "Not:\t";
463 DAG->dumpNode(*Current.SU);
464 }
465
466 dbgs() << "Reason:\t\t";
467 traceCandidate(Preferred);
468 });
469}
470
471// This function is mostly cut and pasted from
472// GenericScheduler::pickNodeFromQueue()
474 const CandPolicy &ZonePolicy,
475 const RegPressureTracker &RPTracker,
476 SchedCandidate &Cand, bool &IsPending,
477 bool IsBottomUp) {
478 const SIRegisterInfo *SRI = static_cast<const SIRegisterInfo *>(TRI);
480 unsigned SGPRPressure = 0;
481 unsigned VGPRPressure = 0;
482 IsPending = false;
483 if (DAG->isTrackingPressure()) {
484 if (!useGCNTrackers()) {
485 SGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
486 VGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
487 } else {
488 GCNRPTracker *T = IsBottomUp
489 ? static_cast<GCNRPTracker *>(&UpwardTracker)
490 : static_cast<GCNRPTracker *>(&DownwardTracker);
491 SGPRPressure = T->getPressure().getSGPRNum();
492 VGPRPressure = T->getPressure().getArchVGPRNum();
493 }
494 }
495 LLVM_DEBUG(dbgs() << "Available Q:\n");
496 ReadyQueue &AQ = Zone.Available;
497 for (SUnit *SU : AQ) {
498
499 SchedCandidate TryCand(ZonePolicy);
500 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, SRI, SGPRPressure,
501 VGPRPressure, IsBottomUp);
502 // Pass SchedBoundary only when comparing nodes from the same boundary.
503 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
504 tryCandidate(Cand, TryCand, ZoneArg);
505 if (TryCand.Reason != NoCand) {
506 // Initialize resource delta if needed in case future heuristics query it.
507 if (TryCand.ResDelta == SchedResourceDelta())
508 TryCand.initResourceDelta(Zone.DAG, SchedModel);
509 LLVM_DEBUG(printCandidateDecision(Cand, TryCand));
510 Cand.setBest(TryCand);
511 } else {
512 printCandidateDecision(TryCand, Cand);
513 }
514 }
515
516 if (!shouldCheckPending(Zone, SchedModel))
517 return;
518
519 LLVM_DEBUG(dbgs() << "Pending Q:\n");
520 ReadyQueue &PQ = Zone.Pending;
521 for (SUnit *SU : PQ) {
522
523 SchedCandidate TryCand(ZonePolicy);
524 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, SRI, SGPRPressure,
525 VGPRPressure, IsBottomUp);
526 // Pass SchedBoundary only when comparing nodes from the same boundary.
527 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
528 tryPendingCandidate(Cand, TryCand, ZoneArg);
529 if (TryCand.Reason != NoCand) {
530 // Initialize resource delta if needed in case future heuristics query it.
531 if (TryCand.ResDelta == SchedResourceDelta())
532 TryCand.initResourceDelta(Zone.DAG, SchedModel);
533 LLVM_DEBUG(printCandidateDecision(Cand, TryCand));
534 IsPending = true;
535 Cand.setBest(TryCand);
536 } else {
537 printCandidateDecision(TryCand, Cand);
538 }
539 }
540}
541
542// This function is mostly cut and pasted from
543// GenericScheduler::pickNodeBidirectional()
545 bool &PickedPending) {
546 // Schedule as far as possible in the direction of no choice. This is most
547 // efficient, but also provides the best heuristics for CriticalPSets.
548 if (SUnit *SU = pickOnlyChoice(Bot, SchedModel)) {
549 IsTopNode = false;
550 return SU;
551 }
552 if (SUnit *SU = pickOnlyChoice(Top, SchedModel)) {
553 IsTopNode = true;
554 return SU;
555 }
556 // Set the bottom-up policy based on the state of the current bottom zone
557 // and the instructions outside the zone, including the top zone.
558 CandPolicy BotPolicy;
559 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
560 // Set the top-down policy based on the state of the current top zone and
561 // the instructions outside the zone, including the bottom zone.
562 CandPolicy TopPolicy;
563 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
564
565 bool BotPending = false;
566 // See if BotCand is still valid (because we previously scheduled from Top).
567 LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
568 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
569 BotCand.Policy != BotPolicy) {
570 BotCand.reset(CandPolicy());
571 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand,
572 BotPending,
573 /*IsBottomUp=*/true);
574 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
575 } else {
577#ifndef NDEBUG
578 if (VerifyScheduling) {
579 SchedCandidate TCand;
580 TCand.reset(CandPolicy());
581 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand,
582 BotPending,
583 /*IsBottomUp=*/true);
584 assert(TCand.SU == BotCand.SU &&
585 "Last pick result should correspond to re-picking right now");
586 }
587#endif
588 }
589
590 bool TopPending = false;
591 // Check if the top Q has a better candidate.
592 LLVM_DEBUG(dbgs() << "Picking from Top:\n");
593 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
594 TopCand.Policy != TopPolicy) {
595 TopCand.reset(CandPolicy());
596 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand,
597 TopPending,
598 /*IsBottomUp=*/false);
599 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
600 } else {
602#ifndef NDEBUG
603 if (VerifyScheduling) {
604 SchedCandidate TCand;
605 TCand.reset(CandPolicy());
606 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand,
607 TopPending,
608 /*IsBottomUp=*/false);
609 assert(TCand.SU == TopCand.SU &&
610 "Last pick result should correspond to re-picking right now");
611 }
612#endif
613 }
614
615 // Pick best from BotCand and TopCand.
616 LLVM_DEBUG(dbgs() << "Top Cand: "; traceCandidate(TopCand);
617 dbgs() << "Bot Cand: "; traceCandidate(BotCand););
618 SchedCandidate Cand = BotPending ? TopCand : BotCand;
619 SchedCandidate TryCand = BotPending ? BotCand : TopCand;
620 PickedPending = BotPending && TopPending;
621
622 TryCand.Reason = NoCand;
623 if (BotPending || TopPending) {
624 PickedPending |= tryPendingCandidate(Cand, TopCand, nullptr);
625 } else {
626 tryCandidate(Cand, TryCand, nullptr);
627 }
628
629 if (TryCand.Reason != NoCand) {
630 Cand.setBest(TryCand);
631 }
632
633 LLVM_DEBUG(dbgs() << "Picking: "; traceCandidate(Cand););
634
635 IsTopNode = Cand.AtTop;
636 return Cand.SU;
637}
638
639// This function is mostly cut and pasted from
640// GenericScheduler::pickNode()
642 if (DAG->top() == DAG->bottom()) {
643 assert(Top.Available.empty() && Top.Pending.empty() &&
644 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
645 return nullptr;
646 }
647 bool PickedPending;
648 SUnit *SU;
649 do {
650 PickedPending = false;
651 if (RegionPolicy.OnlyTopDown) {
653 if (!SU) {
654 CandPolicy NoPolicy;
655 TopCand.reset(NoPolicy);
656 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand,
657 PickedPending,
658 /*IsBottomUp=*/false);
659 assert(TopCand.Reason != NoCand && "failed to find a candidate");
660 SU = TopCand.SU;
661 }
662 IsTopNode = true;
663 } else if (RegionPolicy.OnlyBottomUp) {
665 if (!SU) {
666 CandPolicy NoPolicy;
667 BotCand.reset(NoPolicy);
668 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand,
669 PickedPending,
670 /*IsBottomUp=*/true);
671 assert(BotCand.Reason != NoCand && "failed to find a candidate");
672 SU = BotCand.SU;
673 }
674 IsTopNode = false;
675 } else {
676 SU = pickNodeBidirectional(IsTopNode, PickedPending);
677 }
678 } while (SU->isScheduled);
679
680 if (PickedPending) {
681 unsigned ReadyCycle = IsTopNode ? SU->TopReadyCycle : SU->BotReadyCycle;
682 SchedBoundary &Zone = IsTopNode ? Top : Bot;
683 unsigned CurrentCycle = Zone.getCurrCycle();
684 if (ReadyCycle > CurrentCycle)
685 Zone.bumpCycle(ReadyCycle);
686
687 // FIXME: checkHazard() doesn't give information about which cycle the
688 // hazard will resolve so just keep bumping the cycle by 1. This could be
689 // made more efficient if checkHazard() returned more details.
690 while (Zone.checkHazard(SU))
691 Zone.bumpCycle(Zone.getCurrCycle() + 1);
692
693 Zone.releasePending();
694 }
695
696 if (SU->isTopReady())
697 Top.removeReady(SU);
698 if (SU->isBottomReady())
699 Bot.removeReady(SU);
700
701 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
702 << *SU->getInstr());
703 return SU;
704}
705
706void GCNSchedStrategy::schedNode(SUnit *SU, bool IsTopNode) {
707 if (useGCNTrackers()) {
708 MachineInstr *MI = SU->getInstr();
709 IsTopNode ? (void)DownwardTracker.advance(MI, false)
710 : UpwardTracker.recede(*MI);
711 }
712
713 return GenericScheduler::schedNode(SU, IsTopNode);
714}
715
720
723 if (!CurrentStage)
724 CurrentStage = SchedStages.begin();
725 else
726 CurrentStage++;
727
728 return CurrentStage != SchedStages.end();
729}
730
733 return std::next(CurrentStage) != SchedStages.end();
734}
735
737 assert(CurrentStage && std::next(CurrentStage) != SchedStages.end());
738 return *std::next(CurrentStage);
739}
740
742 SchedCandidate &TryCand,
743 SchedBoundary *Zone) const {
744 // Initialize the candidate if needed.
745 if (!Cand.isValid()) {
746 TryCand.Reason = NodeOrder;
747 return true;
748 }
749
750 // Bias PhysReg Defs and copies to their uses and defined respectively.
751 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
752 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
753 return TryCand.Reason != NoCand;
754
755 // Avoid exceeding the target's limit.
756 if (DAG->isTrackingPressure() &&
757 tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
758 RegExcess, TRI, DAG->MF))
759 return TryCand.Reason != NoCand;
760
761 // Avoid increasing the max critical pressure in the scheduled region.
762 if (DAG->isTrackingPressure() &&
764 TryCand, Cand, RegCritical, TRI, DAG->MF))
765 return TryCand.Reason != NoCand;
766
767 bool SameBoundary = Zone != nullptr;
768 if (SameBoundary) {
771 TryCand, Cand, ResourceReduce))
772 return TryCand.Reason != NoCand;
774 Cand.ResDelta.DemandedResources, TryCand, Cand,
776 return TryCand.Reason != NoCand;
777 }
778
779 return false;
780}
781
794
799
801 SchedCandidate &TryCand,
802 SchedBoundary *Zone) const {
803 // Initialize the candidate if needed.
804 if (!Cand.isValid()) {
805 TryCand.Reason = NodeOrder;
806 return true;
807 }
808
809 // Avoid spilling by exceeding the register limit.
810 if (DAG->isTrackingPressure() &&
811 tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
812 RegExcess, TRI, DAG->MF))
813 return TryCand.Reason != NoCand;
814
815 // Bias PhysReg Defs and copies to their uses and defined respectively.
816 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
817 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
818 return TryCand.Reason != NoCand;
819
820 bool SameBoundary = Zone != nullptr;
821 if (SameBoundary) {
822 // Prioritize instructions that read unbuffered resources by stall cycles.
823 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
824 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
825 return TryCand.Reason != NoCand;
826
827 // Avoid critical resource consumption and balance the schedule.
830 TryCand, Cand, ResourceReduce))
831 return TryCand.Reason != NoCand;
833 Cand.ResDelta.DemandedResources, TryCand, Cand,
835 return TryCand.Reason != NoCand;
836
837 // Unconditionally try to reduce latency.
838 if (tryLatency(TryCand, Cand, *Zone))
839 return TryCand.Reason != NoCand;
840
841 // Weak edges are for clustering and other constraints.
842 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
843 getWeakLeft(Cand.SU, Cand.AtTop), TryCand, Cand, Weak))
844 return TryCand.Reason != NoCand;
845 }
846
847 // Keep clustered nodes together to encourage downstream peephole
848 // optimizations which may reduce resource requirements.
849 //
850 // This is a best effort to set things up for a post-RA pass. Optimizations
851 // like generating loads of multiple registers should ideally be done within
852 // the scheduler pass by combining the loads during DAG postprocessing.
853 unsigned CandZoneCluster = Cand.AtTop ? TopClusterID : BotClusterID;
854 unsigned TryCandZoneCluster = TryCand.AtTop ? TopClusterID : BotClusterID;
855 bool CandIsClusterSucc =
856 isTheSameCluster(CandZoneCluster, Cand.SU->ParentClusterIdx);
857 bool TryCandIsClusterSucc =
858 isTheSameCluster(TryCandZoneCluster, TryCand.SU->ParentClusterIdx);
859 if (tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
860 Cluster))
861 return TryCand.Reason != NoCand;
862
863 // Avoid increasing the max critical pressure in the scheduled region.
864 if (DAG->isTrackingPressure() &&
866 TryCand, Cand, RegCritical, TRI, DAG->MF))
867 return TryCand.Reason != NoCand;
868
869 // Avoid increasing the max pressure of the entire region.
870 if (DAG->isTrackingPressure() &&
871 tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax, TryCand,
872 Cand, RegMax, TRI, DAG->MF))
873 return TryCand.Reason != NoCand;
874
875 if (SameBoundary) {
876 // Fall through to original instruction order.
877 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum) ||
878 (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
879 TryCand.Reason = NodeOrder;
880 return true;
881 }
882 }
883 return false;
884}
885
891
892/// GCNMaxMemoryClauseSchedStrategy tries best to clause memory instructions as
893/// much as possible. This is achieved by:
894// 1. Prioritize clustered operations before stall latency heuristic.
895// 2. Prioritize long-latency-load before stall latency heuristic.
896///
897/// \param Cand provides the policy and current best candidate.
898/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
899/// \param Zone describes the scheduled zone that we are extending, or nullptr
900/// if Cand is from a different zone than TryCand.
901/// \return \c true if TryCand is better than Cand (Reason is NOT NoCand)
903 SchedCandidate &TryCand,
904 SchedBoundary *Zone) const {
905 // Initialize the candidate if needed.
906 if (!Cand.isValid()) {
907 TryCand.Reason = NodeOrder;
908 return true;
909 }
910
911 // Bias PhysReg Defs and copies to their uses and defined respectively.
912 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
913 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
914 return TryCand.Reason != NoCand;
915
916 if (DAG->isTrackingPressure()) {
917 // Avoid exceeding the target's limit.
918 if (tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
919 RegExcess, TRI, DAG->MF))
920 return TryCand.Reason != NoCand;
921
922 // Avoid increasing the max critical pressure in the scheduled region.
924 TryCand, Cand, RegCritical, TRI, DAG->MF))
925 return TryCand.Reason != NoCand;
926 }
927
928 // MaxMemoryClause-specific: We prioritize clustered instructions as we would
929 // get more benefit from clausing these memory instructions.
930 unsigned CandZoneCluster = Cand.AtTop ? TopClusterID : BotClusterID;
931 unsigned TryCandZoneCluster = TryCand.AtTop ? TopClusterID : BotClusterID;
932 bool CandIsClusterSucc =
933 isTheSameCluster(CandZoneCluster, Cand.SU->ParentClusterIdx);
934 bool TryCandIsClusterSucc =
935 isTheSameCluster(TryCandZoneCluster, TryCand.SU->ParentClusterIdx);
936 if (tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
937 Cluster))
938 return TryCand.Reason != NoCand;
939
940 // We only compare a subset of features when comparing nodes between
941 // Top and Bottom boundary. Some properties are simply incomparable, in many
942 // other instances we should only override the other boundary if something
943 // is a clear good pick on one boundary. Skip heuristics that are more
944 // "tie-breaking" in nature.
945 bool SameBoundary = Zone != nullptr;
946 if (SameBoundary) {
947 // For loops that are acyclic path limited, aggressively schedule for
948 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
949 // heuristics to take precedence.
950 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
951 tryLatency(TryCand, Cand, *Zone))
952 return TryCand.Reason != NoCand;
953
954 // MaxMemoryClause-specific: Prioritize long latency memory load
955 // instructions in top-bottom order to hide more latency. The mayLoad check
956 // is used to exclude store-like instructions, which we do not want to
957 // scheduler them too early.
958 bool TryMayLoad =
959 TryCand.SU->isInstr() && TryCand.SU->getInstr()->mayLoad();
960 bool CandMayLoad = Cand.SU->isInstr() && Cand.SU->getInstr()->mayLoad();
961
962 if (TryMayLoad || CandMayLoad) {
963 bool TryLongLatency =
964 TryCand.SU->Latency > 10 * Cand.SU->Latency && TryMayLoad;
965 bool CandLongLatency =
966 10 * TryCand.SU->Latency < Cand.SU->Latency && CandMayLoad;
967
968 if (tryGreater(Zone->isTop() ? TryLongLatency : CandLongLatency,
969 Zone->isTop() ? CandLongLatency : TryLongLatency, TryCand,
970 Cand, Stall))
971 return TryCand.Reason != NoCand;
972 }
973 // Prioritize instructions that read unbuffered resources by stall cycles.
974 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
975 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
976 return TryCand.Reason != NoCand;
977 }
978
979 if (SameBoundary) {
980 // Weak edges are for clustering and other constraints.
981 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
982 getWeakLeft(Cand.SU, Cand.AtTop), TryCand, Cand, Weak))
983 return TryCand.Reason != NoCand;
984 }
985
986 // Avoid increasing the max pressure of the entire region.
987 if (DAG->isTrackingPressure() &&
988 tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax, TryCand,
989 Cand, RegMax, TRI, DAG->MF))
990 return TryCand.Reason != NoCand;
991
992 if (SameBoundary) {
993 // Avoid critical resource consumption and balance the schedule.
996 TryCand, Cand, ResourceReduce))
997 return TryCand.Reason != NoCand;
999 Cand.ResDelta.DemandedResources, TryCand, Cand,
1001 return TryCand.Reason != NoCand;
1002
1003 // Avoid serializing long latency dependence chains.
1004 // For acyclic path limited loops, latency was already checked above.
1005 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
1006 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
1007 return TryCand.Reason != NoCand;
1008
1009 // Fall through to original instruction order.
1010 if (Zone->isTop() == (TryCand.SU->NodeNum < Cand.SU->NodeNum)) {
1011 assert(TryCand.SU->NodeNum != Cand.SU->NodeNum);
1012 TryCand.Reason = NodeOrder;
1013 return true;
1014 }
1015 }
1016
1017 return false;
1018}
1019
1021 MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S)
1022 : ScheduleDAGMILive(C, std::move(S)), ST(MF.getSubtarget<GCNSubtarget>()),
1023 MFI(*MF.getInfo<SIMachineFunctionInfo>()),
1024 StartingOccupancy(MFI.getOccupancy()), MinOccupancy(StartingOccupancy),
1025 RegionLiveOuts(this, /*IsLiveOut=*/true) {
1026
1027 // We want regions with a single MI to be scheduled so that we can reason
1028 // about them correctly during scheduling stages that move MIs between regions
1029 // (e.g., rematerialization).
1031 LLVM_DEBUG(dbgs() << "Starting occupancy is " << StartingOccupancy << ".\n");
1032 if (RelaxedOcc) {
1033 MinOccupancy = std::min(MFI.getMinAllowedOccupancy(), StartingOccupancy);
1034 if (MinOccupancy != StartingOccupancy)
1035 LLVM_DEBUG(dbgs() << "Allowing Occupancy drops to " << MinOccupancy
1036 << ".\n");
1037 }
1038}
1039
1040std::unique_ptr<GCNSchedStage>
1041GCNScheduleDAGMILive::createSchedStage(GCNSchedStageID SchedStageID) {
1042 switch (SchedStageID) {
1044 return std::make_unique<OccInitialScheduleStage>(SchedStageID, *this);
1046 return std::make_unique<RewriteMFMAFormStage>(SchedStageID, *this);
1048 return std::make_unique<UnclusteredHighRPStage>(SchedStageID, *this);
1050 return std::make_unique<ClusteredLowOccStage>(SchedStageID, *this);
1052 return std::make_unique<PreRARematStage>(SchedStageID, *this);
1054 return std::make_unique<ILPInitialScheduleStage>(SchedStageID, *this);
1056 return std::make_unique<MemoryClauseInitialScheduleStage>(SchedStageID,
1057 *this);
1058 }
1059
1060 llvm_unreachable("Unknown SchedStageID.");
1061}
1062
1064 // Collect all scheduling regions. The actual scheduling is performed in
1065 // GCNScheduleDAGMILive::finalizeSchedule.
1066 Regions.push_back(std::pair(RegionBegin, RegionEnd));
1067}
1068
1070GCNScheduleDAGMILive::getRealRegPressure(unsigned RegionIdx) const {
1071 if (Regions[RegionIdx].first == Regions[RegionIdx].second)
1072 return llvm::getRegPressure(MRI, LiveIns[RegionIdx]);
1074 RPTracker.advance(Regions[RegionIdx].first, Regions[RegionIdx].second,
1075 &LiveIns[RegionIdx]);
1076 return RPTracker.moveMaxPressure();
1077}
1078
1080 MachineBasicBlock::iterator RegionEnd) {
1081 assert(RegionBegin != RegionEnd && "Region must not be empty");
1082 return &*skipDebugInstructionsBackward(std::prev(RegionEnd), RegionBegin);
1083}
1084
1085void GCNScheduleDAGMILive::computeBlockPressure(unsigned RegionIdx,
1086 const MachineBasicBlock *MBB) {
1087 GCNDownwardRPTracker RPTracker(*LIS);
1088
1089 // If the block has the only successor then live-ins of that successor are
1090 // live-outs of the current block. We can reuse calculated live set if the
1091 // successor will be sent to scheduling past current block.
1092
1093 // However, due to the bug in LiveInterval analysis it may happen that two
1094 // predecessors of the same successor block have different lane bitmasks for
1095 // a live-out register. Workaround that by sticking to one-to-one relationship
1096 // i.e. one predecessor with one successor block.
1097 const MachineBasicBlock *OnlySucc = nullptr;
1098 if (MBB->succ_size() == 1) {
1099 auto *Candidate = *MBB->succ_begin();
1100 if (!Candidate->empty() && Candidate->pred_size() == 1) {
1101 SlotIndexes *Ind = LIS->getSlotIndexes();
1102 if (Ind->getMBBStartIdx(MBB) < Ind->getMBBStartIdx(Candidate))
1103 OnlySucc = Candidate;
1104 }
1105 }
1106
1107 // Scheduler sends regions from the end of the block upwards.
1108 size_t CurRegion = RegionIdx;
1109 for (size_t E = Regions.size(); CurRegion != E; ++CurRegion)
1110 if (Regions[CurRegion].first->getParent() != MBB)
1111 break;
1112 --CurRegion;
1113
1114 auto I = MBB->begin();
1115 auto LiveInIt = MBBLiveIns.find(MBB);
1116 auto &Rgn = Regions[CurRegion];
1117 auto *NonDbgMI = &*skipDebugInstructionsForward(Rgn.first, Rgn.second);
1118 if (LiveInIt != MBBLiveIns.end()) {
1119 auto LiveIn = std::move(LiveInIt->second);
1120 RPTracker.reset(*MBB->begin(), MBB->end(), &LiveIn);
1121 MBBLiveIns.erase(LiveInIt);
1122 } else {
1123 I = Rgn.first;
1124 auto LRS = BBLiveInMap.lookup(NonDbgMI);
1125#ifdef EXPENSIVE_CHECKS
1126 assert(isEqual(getLiveRegsBefore(*NonDbgMI, *LIS), LRS));
1127#endif
1128 RPTracker.reset(*I, I->getParent()->end(), &LRS);
1129 }
1130
1131 for (;;) {
1132 I = RPTracker.getNext();
1133
1134 if (Regions[CurRegion].first == I || NonDbgMI == I) {
1135 LiveIns[CurRegion] = RPTracker.getLiveRegs();
1136 RPTracker.clearMaxPressure();
1137 }
1138
1139 if (Regions[CurRegion].second == I) {
1140 Pressure[CurRegion] = RPTracker.moveMaxPressure();
1141 if (CurRegion-- == RegionIdx)
1142 break;
1143 auto &Rgn = Regions[CurRegion];
1144 NonDbgMI = &*skipDebugInstructionsForward(Rgn.first, Rgn.second);
1145 }
1146 RPTracker.advanceBeforeNext();
1147 RPTracker.advanceToNext();
1148 }
1149
1150 if (OnlySucc) {
1151 if (I != MBB->end()) {
1152 RPTracker.advanceBeforeNext();
1153 RPTracker.advanceToNext();
1154 RPTracker.advance(MBB->end());
1155 }
1156 MBBLiveIns[OnlySucc] = RPTracker.moveLiveRegs();
1157 }
1158}
1159
1161GCNScheduleDAGMILive::getRegionLiveInMap() const {
1162 assert(!Regions.empty());
1163 std::vector<MachineInstr *> RegionFirstMIs;
1164 RegionFirstMIs.reserve(Regions.size());
1165 for (auto &[RegionBegin, RegionEnd] : reverse(Regions))
1166 RegionFirstMIs.push_back(
1168
1169 return getLiveRegMap(RegionFirstMIs, /*After=*/false, *LIS);
1170}
1171
1173GCNScheduleDAGMILive::getRegionLiveOutMap() const {
1174 assert(!Regions.empty());
1175 std::vector<MachineInstr *> RegionLastMIs;
1176 RegionLastMIs.reserve(Regions.size());
1177 for (auto &[RegionBegin, RegionEnd] : reverse(Regions)) {
1178 // Skip empty regions.
1179 if (RegionBegin == RegionEnd)
1180 continue;
1181 RegionLastMIs.push_back(getLastMIForRegion(RegionBegin, RegionEnd));
1182 }
1183 return getLiveRegMap(RegionLastMIs, /*After=*/true, *LIS);
1184}
1185
1187 IdxToInstruction.clear();
1188
1189 RegionLiveRegMap =
1190 IsLiveOut ? DAG->getRegionLiveOutMap() : DAG->getRegionLiveInMap();
1191 for (unsigned I = 0; I < DAG->Regions.size(); I++) {
1192 auto &[RegionBegin, RegionEnd] = DAG->Regions[I];
1193 // Skip empty regions.
1194 if (RegionBegin == RegionEnd)
1195 continue;
1196 MachineInstr *RegionKey =
1197 IsLiveOut ? getLastMIForRegion(RegionBegin, RegionEnd) : &*RegionBegin;
1198 IdxToInstruction[I] = RegionKey;
1199 }
1200}
1201
1203 // Start actual scheduling here. This function is called by the base
1204 // MachineScheduler after all regions have been recorded by
1205 // GCNScheduleDAGMILive::schedule().
1206 LiveIns.resize(Regions.size());
1207 Pressure.resize(Regions.size());
1208 RegionsWithHighRP.resize(Regions.size());
1209 RegionsWithExcessRP.resize(Regions.size());
1210 RegionsWithIGLPInstrs.resize(Regions.size());
1211 RegionsWithHighRP.reset();
1212 RegionsWithExcessRP.reset();
1213 RegionsWithIGLPInstrs.reset();
1214
1215 runSchedStages();
1216}
1217
1218void GCNScheduleDAGMILive::runSchedStages() {
1219 LLVM_DEBUG(dbgs() << "All regions recorded, starting actual scheduling.\n");
1220
1221 GCNSchedStrategy &S = static_cast<GCNSchedStrategy &>(*SchedImpl);
1222 if (!Regions.empty()) {
1223 BBLiveInMap = getRegionLiveInMap();
1224 if (S.useGCNTrackers())
1225 RegionLiveOuts.buildLiveRegMap();
1226 }
1227
1228#ifdef DUMP_MAX_REG_PRESSURE
1232 LIS->dump();
1233 }
1234#endif
1235
1236 while (S.advanceStage()) {
1237 auto Stage = createSchedStage(S.getCurrentStage());
1238 if (!Stage->initGCNSchedStage())
1239 continue;
1240
1241 for (auto Region : Regions) {
1242 RegionBegin = Region.first;
1243 RegionEnd = Region.second;
1244 // Setup for scheduling the region and check whether it should be skipped.
1245 if (!Stage->initGCNRegion()) {
1246 Stage->advanceRegion();
1247 exitRegion();
1248 continue;
1249 }
1250
1251 if (S.useGCNTrackers()) {
1252 const unsigned RegionIdx = Stage->getRegionIdx();
1253 S.getDownwardTracker()->reset(MRI, LiveIns[RegionIdx]);
1255 MRI, RegionLiveOuts.getLiveRegsForRegionIdx(RegionIdx));
1256 }
1257
1259 Stage->finalizeGCNRegion();
1260 Stage->advanceRegion();
1261 exitRegion();
1262 }
1263
1264 Stage->finalizeGCNSchedStage();
1265 }
1266
1267#ifdef DUMP_MAX_REG_PRESSURE
1271 LIS->dump();
1272 }
1273#endif
1274}
1275
1276#ifndef NDEBUG
1278 switch (StageID) {
1280 OS << "Max Occupancy Initial Schedule";
1281 break;
1283 OS << "Instruction Rewriting Reschedule";
1284 break;
1286 OS << "Unclustered High Register Pressure Reschedule";
1287 break;
1289 OS << "Clustered Low Occupancy Reschedule";
1290 break;
1292 OS << "Pre-RA Rematerialize";
1293 break;
1295 OS << "Max ILP Initial Schedule";
1296 break;
1298 OS << "Max memory clause Initial Schedule";
1299 break;
1300 }
1301
1302 return OS;
1303}
1304#endif
1305
1309
1311 if (!DAG.LIS)
1312 return false;
1313
1314 LLVM_DEBUG(dbgs() << "Starting scheduling stage: " << StageID << "\n");
1315 return true;
1316}
1317
1318void RewriteMFMAFormStage::findReachingDefs(
1319 MachineOperand &UseMO, LiveIntervals *LIS,
1320 SmallVectorImpl<SlotIndex> &DefIdxs) {
1321 MachineInstr *UseMI = UseMO.getParent();
1322 LiveInterval &UseLI = LIS->getInterval(UseMO.getReg());
1323 VNInfo *VNI = UseLI.getVNInfoAt(LIS->getInstructionIndex(*UseMI));
1324
1325 // If the def is not a PHI, then it must be the only reaching def.
1326 if (!VNI->isPHIDef()) {
1327 DefIdxs.push_back(VNI->def);
1328 return;
1329 }
1330
1331 SmallPtrSet<MachineBasicBlock *, 8> Visited = {UseMI->getParent()};
1333
1334 // Mark the predecessor blocks for traversal
1335 for (MachineBasicBlock *PredMBB : UseMI->getParent()->predecessors()) {
1336 Worklist.push_back(PredMBB);
1337 Visited.insert(PredMBB);
1338 }
1339
1340 while (!Worklist.empty()) {
1341 MachineBasicBlock *CurrMBB = Worklist.pop_back_val();
1342
1343 SlotIndex CurrMBBEnd = LIS->getMBBEndIdx(CurrMBB);
1344 VNInfo *VNI = UseLI.getVNInfoAt(CurrMBBEnd.getPrevSlot());
1345
1346 MachineBasicBlock *DefMBB = LIS->getMBBFromIndex(VNI->def);
1347
1348 // If there is a def in this block, then add it to the list. This is the
1349 // reaching def of this path.
1350 if (!VNI->isPHIDef()) {
1351 DefIdxs.push_back(VNI->def);
1352 continue;
1353 }
1354
1355 for (MachineBasicBlock *PredMBB : DefMBB->predecessors()) {
1356 if (Visited.insert(PredMBB).second)
1357 Worklist.push_back(PredMBB);
1358 }
1359 }
1360}
1361
1362void RewriteMFMAFormStage::findReachingUses(
1363 const MachineInstr *DefMI, LiveIntervals *LIS,
1364 SmallVectorImpl<MachineOperand *> &ReachingUses) {
1365 SlotIndex DefIdx = LIS->getInstructionIndex(*DefMI);
1366 for (MachineOperand &UseMO :
1367 DAG.MRI.use_nodbg_operands(DefMI->getOperand(0).getReg())) {
1368 SmallVector<SlotIndex, 8> ReachingDefIndexes;
1369 findReachingDefs(UseMO, LIS, ReachingDefIndexes);
1370
1371 // If we find a use that contains this DefMI in its reachingDefs, then it is
1372 // a reaching use.
1373 if (any_of(ReachingDefIndexes, [DefIdx](SlotIndex RDIdx) {
1374 return SlotIndex::isSameInstr(RDIdx, DefIdx);
1375 }))
1376 ReachingUses.push_back(&UseMO);
1377 }
1378}
1379
1381 // We only need to run this pass if the architecture supports AGPRs.
1382 // Additionally, we don't use AGPRs at occupancy levels above 1 so there
1383 // is no need for this pass in that case, either.
1384 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1385 if (!ST.hasGFX90AInsts() || MFI.getMinWavesPerEU() > 1)
1386 return false;
1387
1388 RegionsWithExcessArchVGPR.resize(DAG.Regions.size());
1389 RegionsWithExcessArchVGPR.reset();
1390 for (unsigned Region = 0; Region < DAG.Regions.size(); Region++) {
1392 if (PressureBefore.getArchVGPRNum() > ST.getAddressableNumArchVGPRs())
1393 RegionsWithExcessArchVGPR[Region] = true;
1394 }
1395
1396 if (RegionsWithExcessArchVGPR.none())
1397 return false;
1398
1399 TII = ST.getInstrInfo();
1400 SRI = ST.getRegisterInfo();
1401
1402 std::vector<std::pair<MachineInstr *, unsigned>> RewriteCands;
1405
1406 if (!initHeuristics(RewriteCands, CopyForUse, CopyForDef))
1407 return false;
1408
1409 int64_t Cost = getRewriteCost(RewriteCands, CopyForUse, CopyForDef);
1410
1411 // If we haven't found the beneficial conditions, prefer the VGPR form which
1412 // may result in less cross RC copies.
1413 if (Cost > 0)
1414 return false;
1415
1416 return rewrite(RewriteCands);
1417}
1418
1421 return false;
1422
1424 return false;
1425
1426 if (DAG.RegionsWithHighRP.none() && DAG.RegionsWithExcessRP.none())
1427 return false;
1428
1429 SavedMutations.swap(DAG.Mutations);
1430 DAG.addMutation(
1432
1433 InitialOccupancy = DAG.MinOccupancy;
1434 // Aggressively try to reduce register pressure in the unclustered high RP
1435 // stage. Temporarily increase occupancy target in the region.
1436 TempTargetOccupancy = MFI.getMaxWavesPerEU() > DAG.MinOccupancy
1437 ? InitialOccupancy + 1
1438 : InitialOccupancy;
1439 IsAnyRegionScheduled = false;
1440 S.SGPRLimitBias = S.HighRPSGPRBias;
1441 S.VGPRLimitBias = S.HighRPVGPRBias;
1442
1443 LLVM_DEBUG(
1444 dbgs()
1445 << "Retrying function scheduling without clustering. "
1446 "Aggressively try to reduce register pressure to achieve occupancy "
1447 << TempTargetOccupancy << ".\n");
1448
1449 return true;
1450}
1451
1454 return false;
1455
1457 return false;
1458
1459 // Don't bother trying to improve ILP in lower RP regions if occupancy has not
1460 // been dropped. All regions will have already been scheduled with the ideal
1461 // occupancy targets.
1462 if (DAG.StartingOccupancy <= DAG.MinOccupancy)
1463 return false;
1464
1465 LLVM_DEBUG(
1466 dbgs() << "Retrying function scheduling with lowest recorded occupancy "
1467 << DAG.MinOccupancy << ".\n");
1468 return true;
1469}
1470
1471/// Allows to easily filter for this stage's debug output.
1472#define REMAT_PREFIX "[PreRARemat] "
1473#define REMAT_DEBUG(X) LLVM_DEBUG(dbgs() << REMAT_PREFIX; X;)
1474
1475#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1476Printable PreRARematStage::ScoredRemat::print() const {
1477 return Printable([&](raw_ostream &OS) {
1478 OS << '(' << MaxFreq << ", " << FreqDiff << ", " << RegionImpact << ')';
1479 });
1480}
1481#endif
1482
1484 // FIXME: This pass will invalidate cached BBLiveInMap and MBBLiveIns for
1485 // regions inbetween the defs and region we sinked the def to. Will need to be
1486 // fixed if there is another pass after this pass.
1487 assert(!S.hasNextStage());
1488
1489 if (!GCNSchedStage::initGCNSchedStage() || DAG.Regions.size() <= 1)
1490 return false;
1491
1492#ifndef NDEBUG
1493 auto PrintTargetRegions = [&]() -> void {
1494 if (TargetRegions.none()) {
1495 dbgs() << REMAT_PREFIX << "No target regions\n";
1496 return;
1497 }
1498 dbgs() << REMAT_PREFIX << "Target regions:\n";
1499 for (unsigned I : TargetRegions.set_bits())
1500 dbgs() << REMAT_PREFIX << " [" << I << "] " << RPTargets[I] << '\n';
1501 };
1502#endif
1503
1504 // Set an objective for the stage based on current RP in each region.
1505 REMAT_DEBUG({
1506 dbgs() << "Analyzing ";
1507 MF.getFunction().printAsOperand(dbgs(), false);
1508 dbgs() << ": ";
1509 });
1510 if (!setObjective()) {
1511 LLVM_DEBUG(dbgs() << "no objective to achieve, occupancy is maximal at "
1512 << MFI.getMaxWavesPerEU() << '\n');
1513 return false;
1514 }
1515 LLVM_DEBUG({
1516 if (TargetOcc) {
1517 dbgs() << "increase occupancy from " << *TargetOcc - 1 << '\n';
1518 } else {
1519 dbgs() << "reduce spilling (minimum target occupancy is "
1520 << MFI.getMinWavesPerEU() << ")\n";
1521 }
1522 PrintTargetRegions();
1523 });
1524
1525 // We need up-to-date live-out info. to query live-out register masks in
1526 // regions containing rematerializable instructions.
1527 DAG.RegionLiveOuts.buildLiveRegMap();
1528
1529 if (!Remater.analyze()) {
1530 REMAT_DEBUG(dbgs() << "No rematerializable registers\n");
1531 return false;
1532 }
1533 const ScoredRemat::FreqInfo FreqInfo(MF, DAG);
1534
1535 // Set of registers already marked for potential remterialization; used to
1536 // avoid rematerialization chains.
1537 SmallSet<Register, 4> MarkedRegs;
1538
1539 // Collect candidates. We have more restrictions on what we can track here
1540 // compared to the rematerializer.
1541 SmallVector<ScoredRemat, 8> Candidates;
1542 SmallVector<unsigned> CandidateOrder;
1543 for (unsigned RegIdx = 0, E = Remater.getNumRegs(); RegIdx < E; ++RegIdx) {
1544 const Rematerializer::Reg &CandReg = Remater.getReg(RegIdx);
1545
1546 // Single user only.
1547 unsigned NumUsers = 0;
1548 for (const auto &[_, RegionUses] : CandReg.Uses)
1549 NumUsers += RegionUses.size();
1550 if (NumUsers != 1)
1551 continue;
1552
1553 // We further filter the registers that we can rematerialize based on our
1554 // current tracking capabilities in the stage. The user cannot itself be
1555 // marked rematerializable, and no register operand of the defining MI can
1556 // be marked rematerializable. We also do not rematerialize an instruction
1557 // if it uses registers that aren't available at its use. This ensures that
1558 // we are not extending any live range while rematerializing.
1559 MachineInstr *UseMI = *CandReg.Uses.begin()->getSecond().begin();
1560 const MachineOperand &UseMO = UseMI->getOperand(0);
1561 if (UseMO.isReg() && MarkedRegs.contains(UseMO.getReg()))
1562 continue;
1563 SlotIndex UseIdx = DAG.LIS->getInstructionIndex(*UseMI).getRegSlot(true);
1564 SlotIndex RefIdx =
1565 DAG.LIS->getInstructionIndex(*CandReg.DefMI).getRegSlot(true);
1566 if (llvm::any_of(CandReg.Dependencies, [&](RegisterIdx DepRegIdx) {
1567 const Rematerializer::Reg &DepReg = Remater.getReg(DepRegIdx);
1568 Register DepDefReg = DepReg.getDefReg();
1569 return MarkedRegs.contains(DepDefReg) ||
1570 !Remater.isRegIdenticalAtUses(DepDefReg, DepReg.Mask, RefIdx,
1571 {UseIdx});
1572 }))
1573 continue;
1574 if (llvm::any_of(Remater.getUnrematableDeps(RegIdx),
1575 [&](const std::pair<Register, LaneBitmask> &RegAndMask) {
1576 const auto &[Reg, Mask] = RegAndMask;
1577 return !Remater.isRegIdenticalAtUses(Reg, Mask, RefIdx,
1578 {UseIdx});
1579 }))
1580 continue;
1581
1582 MarkedRegs.insert(CandReg.getDefReg());
1583 ScoredRemat &Cand = Candidates.emplace_back();
1584 Cand.init(RegIdx, FreqInfo, Remater, DAG);
1585 Cand.update(TargetRegions, RPTargets, FreqInfo, !TargetOcc);
1586 if (!Cand.hasNullScore())
1587 CandidateOrder.push_back(Candidates.size() - 1);
1588 }
1589
1590 if (TargetOcc) {
1591 // Every rematerialization we do here is likely to move the instruction
1592 // into a higher frequency region, increasing the total sum latency of the
1593 // instruction itself. This is acceptable if we are eliminating a spill in
1594 // the process, but when the goal is increasing occupancy we get nothing
1595 // out of rematerialization if occupancy is not increased in the end; in
1596 // such cases we want to roll back the rematerialization.
1597 Rollback = std::make_unique<RollbackSupport>(Remater);
1598 }
1599
1600 // Rematerialize registers in successive rounds until all RP targets are
1601 // satisifed or until we run out of rematerialization candidates.
1602 BitVector RecomputeRP(DAG.Regions.size());
1603 for (;;) {
1604 RecomputeRP.reset();
1605
1606 // Sort candidates in increasing score order.
1607 sort(CandidateOrder, [&](unsigned LHSIndex, unsigned RHSIndex) {
1608 return Candidates[LHSIndex] < Candidates[RHSIndex];
1609 });
1610
1611 REMAT_DEBUG({
1612 dbgs() << "==== NEW REMAT ROUND ====\n"
1613 << REMAT_PREFIX
1614 << "Candidates with non-null score, in rematerialization order:\n";
1615 for (const ScoredRemat &Cand : reverse(Candidates)) {
1616 dbgs() << REMAT_PREFIX << " " << Cand.print() << " | "
1617 << Remater.printRematReg(Cand.RegIdx) << '\n';
1618 }
1619 PrintTargetRegions();
1620 });
1621
1622 // Rematerialize registers in decreasing score order until we estimate
1623 // that all RP targets are satisfied or until rematerialization candidates
1624 // are no longer useful to decrease RP.
1625 while (!CandidateOrder.empty()) {
1626 const ScoredRemat &Cand = Candidates[CandidateOrder.back()];
1627 const Rematerializer::Reg &Reg = Remater.getReg(Cand.RegIdx);
1628
1629 // When previous rematerializations in this round have already satisfied
1630 // RP targets in all regions this rematerialization can impact, we have a
1631 // good indication that our scores have diverged significantly from
1632 // reality, in which case we interrupt this round and re-score. This also
1633 // ensures that every rematerialization we perform is possibly impactful
1634 // in at least one target region.
1635 if (!Cand.maybeBeneficial(TargetRegions, RPTargets)) {
1636 REMAT_DEBUG(dbgs() << "Interrupt round on stale score for "
1637 << Cand.print() << " | "
1638 << Remater.printRematReg(Cand.RegIdx));
1639 break;
1640 }
1641 CandidateOrder.pop_back();
1642
1643#ifdef EXPENSIVE_CHECKS
1644 // All uses are known to be available / live at the remat point. Thus,
1645 // the uses should already be live in to the using region.
1646 for (MachineOperand &MO : Reg.DefMI->operands()) {
1647 if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
1648 continue;
1649
1650 Register UseReg = MO.getReg();
1651 if (!UseReg.isVirtual())
1652 continue;
1653
1654 LiveInterval &LI = DAG.LIS->getInterval(UseReg);
1655 LaneBitmask LM = DAG.MRI.getMaxLaneMaskForVReg(MO.getReg());
1656 if (LI.hasSubRanges() && MO.getSubReg())
1657 LM = DAG.TRI->getSubRegIndexLaneMask(MO.getSubReg());
1658
1659 const unsigned UseRegion = Reg.Uses.begin()->first;
1660 LaneBitmask LiveInMask = DAG.LiveIns[UseRegion].at(UseReg);
1661 LaneBitmask UncoveredLanes = LM & ~(LiveInMask & LM);
1662 // If this register has lanes not covered by the LiveIns, be sure they
1663 // do not map to any subrange. ref:
1664 // machine-scheduler-sink-trivial-remats.mir::omitted_subrange
1665 if (UncoveredLanes.any()) {
1666 assert(LI.hasSubRanges());
1667 for (LiveInterval::SubRange &SR : LI.subranges())
1668 assert((SR.LaneMask & UncoveredLanes).none());
1669 }
1670 }
1671#endif
1672
1673 // Remove the register from all regions where it is a live-in or live-out,
1674 // then rematerialize the register.
1675 REMAT_DEBUG(dbgs() << "** REMAT " << Remater.printRematReg(Cand.RegIdx)
1676 << '\n');
1677 removeFromLiveMaps(Reg.getDefReg(), Cand.LiveIn, Cand.LiveOut);
1678 if (Rollback) {
1679 Rollback->LiveMapUpdates.emplace_back(Cand.RegIdx, Cand.LiveIn,
1680 Cand.LiveOut);
1681 }
1682 Cand.rematerialize(Remater);
1683
1684 // Adjust RP targets. The save is guaranteed in regions in which the
1685 // register is live-through and unused but optimistic in all other regions
1686 // where the register is live.
1687 updateRPTargets(Cand.Live, Cand.RPSave);
1688 RecomputeRP |= Cand.UnpredictableRPSave;
1689 RescheduleRegions |= Cand.Live;
1690 if (!TargetRegions.any()) {
1691 REMAT_DEBUG(dbgs() << "All targets cleared, verifying...\n");
1692 break;
1693 }
1694 }
1695
1696 if (!updateAndVerifyRPTargets(RecomputeRP) && !TargetRegions.any()) {
1697 REMAT_DEBUG(dbgs() << "Objectives achieved!\n");
1698 break;
1699 }
1700
1701 // Update the score of remaining candidates and filter out those that have
1702 // become useless from the vector. Candidates never become useful after
1703 // having been useless for a round, so we can freely drop them without
1704 // losing any future rematerialization opportunity.
1705 unsigned NumUsefulCandidates = 0;
1706 for (unsigned CandIdx : CandidateOrder) {
1707 ScoredRemat &Candidate = Candidates[CandIdx];
1708 Candidate.update(TargetRegions, RPTargets, FreqInfo, !TargetOcc);
1709 if (!Candidate.hasNullScore())
1710 CandidateOrder[NumUsefulCandidates++] = CandIdx;
1711 }
1712 if (NumUsefulCandidates == 0) {
1713 REMAT_DEBUG(dbgs() << "Stop on exhausted rematerialization candidates\n");
1714 break;
1715 }
1716 CandidateOrder.truncate(NumUsefulCandidates);
1717 }
1718
1719 if (RescheduleRegions.none())
1720 return false;
1721
1722 // Commit all pressure changes to the DAG and compute minimum achieved
1723 // occupancy in impacted regions.
1724 REMAT_DEBUG(dbgs() << "==== REMAT RESULTS ====\n");
1725 unsigned DynamicVGPRBlockSize = MFI.getDynamicVGPRBlockSize();
1726 for (unsigned I : RescheduleRegions.set_bits()) {
1727 DAG.Pressure[I] = RPTargets[I].getCurrentRP();
1728 REMAT_DEBUG(dbgs() << '[' << I << "] Achieved occupancy "
1729 << DAG.Pressure[I].getOccupancy(ST, DynamicVGPRBlockSize)
1730 << " (" << RPTargets[I] << ")\n");
1731 }
1732 AchievedOcc = MFI.getMaxWavesPerEU();
1733 for (const GCNRegPressure &RP : DAG.Pressure) {
1734 AchievedOcc =
1735 std::min(AchievedOcc, RP.getOccupancy(ST, DynamicVGPRBlockSize));
1736 }
1737
1738 REMAT_DEBUG({
1739 dbgs() << "Retrying function scheduling with new min. occupancy of "
1740 << AchievedOcc << " from rematerializing (original was "
1741 << DAG.MinOccupancy;
1742 if (TargetOcc)
1743 dbgs() << ", target was " << *TargetOcc;
1744 dbgs() << ")\n";
1745 });
1746
1747 DAG.setTargetOccupancy(getStageTargetOccupancy());
1748 return true;
1749}
1750
1752 DAG.finishBlock();
1753 LLVM_DEBUG(dbgs() << "Ending scheduling stage: " << StageID << "\n");
1754}
1755
1757 SavedMutations.swap(DAG.Mutations);
1758 S.SGPRLimitBias = S.VGPRLimitBias = 0;
1759 if (DAG.MinOccupancy > InitialOccupancy) {
1760 assert(IsAnyRegionScheduled);
1762 << " stage successfully increased occupancy to "
1763 << DAG.MinOccupancy << '\n');
1764 } else if (!IsAnyRegionScheduled) {
1765 assert(DAG.MinOccupancy == InitialOccupancy);
1767 << ": No regions scheduled, min occupancy stays at "
1768 << DAG.MinOccupancy << ", MFI occupancy stays at "
1769 << MFI.getOccupancy() << ".\n");
1770 }
1771
1773}
1774
1776 // Skip empty scheduling region.
1777 if (DAG.begin() == DAG.end())
1778 return false;
1779
1780 // Check whether this new region is also a new block.
1781 if (DAG.RegionBegin->getParent() != CurrentMBB)
1782 setupNewBlock();
1783
1784 unsigned NumRegionInstrs = std::distance(DAG.begin(), DAG.end());
1785 DAG.enterRegion(CurrentMBB, DAG.begin(), DAG.end(), NumRegionInstrs);
1786
1787 // Skip regions with 1 schedulable instruction.
1788 if (DAG.begin() == std::prev(DAG.end()))
1789 return false;
1790
1791 LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
1792 LLVM_DEBUG(dbgs() << MF.getName() << ":" << printMBBReference(*CurrentMBB)
1793 << " " << CurrentMBB->getName()
1794 << "\n From: " << *DAG.begin() << " To: ";
1795 if (DAG.RegionEnd != CurrentMBB->end()) dbgs() << *DAG.RegionEnd;
1796 else dbgs() << "End";
1797 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
1798
1799 // Save original instruction order before scheduling for possible revert.
1800 Unsched.clear();
1801 Unsched.reserve(DAG.NumRegionInstrs);
1804 const SIInstrInfo *SII = static_cast<const SIInstrInfo *>(DAG.TII);
1805 for (auto &I : DAG) {
1806 Unsched.push_back(&I);
1807 if (SII->isIGLPMutationOnly(I.getOpcode()))
1808 DAG.RegionsWithIGLPInstrs[RegionIdx] = true;
1809 }
1810 } else {
1811 for (auto &I : DAG)
1812 Unsched.push_back(&I);
1813 }
1814
1815 PressureBefore = DAG.Pressure[RegionIdx];
1816
1817 LLVM_DEBUG(
1818 dbgs() << "Pressure before scheduling:\nRegion live-ins:"
1819 << print(DAG.LiveIns[RegionIdx], DAG.MRI)
1820 << "Region live-in pressure: "
1821 << print(llvm::getRegPressure(DAG.MRI, DAG.LiveIns[RegionIdx]))
1822 << "Region register pressure: " << print(PressureBefore));
1823
1824 S.HasHighPressure = false;
1825 S.KnownExcessRP = isRegionWithExcessRP();
1826
1827 if (DAG.RegionsWithIGLPInstrs[RegionIdx] &&
1829 SavedMutations.clear();
1830 SavedMutations.swap(DAG.Mutations);
1831 bool IsInitialStage = StageID == GCNSchedStageID::OccInitialSchedule ||
1833 DAG.addMutation(createIGroupLPDAGMutation(
1834 IsInitialStage ? AMDGPU::SchedulingPhase::Initial
1836 }
1837
1838 return true;
1839}
1840
1842 // Only reschedule regions that have excess register pressure (i.e. spilling)
1843 // or had minimum occupancy at the beginning of the stage (as long as
1844 // rescheduling of previous regions did not make occupancy drop back down to
1845 // the initial minimum).
1846 unsigned DynamicVGPRBlockSize = DAG.MFI.getDynamicVGPRBlockSize();
1847 // If no region has been scheduled yet, the DAG has not yet been updated with
1848 // the occupancy target. So retrieve it from the temporary.
1849 unsigned CurrentTargetOccupancy =
1850 IsAnyRegionScheduled ? DAG.MinOccupancy : TempTargetOccupancy;
1851 if (!DAG.RegionsWithExcessRP[RegionIdx] &&
1852 (CurrentTargetOccupancy <= InitialOccupancy ||
1853 DAG.Pressure[RegionIdx].getOccupancy(ST, DynamicVGPRBlockSize) !=
1854 InitialOccupancy))
1855 return false;
1856
1857 bool IsSchedulingThisRegion = GCNSchedStage::initGCNRegion();
1858 // If this is the first region scheduled during this stage, make the target
1859 // occupancy changes in the DAG and MFI.
1860 if (!IsAnyRegionScheduled && IsSchedulingThisRegion) {
1861 IsAnyRegionScheduled = true;
1862 if (MFI.getMaxWavesPerEU() > DAG.MinOccupancy)
1863 DAG.setTargetOccupancy(TempTargetOccupancy);
1864 }
1865 return IsSchedulingThisRegion;
1866}
1867
1869 // We may need to reschedule this region if it wasn't rescheduled in the last
1870 // stage, or if we found it was testing critical register pressure limits in
1871 // the unclustered reschedule stage. The later is because we may not have been
1872 // able to raise the min occupancy in the previous stage so the region may be
1873 // overly constrained even if it was already rescheduled.
1874 if (!DAG.RegionsWithHighRP[RegionIdx])
1875 return false;
1876
1878}
1879
1881 return !RevertAllRegions && RescheduleRegions[RegionIdx] &&
1883}
1884
1886 if (CurrentMBB)
1887 DAG.finishBlock();
1888
1889 CurrentMBB = DAG.RegionBegin->getParent();
1890 DAG.startBlock(CurrentMBB);
1891 // Get real RP for the region if it hasn't be calculated before. After the
1892 // initial schedule stage real RP will be collected after scheduling.
1896 DAG.computeBlockPressure(RegionIdx, CurrentMBB);
1897}
1898
1900 DAG.Regions[RegionIdx] = std::pair(DAG.RegionBegin, DAG.RegionEnd);
1901 if (S.HasHighPressure)
1902 DAG.RegionsWithHighRP[RegionIdx] = true;
1903
1904 // Revert scheduling if we have dropped occupancy or there is some other
1905 // reason that the original schedule is better.
1907
1908 if (DAG.RegionsWithIGLPInstrs[RegionIdx] &&
1910 SavedMutations.swap(DAG.Mutations);
1911}
1912
1915 // When the goal is to increase occupancy, all regions must reach the target
1916 // occupancy for rematerializations to be possibly useful, otherwise we will
1917 // just hurt latency for no benefit. If minimum occupancy drops below the
1918 // target there is no point in trying to re-schedule further regions.
1919 if (!TargetOcc)
1920 return;
1921 RegionReverts.emplace_back(RegionIdx, Unsched, PressureBefore);
1922 if (DAG.MinOccupancy < *TargetOcc) {
1923 REMAT_DEBUG(dbgs() << "Region " << RegionIdx
1924 << " cannot meet occupancy target, interrupting "
1925 "re-scheduling in all regions\n");
1926 RevertAllRegions = true;
1927 }
1928}
1929
1931 // Check the results of scheduling.
1932 PressureAfter = DAG.getRealRegPressure(RegionIdx);
1933
1934 LLVM_DEBUG(dbgs() << "Pressure after scheduling: " << print(PressureAfter));
1935 LLVM_DEBUG(dbgs() << "Region: " << RegionIdx << ".\n");
1936
1937 unsigned DynamicVGPRBlockSize = DAG.MFI.getDynamicVGPRBlockSize();
1938
1939 if (PressureAfter.getSGPRNum() <= S.SGPRCriticalLimit &&
1940 PressureAfter.getVGPRNum(ST.hasGFX90AInsts()) <= S.VGPRCriticalLimit) {
1941 DAG.Pressure[RegionIdx] = PressureAfter;
1942
1943 // Early out if we have achieved the occupancy target.
1944 LLVM_DEBUG(dbgs() << "Pressure in desired limits, done.\n");
1945 return;
1946 }
1947
1948 unsigned TargetOccupancy = std::min(
1949 S.getTargetOccupancy(), ST.getOccupancyWithWorkGroupSizes(MF).second);
1950 unsigned WavesAfter = std::min(
1951 TargetOccupancy, PressureAfter.getOccupancy(ST, DynamicVGPRBlockSize));
1952 unsigned WavesBefore = std::min(
1953 TargetOccupancy, PressureBefore.getOccupancy(ST, DynamicVGPRBlockSize));
1954 LLVM_DEBUG(dbgs() << "Occupancy before scheduling: " << WavesBefore
1955 << ", after " << WavesAfter << ".\n");
1956
1957 // We may not be able to keep the current target occupancy because of the just
1958 // scheduled region. We might still be able to revert scheduling if the
1959 // occupancy before was higher, or if the current schedule has register
1960 // pressure higher than the excess limits which could lead to more spilling.
1961 unsigned NewOccupancy = std::max(WavesAfter, WavesBefore);
1962
1963 // Allow memory bound functions to drop to 4 waves if not limited by an
1964 // attribute.
1965 if (WavesAfter < WavesBefore && WavesAfter < DAG.MinOccupancy &&
1966 WavesAfter >= MFI.getMinAllowedOccupancy()) {
1967 LLVM_DEBUG(dbgs() << "Function is memory bound, allow occupancy drop up to "
1968 << MFI.getMinAllowedOccupancy() << " waves\n");
1969 NewOccupancy = WavesAfter;
1970 }
1971
1972 if (NewOccupancy < DAG.MinOccupancy) {
1973 DAG.MinOccupancy = NewOccupancy;
1974 MFI.limitOccupancy(DAG.MinOccupancy);
1975 LLVM_DEBUG(dbgs() << "Occupancy lowered for the function to "
1976 << DAG.MinOccupancy << ".\n");
1977 }
1978 // The maximum number of arch VGPR on non-unified register file, or the
1979 // maximum VGPR + AGPR in the unified register file case.
1980 unsigned MaxVGPRs = ST.getMaxNumVGPRs(MF);
1981 // The maximum number of arch VGPR for both unified and non-unified register
1982 // file.
1983 unsigned MaxArchVGPRs = std::min(MaxVGPRs, ST.getAddressableNumArchVGPRs());
1984 unsigned MaxSGPRs = ST.getMaxNumSGPRs(MF);
1985
1986 if (PressureAfter.getVGPRNum(ST.hasGFX90AInsts()) > MaxVGPRs ||
1987 PressureAfter.getArchVGPRNum() > MaxArchVGPRs ||
1988 PressureAfter.getAGPRNum() > MaxArchVGPRs ||
1989 PressureAfter.getSGPRNum() > MaxSGPRs) {
1990 DAG.RegionsWithHighRP[RegionIdx] = true;
1991 DAG.RegionsWithExcessRP[RegionIdx] = true;
1992 }
1993
1994 // Revert if this region's schedule would cause a drop in occupancy or
1995 // spilling.
1996 if (shouldRevertScheduling(WavesAfter)) {
1998 std::tie(DAG.RegionBegin, DAG.RegionEnd) = DAG.Regions[RegionIdx];
1999 } else {
2000 DAG.Pressure[RegionIdx] = PressureAfter;
2001 }
2002}
2003
2004unsigned
2005GCNSchedStage::computeSUnitReadyCycle(const SUnit &SU, unsigned CurrCycle,
2006 DenseMap<unsigned, unsigned> &ReadyCycles,
2007 const TargetSchedModel &SM) {
2008 unsigned ReadyCycle = CurrCycle;
2009 for (auto &D : SU.Preds) {
2010 if (D.isAssignedRegDep()) {
2011 MachineInstr *DefMI = D.getSUnit()->getInstr();
2012 unsigned Latency = SM.computeInstrLatency(DefMI);
2013 unsigned DefReady = ReadyCycles[DAG.getSUnit(DefMI)->NodeNum];
2014 ReadyCycle = std::max(ReadyCycle, DefReady + Latency);
2015 }
2016 }
2017 ReadyCycles[SU.NodeNum] = ReadyCycle;
2018 return ReadyCycle;
2019}
2020
2021#ifndef NDEBUG
2023 bool operator()(std::pair<MachineInstr *, unsigned> A,
2024 std::pair<MachineInstr *, unsigned> B) const {
2025 return A.second < B.second;
2026 }
2027};
2028
2029static void printScheduleModel(std::set<std::pair<MachineInstr *, unsigned>,
2030 EarlierIssuingCycle> &ReadyCycles) {
2031 if (ReadyCycles.empty())
2032 return;
2033 unsigned BBNum = ReadyCycles.begin()->first->getParent()->getNumber();
2034 dbgs() << "\n################## Schedule time ReadyCycles for MBB : " << BBNum
2035 << " ##################\n# Cycle #\t\t\tInstruction "
2036 " "
2037 " \n";
2038 unsigned IPrev = 1;
2039 for (auto &I : ReadyCycles) {
2040 if (I.second > IPrev + 1)
2041 dbgs() << "****************************** BUBBLE OF " << I.second - IPrev
2042 << " CYCLES DETECTED ******************************\n\n";
2043 dbgs() << "[ " << I.second << " ] : " << *I.first << "\n";
2044 IPrev = I.second;
2045 }
2046}
2047#endif
2048
2049ScheduleMetrics
2050GCNSchedStage::getScheduleMetrics(const std::vector<SUnit> &InputSchedule) {
2051#ifndef NDEBUG
2052 std::set<std::pair<MachineInstr *, unsigned>, EarlierIssuingCycle>
2053 ReadyCyclesSorted;
2054#endif
2055 const TargetSchedModel &SM = ST.getInstrInfo()->getSchedModel();
2056 unsigned SumBubbles = 0;
2057 DenseMap<unsigned, unsigned> ReadyCycles;
2058 unsigned CurrCycle = 0;
2059 for (auto &SU : InputSchedule) {
2060 unsigned ReadyCycle =
2061 computeSUnitReadyCycle(SU, CurrCycle, ReadyCycles, SM);
2062 SumBubbles += ReadyCycle - CurrCycle;
2063#ifndef NDEBUG
2064 ReadyCyclesSorted.insert(std::make_pair(SU.getInstr(), ReadyCycle));
2065#endif
2066 CurrCycle = ++ReadyCycle;
2067 }
2068#ifndef NDEBUG
2069 LLVM_DEBUG(
2070 printScheduleModel(ReadyCyclesSorted);
2071 dbgs() << "\n\t"
2072 << "Metric: "
2073 << (SumBubbles
2074 ? (SumBubbles * ScheduleMetrics::ScaleFactor) / CurrCycle
2075 : 1)
2076 << "\n\n");
2077#endif
2078
2079 return ScheduleMetrics(CurrCycle, SumBubbles);
2080}
2081
2084#ifndef NDEBUG
2085 std::set<std::pair<MachineInstr *, unsigned>, EarlierIssuingCycle>
2086 ReadyCyclesSorted;
2087#endif
2088 const TargetSchedModel &SM = ST.getInstrInfo()->getSchedModel();
2089 unsigned SumBubbles = 0;
2090 DenseMap<unsigned, unsigned> ReadyCycles;
2091 unsigned CurrCycle = 0;
2092 for (auto &MI : DAG) {
2093 SUnit *SU = DAG.getSUnit(&MI);
2094 if (!SU)
2095 continue;
2096 unsigned ReadyCycle =
2097 computeSUnitReadyCycle(*SU, CurrCycle, ReadyCycles, SM);
2098 SumBubbles += ReadyCycle - CurrCycle;
2099#ifndef NDEBUG
2100 ReadyCyclesSorted.insert(std::make_pair(SU->getInstr(), ReadyCycle));
2101#endif
2102 CurrCycle = ++ReadyCycle;
2103 }
2104#ifndef NDEBUG
2105 LLVM_DEBUG(
2106 printScheduleModel(ReadyCyclesSorted);
2107 dbgs() << "\n\t"
2108 << "Metric: "
2109 << (SumBubbles
2110 ? (SumBubbles * ScheduleMetrics::ScaleFactor) / CurrCycle
2111 : 1)
2112 << "\n\n");
2113#endif
2114
2115 return ScheduleMetrics(CurrCycle, SumBubbles);
2116}
2117
2118bool GCNSchedStage::shouldRevertScheduling(unsigned WavesAfter) {
2119 if (WavesAfter < DAG.MinOccupancy)
2120 return true;
2121
2122 // For dynamic VGPR mode, we don't want to waste any VGPR blocks.
2123 if (DAG.MFI.isDynamicVGPREnabled()) {
2124 unsigned BlocksBefore = AMDGPU::IsaInfo::getAllocatedNumVGPRBlocks(
2125 ST, DAG.MFI.getDynamicVGPRBlockSize(),
2126 PressureBefore.getVGPRNum(false));
2127 unsigned BlocksAfter = AMDGPU::IsaInfo::getAllocatedNumVGPRBlocks(
2128 ST, DAG.MFI.getDynamicVGPRBlockSize(), PressureAfter.getVGPRNum(false));
2129 if (BlocksAfter > BlocksBefore)
2130 return true;
2131 }
2132
2133 return false;
2134}
2135
2138 return false;
2139
2141 return true;
2142
2143 if (mayCauseSpilling(WavesAfter))
2144 return true;
2145
2146 return false;
2147}
2148
2150 // If RP is not reduced in the unclustered reschedule stage, revert to the
2151 // old schedule.
2152 if ((WavesAfter <=
2153 PressureBefore.getOccupancy(ST, DAG.MFI.getDynamicVGPRBlockSize()) &&
2154 mayCauseSpilling(WavesAfter)) ||
2156 LLVM_DEBUG(dbgs() << "Unclustered reschedule did not help.\n");
2157 return true;
2158 }
2159
2160 // Do not attempt to relax schedule even more if we are already spilling.
2162 return false;
2163
2164 LLVM_DEBUG(
2165 dbgs()
2166 << "\n\t *** In shouldRevertScheduling ***\n"
2167 << " *********** BEFORE UnclusteredHighRPStage ***********\n");
2168 ScheduleMetrics MBefore = getScheduleMetrics(DAG.SUnits);
2169 LLVM_DEBUG(
2170 dbgs()
2171 << "\n *********** AFTER UnclusteredHighRPStage ***********\n");
2173 unsigned OldMetric = MBefore.getMetric();
2174 unsigned NewMetric = MAfter.getMetric();
2175 unsigned WavesBefore = std::min(
2176 S.getTargetOccupancy(),
2177 PressureBefore.getOccupancy(ST, DAG.MFI.getDynamicVGPRBlockSize()));
2178 unsigned Profit =
2179 ((WavesAfter * ScheduleMetrics::ScaleFactor) / WavesBefore *
2181 NewMetric) /
2183 LLVM_DEBUG(dbgs() << "\tMetric before " << MBefore << "\tMetric after "
2184 << MAfter << "Profit: " << Profit << "\n");
2185 return Profit < ScheduleMetrics::ScaleFactor;
2186}
2187
2190 return false;
2191
2193 return true;
2194
2195 if (mayCauseSpilling(WavesAfter))
2196 return true;
2197
2198 return false;
2199}
2200
2202 // When trying to increase occupancy (TargetOcc == true) the stage manages
2203 // region reverts globally (all or none), so we always return false here.
2204 return !TargetOcc && mayCauseSpilling(WavesAfter);
2205}
2206
2208 if (mayCauseSpilling(WavesAfter))
2209 return true;
2210
2211 return false;
2212}
2213
2215 unsigned WavesAfter) {
2216 return mayCauseSpilling(WavesAfter);
2217}
2218
2219bool GCNSchedStage::mayCauseSpilling(unsigned WavesAfter) {
2220 if (WavesAfter <= MFI.getMinWavesPerEU() && isRegionWithExcessRP() &&
2222 LLVM_DEBUG(dbgs() << "New pressure will result in more spilling.\n");
2223 return true;
2224 }
2225
2226 return false;
2227}
2228
2230 ArrayRef<MachineInstr *> MIOrder) {
2231 assert(static_cast<size_t>(std::distance(DAG.Regions[RegionIdx].first,
2232 DAG.Regions[RegionIdx].second)) ==
2233 MIOrder.size() &&
2234 "instruction number mismatch");
2235 if (MIOrder.empty())
2236 return;
2237
2238 LLVM_DEBUG(dbgs() << "Reverting scheduling for region " << RegionIdx << '\n');
2239
2240 // Reconstruct MI sequence by moving instructions in desired order before
2241 // the current region's start.
2242 MachineBasicBlock::iterator RegionEnd = DAG.Regions[RegionIdx].first;
2243 MachineBasicBlock *MBB = MIOrder.front()->getParent();
2244 for (MachineInstr *MI : MIOrder) {
2245 // Either move the next MI in order before the end of the region or move the
2246 // region end past the MI if it is at the correct position.
2247 MachineBasicBlock::iterator MII = MI->getIterator();
2248 if (MII != RegionEnd) {
2249 // Will subsequent splice move MI up past a non-debug instruction?
2250 bool NonDebugReordered =
2251 !MI->isDebugInstr() &&
2252 skipDebugInstructionsForward(RegionEnd, MII) != MII;
2253 MBB->splice(RegionEnd, MBB, MI);
2254 // Only update LiveIntervals information if non-debug instructions are
2255 // reordered. Otherwise debug instructions could cause code generation to
2256 // change.
2257 if (NonDebugReordered)
2258 DAG.LIS->handleMove(*MI, true);
2259 } else {
2260 // MI is already at the expected position. However, earlier splices in
2261 // this loop may have changed neighboring slot indices, so this MI's
2262 // slot index can become non-monotonic w.r.t. the physical MBB order.
2263 // Only re-seat when monotonicity is actually violated to avoid
2264 // unnecessary LiveInterval changes that could perturb scheduling.
2265 if (!MI->isDebugInstr()) {
2266 SlotIndex MIIdx = DAG.LIS->getInstructionIndex(*MI);
2267 SlotIndex PrevIdx = DAG.LIS->getSlotIndexes()->getIndexBefore(*MI);
2268 if (PrevIdx >= MIIdx)
2269 DAG.LIS->handleMove(*MI, true);
2270 }
2271 ++RegionEnd;
2272 }
2273 if (MI->isDebugInstr()) {
2274 LLVM_DEBUG(dbgs() << "Scheduling " << *MI);
2275 continue;
2276 }
2277
2278 // Reset read-undef flags and update them later.
2279 for (MachineOperand &Op : MI->all_defs())
2280 Op.setIsUndef(false);
2281 RegisterOperands RegOpers;
2282 RegOpers.collect(*MI, *DAG.TRI, DAG.MRI, DAG.ShouldTrackLaneMasks, false);
2283 if (DAG.ShouldTrackLaneMasks) {
2284 // Adjust liveness and add missing dead+read-undef flags.
2285 SlotIndex SlotIdx = DAG.LIS->getInstructionIndex(*MI).getRegSlot();
2286 RegOpers.adjustLaneLiveness(*DAG.LIS, DAG.MRI, SlotIdx, MI);
2287 } else {
2288 // Adjust for missing dead-def flags.
2289 RegOpers.detectDeadDefs(*MI, *DAG.LIS);
2290 }
2291 LLVM_DEBUG(dbgs() << "Scheduling " << *MI);
2292 }
2293
2294 // The region end doesn't change throughout scheduling since it itself is
2295 // outside the region (whether that is a MBB end or a terminator MI).
2296 assert(RegionEnd == DAG.Regions[RegionIdx].second && "region end mismatch");
2297 DAG.Regions[RegionIdx].first = MIOrder.front();
2298}
2299
2300/// Returns true if reaching def \p RD will be in AGPR form after the rewrite
2301/// and so needs no bridge copy: a candidate MFMA in \p RewriteSet, an
2302/// AV_MOV_*_IMM_PSEUDO, or a copy from a candidate src2 reg in \p CandSrc2Regs.
2303/// A non-candidate MFMA stays in VGPR form and still needs a bridge.
2305 MachineInstr *RD, const SmallPtrSetImpl<MachineInstr *> &RewriteSet,
2306 const DenseSet<Register> &CandSrc2Regs, const SIInstrInfo &TII) {
2307 if (TII.isMAI(*RD))
2308 return RewriteSet.contains(RD);
2309 if (RD->getOpcode() == AMDGPU::AV_MOV_B32_IMM_PSEUDO ||
2310 RD->getOpcode() == AMDGPU::AV_MOV_B64_IMM_PSEUDO)
2311 return true;
2312 if (RD->isCopy() && CandSrc2Regs.contains(RD->getOperand(1).getReg()))
2313 return true;
2314 return false;
2315}
2316
2317bool RewriteMFMAFormStage::hasUseRequiringVGPR(
2318 ArrayRef<SlotIndex> Src2ReachingDefs,
2319 const SmallPtrSetImpl<MachineInstr *> &RewriteSet) {
2320 for (SlotIndex RDIdx : Src2ReachingDefs) {
2321 const MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIdx);
2323 findReachingUses(RD, DAG.LIS, ReachingUses);
2324 for (const MachineOperand *UseMO : ReachingUses) {
2325 const MachineInstr *UseMI = UseMO->getParent();
2326 if (UseMI->isCopy())
2327 continue;
2328 if (TII->isMAI(*UseMI) && RewriteSet.contains(UseMI))
2329 continue;
2330 return true;
2331 }
2332 }
2333 return false;
2334}
2335
2336void RewriteMFMAFormStage::resetRewriteCandsToVGPR(
2337 ArrayRef<std::pair<MachineInstr *, unsigned>> RewriteCands) {
2338 for (auto [MI, OriginalOpcode] : RewriteCands) {
2339 assert(TII->isMAI(*MI));
2340 const TargetRegisterClass *ADefRC =
2341 DAG.MRI.getRegClass(MI->getOperand(0).getReg());
2342 const TargetRegisterClass *VDefRC = SRI->getEquivalentVGPRClass(ADefRC);
2343 DAG.MRI.setRegClass(MI->getOperand(0).getReg(), VDefRC);
2344 MI->setDesc(TII->get(OriginalOpcode));
2345
2346 MachineOperand *Src2 = TII->getNamedOperand(*MI, AMDGPU::OpName::src2);
2347 if (!Src2->isReg())
2348 continue;
2349
2350 // Have to get src types separately since subregs may cause C and D
2351 // registers to be different types even though the actual operand is
2352 // the same size.
2353 const TargetRegisterClass *AUseRC = DAG.MRI.getRegClass(Src2->getReg());
2354 const TargetRegisterClass *VUseRC = SRI->getEquivalentVGPRClass(AUseRC);
2355 DAG.MRI.setRegClass(Src2->getReg(), VUseRC);
2356 }
2357}
2358
2359bool RewriteMFMAFormStage::isRewriteCandidate(MachineInstr *MI) const {
2360 if (!static_cast<const SIInstrInfo *>(DAG.TII)->isMAI(*MI))
2361 return false;
2362 if (AMDGPU::getMFMASrcCVDstAGPROp(MI->getOpcode()) == -1)
2363 return false;
2364 // Reject candidates whose users force an unavoidable bridge copy.
2365 Register DstReg = MI->getOperand(0).getReg();
2366 for (const MachineOperand &Use : DAG.MRI.use_nodbg_operands(DstReg)) {
2367 if (!TII->isMAI(*Use.getParent()) && !Use.getParent()->isCopy())
2368 return false;
2369 }
2370 return true;
2371}
2372
2373bool RewriteMFMAFormStage::initHeuristics(
2374 std::vector<std::pair<MachineInstr *, unsigned>> &RewriteCands,
2375 DenseMap<MachineBasicBlock *, std::set<Register>> &CopyForUse,
2376 SmallPtrSetImpl<MachineInstr *> &CopyForDef) {
2377 bool Changed = false;
2378
2379 // Collect the candidate group, its members share AGPR-form operands
2380 // post-rewrite, so reaching defs feeding any member don't need bridge copy.
2381 SmallPtrSet<MachineInstr *, 16> RewriteSet;
2382 DenseSet<Register> CandSrc2Regs;
2383 for (MachineBasicBlock &MBB : MF) {
2384 for (MachineInstr &MI : MBB) {
2385 if (!isRewriteCandidate(&MI))
2386 continue;
2387 RewriteSet.insert(&MI);
2388 MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2);
2389 if (Src2 && Src2->isReg())
2390 CandSrc2Regs.insert(Src2->getReg());
2391 }
2392 }
2393
2394 // Prepare for the heuristics
2395 for (MachineBasicBlock &MBB : MF) {
2396 for (MachineInstr &MI : MBB) {
2397 if (!isRewriteCandidate(&MI))
2398 continue;
2399
2400 int ReplacementOp = AMDGPU::getMFMASrcCVDstAGPROp(MI.getOpcode());
2401 assert(ReplacementOp != -1);
2402
2403 RewriteCands.push_back({&MI, MI.getOpcode()});
2404 MI.setDesc(TII->get(ReplacementOp));
2405
2406 MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2);
2407 if (Src2->isReg()) {
2408 SmallVector<SlotIndex, 8> Src2ReachingDefs;
2409 findReachingDefs(*Src2, DAG.LIS, Src2ReachingDefs);
2410
2411 // If src2 has a use that must remain VGPR, it cannot be reclassified to
2412 // AGPR.
2413 bool Src2NeedsVGPR = hasUseRequiringVGPR(Src2ReachingDefs, RewriteSet);
2414 Src2NeedsVGPRCache[&MI] = Src2NeedsVGPR;
2415
2416 for (SlotIndex RDIdx : Src2ReachingDefs) {
2417 MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIdx);
2418 if (!Src2NeedsVGPR &&
2419 isReachingDefAGPRForm(RD, RewriteSet, CandSrc2Regs, *TII))
2420 continue;
2421 CopyForDef.insert(RD);
2422 }
2423 }
2424
2425 MachineOperand &Dst = MI.getOperand(0);
2426 SmallVector<MachineOperand *, 8> DstReachingUses;
2427
2428 findReachingUses(&MI, DAG.LIS, DstReachingUses);
2429
2430 for (MachineOperand *RUOp : DstReachingUses) {
2431 MachineInstr *UserMI = RUOp->getParent();
2432 // Group members read the AGPR result directly.
2433 if (TII->isMAI(*UserMI) && RewriteSet.contains(UserMI))
2434 continue;
2435
2436 // For any user of the result of the MFMA which is not an MFMA, we
2437 // insert a copy. For a given register, we will only insert one copy
2438 // per user block.
2439 CopyForUse[UserMI->getParent()].insert(RUOp->getReg());
2440
2441 if (TII->isMAI(*UserMI))
2442 continue;
2443
2444 SmallVector<SlotIndex, 8> DstUsesReachingDefs;
2445 findReachingDefs(*RUOp, DAG.LIS, DstUsesReachingDefs);
2446
2447 for (SlotIndex RDIndex : DstUsesReachingDefs) {
2448 MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex);
2449 if (TII->isMAI(*RD))
2450 continue;
2451
2452 // For any definition of the user of the MFMA which is not an MFMA,
2453 // we insert a copy. We do this to transform all the reaching defs
2454 // of this use to AGPR. By doing this, we can insert a copy from
2455 // AGPR to VGPR at the user rather than after the MFMA.
2456 CopyForDef.insert(RD);
2457 }
2458 }
2459
2460 // Do the rewrite to allow for updated RP calculation.
2461 const TargetRegisterClass *VDefRC = DAG.MRI.getRegClass(Dst.getReg());
2462 const TargetRegisterClass *ADefRC = SRI->getEquivalentAGPRClass(VDefRC);
2463 DAG.MRI.setRegClass(Dst.getReg(), ADefRC);
2464 if (Src2->isReg()) {
2465 // Have to get src types separately since subregs may cause C and D
2466 // registers to be different types even though the actual operand is
2467 // the same size.
2468 const TargetRegisterClass *VUseRC = DAG.MRI.getRegClass(Src2->getReg());
2469 const TargetRegisterClass *AUseRC = SRI->getEquivalentAGPRClass(VUseRC);
2470 DAG.MRI.setRegClass(Src2->getReg(), AUseRC);
2471 }
2472 Changed = true;
2473 }
2474 }
2475
2476 return Changed;
2477}
2478
2479int64_t RewriteMFMAFormStage::getRewriteCost(
2480 ArrayRef<std::pair<MachineInstr *, unsigned>> RewriteCands,
2481 const DenseMap<MachineBasicBlock *, std::set<Register>> &CopyForUse,
2482 const SmallPtrSetImpl<MachineInstr *> &CopyForDef) {
2483 MachineBlockFrequencyInfo *MBFI = DAG.MBFI;
2484
2485 int64_t BestSpillCost = 0;
2486 int64_t Cost = 0;
2487 uint64_t EntryFreq = MBFI->getEntryFreq().getFrequency();
2488
2489 std::pair<unsigned, unsigned> MaxVectorRegs =
2490 ST.getMaxNumVectorRegs(MF.getFunction());
2491 unsigned ArchVGPRThreshold = MaxVectorRegs.first;
2492 unsigned AGPRThreshold = MaxVectorRegs.second;
2493 unsigned CombinedThreshold = ST.getMaxNumVGPRs(MF);
2494
2495 for (unsigned Region = 0; Region < DAG.Regions.size(); Region++) {
2496 if (!RegionsWithExcessArchVGPR[Region])
2497 continue;
2498
2499 GCNRegPressure &PressureBefore = DAG.Pressure[Region];
2500 unsigned SpillCostBefore = PressureBefore.getVGPRSpills(
2501 MF, ArchVGPRThreshold, AGPRThreshold, CombinedThreshold);
2502
2503 // For the cases we care about (i.e. ArchVGPR usage is greater than the
2504 // addressable limit), rewriting alone should bring pressure to manageable
2505 // level. If we find any such region, then the rewrite is potentially
2506 // beneficial.
2507 GCNRegPressure PressureAfter = DAG.getRealRegPressure(Region);
2508 unsigned SpillCostAfter = PressureAfter.getVGPRSpills(
2509 MF, ArchVGPRThreshold, AGPRThreshold, CombinedThreshold);
2510
2511 uint64_t BlockFreq =
2512 MBFI->getBlockFreq(DAG.Regions[Region].first->getParent())
2513 .getFrequency();
2514
2515 bool RelativeFreqIsDenom = EntryFreq > BlockFreq;
2516 uint64_t RelativeFreq = EntryFreq && BlockFreq
2517 ? (RelativeFreqIsDenom ? EntryFreq / BlockFreq
2518 : BlockFreq / EntryFreq)
2519 : 1;
2520
2521 // This assumes perfect spilling / splitting -- using one spill / copy
2522 // instruction and one restoreFrom / copy for each excess register,
2523 int64_t SpillCost = ((int)SpillCostAfter - (int)SpillCostBefore) * 2;
2524
2525 // Also account for the block frequency.
2526 if (RelativeFreqIsDenom)
2527 SpillCost /= (int64_t)RelativeFreq;
2528 else
2529 SpillCost *= (int64_t)RelativeFreq;
2530
2531 // If we have increased spilling in any block, just bail.
2532 if (SpillCost > 0) {
2533 resetRewriteCandsToVGPR(RewriteCands);
2534 return SpillCost;
2535 }
2536
2537 if (SpillCost < BestSpillCost)
2538 BestSpillCost = SpillCost;
2539 }
2540
2541 // Set the cost to the largest decrease in spill cost in order to not double
2542 // count spill reductions.
2543 Cost = BestSpillCost;
2544 assert(Cost <= 0);
2545
2546 unsigned CopyCost = 0;
2547
2548 // For each CopyForDef, increase the cost by the register size while
2549 // accounting for block frequency.
2550 for (MachineInstr *DefMI : CopyForDef) {
2551 Register DefReg = DefMI->getOperand(0).getReg();
2552 uint64_t DefFreq =
2553 EntryFreq
2554 ? MBFI->getBlockFreq(DefMI->getParent()).getFrequency() / EntryFreq
2555 : 1;
2556
2557 const TargetRegisterClass *RC = DAG.MRI.getRegClass(DefReg);
2558 CopyCost += RC->getCopyCost() * DefFreq;
2559 }
2560
2561 // Account for CopyForUse copies in each block that the register is used.
2562 for (auto &[UseBlock, UseRegs] : CopyForUse) {
2563 uint64_t UseFreq =
2564 EntryFreq ? MBFI->getBlockFreq(UseBlock).getFrequency() / EntryFreq : 1;
2565
2566 for (Register UseReg : UseRegs) {
2567 const TargetRegisterClass *RC = DAG.MRI.getRegClass(UseReg);
2568 CopyCost += RC->getCopyCost() * UseFreq;
2569 }
2570 }
2571
2572 // Reset the classes that were changed to AGPR for better register bank
2573 // analysis. We must do rewriting after copy-insertion, as some defs of the
2574 // register may require VGPR. Additionally, if we bail out and don't perform
2575 // the rewrite then these need to be restored anyway.
2576 resetRewriteCandsToVGPR(RewriteCands);
2577
2578 return Cost + CopyCost;
2579}
2580
2581bool RewriteMFMAFormStage::rewrite(
2582 ArrayRef<std::pair<MachineInstr *, unsigned>> RewriteCands) {
2583 DenseMap<MachineInstr *, unsigned> FirstMIToRegion;
2584 DenseMap<MachineInstr *, unsigned> LastMIToRegion;
2585
2586 for (unsigned Region = 0; Region < DAG.Regions.size(); Region++) {
2587 RegionBoundaries Entry = DAG.Regions[Region];
2588 if (Entry.first == Entry.second)
2589 continue;
2590
2591 FirstMIToRegion[&*Entry.first] = Region;
2592 if (Entry.second != Entry.first->getParent()->end())
2593 LastMIToRegion[&*Entry.second] = Region;
2594 }
2595
2596 // Rewrite the MFMAs to AGPR, and insert any copies as needed.
2597 // The general assumption of the algorithm (and the previous cost calculation)
2598 // is that it is better to insert the copies in the MBB of the def of the src2
2599 // operands, and in the MBB of the user of the dest operands. This is based on
2600 // the assumption that the MFMAs are likely to appear in loop bodies, while
2601 // the src2 and dest operands are live-in / live-out of the loop. Due to this
2602 // design, the algorithm for finding copy insertion points is more
2603 // complicated.
2604 //
2605 // There are three main cases to handle: 1. the reaching defs of the src2
2606 // operands, 2. the reaching uses of the dst operands, and 3. the reaching
2607 // defs of the reaching uses of the dst operand.
2608 //
2609 // In the first case, we simply insert copies after each of the reaching
2610 // definitions. In the second case, we collect all the uses of a given dest
2611 // and organize them by MBB. Then, we insert 1 copy for each MBB before the
2612 // earliest use. Since the use may have multiple reaching defs, and since we
2613 // want to replace the register it is using with the result of the copy, we
2614 // must handle case 3. In the third case, we simply insert a copy after each
2615 // of the reaching defs to connect to the copy of the reaching uses of the dst
2616 // reg. This allows us to avoid inserting copies next to the MFMAs.
2617 //
2618 // While inserting the copies, we maintain a map of operands which will use
2619 // different regs (i.e. the result of the copies). For example, a case 1 src2
2620 // operand will use the register result of the copies after the reaching defs,
2621 // as opposed to the original register. Now that we have completed our copy
2622 // analysis and placement, we can bulk update the registers. We do this
2623 // separately as to avoid complicating the reachingDef and reachingUse
2624 // queries.
2625 //
2626 // While inserting the copies, we also maintain a list or registers which we
2627 // will want to reclassify as AGPR. After doing the copy insertion and the
2628 // register replacement, we can finally do the reclassification. This uses the
2629 // redef map, as the registers we are interested in reclassifying may be
2630 // replaced by the result of a copy. We must do this after the copy analysis
2631 // and placement as we must have an accurate redef map -- otherwise we may end
2632 // up creating illegal instructions.
2633
2634 // The original registers of the MFMA that need to be reclassified as AGPR.
2635 DenseSet<Register> RewriteRegs;
2636 // The map of an original register in the MFMA to a new register (result of a
2637 // copy) that it should be replaced with.
2638 DenseMap<Register, Register> RedefMap;
2639 // The map of the original MFMA registers to the relevant MFMA operands.
2640 DenseMap<Register, DenseSet<MachineOperand *>> ReplaceMap;
2641 // The map of reaching defs for a given register -- to avoid duplicate copies.
2642 DenseMap<Register, SmallPtrSet<MachineInstr *, 8>> ReachingDefCopyMap;
2643 // The map of reaching uses for a given register by basic block -- to avoid
2644 // duplicate copies and to calculate per MBB insert pts.
2645 DenseMap<unsigned, DenseMap<Register, SmallPtrSet<MachineOperand *, 8>>>
2646 ReachingUseTracker;
2647
2648 // Collect the candidate group; its members share AGPR-form operands
2649 // post-rewrite, so reaching defs feeding any member need no bridge copy.
2650 SmallPtrSet<MachineInstr *, 16> RewriteCandsSet;
2651 DenseSet<Register> RewriteSrc2Regs;
2652 for (auto &[MI, OriginalOpcode] : RewriteCands) {
2653 RewriteCandsSet.insert(MI);
2654 MachineOperand *Src2 = TII->getNamedOperand(*MI, AMDGPU::OpName::src2);
2655 if (Src2 && Src2->isReg())
2656 RewriteSrc2Regs.insert(Src2->getReg());
2657 }
2658
2659 for (auto &[MI, OriginalOpcode] : RewriteCands) {
2660 int ReplacementOp = AMDGPU::getMFMASrcCVDstAGPROp(MI->getOpcode());
2661 if (ReplacementOp == -1)
2662 continue;
2663 MI->setDesc(TII->get(ReplacementOp));
2664
2665 // Case 1: insert copies for the reaching defs of the Src2Reg.
2666 MachineOperand *Src2 = TII->getNamedOperand(*MI, AMDGPU::OpName::src2);
2667 if (Src2->isReg()) {
2668 Register Src2Reg = Src2->getReg();
2669 if (!Src2Reg.isVirtual())
2670 return false;
2671
2672 Register MappedReg = Src2->getReg();
2673 SmallVector<SlotIndex, 8> Src2ReachingDefs;
2674 findReachingDefs(*Src2, DAG.LIS, Src2ReachingDefs);
2675 SmallSetVector<MachineInstr *, 8> Src2DefsReplace;
2676
2677 // If src2 has a use that must remain VGPR, it cannot be reclassified to
2678 // AGPR.
2679 bool Src2NeedsVGPR = Src2NeedsVGPRCache.lookup(MI);
2680
2681 for (SlotIndex RDIndex : Src2ReachingDefs) {
2682 MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex);
2683 if (!Src2NeedsVGPR &&
2684 isReachingDefAGPRForm(RD, RewriteCandsSet, RewriteSrc2Regs, *TII))
2685 continue;
2686
2687 Src2DefsReplace.insert(RD);
2688 }
2689
2690 if (!Src2DefsReplace.empty()) {
2691 auto RI = RedefMap.find(Src2Reg);
2692 if (RI != RedefMap.end()) {
2693 MappedReg = RI->second;
2694 } else {
2695 assert(!ReachingDefCopyMap.contains(Src2Reg));
2696 const TargetRegisterClass *Src2RC = DAG.MRI.getRegClass(Src2Reg);
2697 const TargetRegisterClass *VGPRRC =
2698 SRI->getEquivalentVGPRClass(Src2RC);
2699
2700 // Track the mapping of the original register to the new register.
2701 MappedReg = DAG.MRI.createVirtualRegister(VGPRRC);
2702 RedefMap[Src2Reg] = MappedReg;
2703 }
2704
2705 // If none exists, create a copy from this reaching def.
2706 // We may have inserted a copy already in an earlier iteration.
2707 for (MachineInstr *RD : Src2DefsReplace) {
2708 // Do not create redundant copies.
2709 if (ReachingDefCopyMap[Src2Reg].insert(RD).second) {
2710 MachineInstrBuilder VGPRCopy =
2711 BuildMI(*RD->getParent(), std::next(RD->getIterator()),
2712 RD->getDebugLoc(), TII->get(TargetOpcode::COPY))
2713 .addDef(MappedReg, {}, 0)
2714 .addUse(Src2Reg, {}, 0);
2715 DAG.LIS->InsertMachineInstrInMaps(*VGPRCopy);
2716
2717 // If this reaching def was the last MI in the region, update the
2718 // region boundaries.
2719 if (LastMIToRegion.contains(RD)) {
2720 unsigned UpdateRegion = LastMIToRegion[RD];
2721 DAG.Regions[UpdateRegion].second = VGPRCopy;
2722 LastMIToRegion.erase(RD);
2723 }
2724 }
2725 }
2726 }
2727
2728 // Track the register for reclassification
2729 RewriteRegs.insert(Src2Reg);
2730
2731 // Always insert the operand for replacement. If this corresponds with a
2732 // chain of tied-def we may not see the VGPR requirement until later.
2733 ReplaceMap[Src2Reg].insert(Src2);
2734 }
2735
2736 // Case 2 and Case 3: insert copies before the reaching uses of the dsts,
2737 // and after the reaching defs of the reaching uses of the dsts.
2738
2739 MachineOperand *Dst = &MI->getOperand(0);
2740 Register DstReg = Dst->getReg();
2741 if (!DstReg.isVirtual())
2742 return false;
2743
2744 Register MappedReg = DstReg;
2745 SmallVector<MachineOperand *, 8> DstReachingUses;
2746
2747 SmallVector<MachineOperand *, 8> DstReachingUseCopies;
2748 SmallVector<MachineInstr *, 8> DstUseDefsReplace;
2749
2750 findReachingUses(MI, DAG.LIS, DstReachingUses);
2751
2752 for (MachineOperand *RUOp : DstReachingUses) {
2753 MachineInstr *UserMI = RUOp->getParent();
2754 // Group members read the AGPR result directly.
2755 if (TII->isMAI(*UserMI) && RewriteCandsSet.contains(UserMI))
2756 continue;
2757
2758 // If there is a non mai reaching use, then we need a copy.
2759 if (find(DstReachingUseCopies, RUOp) == DstReachingUseCopies.end())
2760 DstReachingUseCopies.push_back(RUOp);
2761
2762 // Non-rewritten MAI: its defs aren't being reclassified.
2763 if (TII->isMAI(*UserMI))
2764 continue;
2765
2766 SmallVector<SlotIndex, 8> DstUsesReachingDefs;
2767 findReachingDefs(*RUOp, DAG.LIS, DstUsesReachingDefs);
2768
2769 for (SlotIndex RDIndex : DstUsesReachingDefs) {
2770 MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex);
2771 if (TII->isMAI(*RD))
2772 continue;
2773
2774 // If there is a non mai reaching def of this reaching use, then we will
2775 // need a copy.
2776 if (find(DstUseDefsReplace, RD) == DstUseDefsReplace.end())
2777 DstUseDefsReplace.push_back(RD);
2778 }
2779 }
2780
2781 if (!DstUseDefsReplace.empty()) {
2782 auto RI = RedefMap.find(DstReg);
2783 if (RI != RedefMap.end()) {
2784 MappedReg = RI->second;
2785 } else {
2786 assert(!ReachingDefCopyMap.contains(DstReg));
2787 const TargetRegisterClass *DstRC = DAG.MRI.getRegClass(DstReg);
2788 const TargetRegisterClass *VGPRRC = SRI->getEquivalentVGPRClass(DstRC);
2789
2790 // Track the mapping of the original register to the new register.
2791 MappedReg = DAG.MRI.createVirtualRegister(VGPRRC);
2792 RedefMap[DstReg] = MappedReg;
2793 }
2794
2795 // If none exists, create a copy from this reaching def.
2796 // We may have inserted a copy already in an earlier iteration.
2797 for (MachineInstr *RD : DstUseDefsReplace) {
2798 // Do not create reundant copies.
2799 if (ReachingDefCopyMap[DstReg].insert(RD).second) {
2800 MachineInstrBuilder VGPRCopy =
2801 BuildMI(*RD->getParent(), std::next(RD->getIterator()),
2802 RD->getDebugLoc(), TII->get(TargetOpcode::COPY))
2803 .addDef(MappedReg, {}, 0)
2804 .addUse(DstReg, {}, 0);
2805 DAG.LIS->InsertMachineInstrInMaps(*VGPRCopy);
2806
2807 // If this reaching def was the last MI in the region, update the
2808 // region boundaries.
2809 auto LMI = LastMIToRegion.find(RD);
2810 if (LMI != LastMIToRegion.end()) {
2811 unsigned UpdateRegion = LMI->second;
2812 DAG.Regions[UpdateRegion].second = VGPRCopy;
2813 LastMIToRegion.erase(RD);
2814 }
2815 }
2816 }
2817 }
2818
2819 DenseSet<MachineOperand *> &DstRegSet = ReplaceMap[DstReg];
2820 for (MachineOperand *RU : DstReachingUseCopies) {
2821 MachineBasicBlock *RUBlock = RU->getParent()->getParent();
2822 // Just keep track of the reaching use of this register by block. After we
2823 // have scanned all the MFMAs we can find optimal insert pts.
2824 if (RUBlock != MI->getParent()) {
2825 ReachingUseTracker[RUBlock->getNumber()][DstReg].insert(RU);
2826 continue;
2827 }
2828
2829 // Special case, the use is in the same block as the MFMA. Insert the copy
2830 // just before the use.
2831 const TargetRegisterClass *DstRC = DAG.MRI.getRegClass(DstReg);
2832 const TargetRegisterClass *VGPRRC = SRI->getEquivalentVGPRClass(DstRC);
2833 Register NewUseReg = DAG.MRI.createVirtualRegister(VGPRRC);
2834 MachineInstr *UseInst = RU->getParent();
2835 MachineInstrBuilder VGPRCopy =
2836 BuildMI(*UseInst->getParent(), UseInst->getIterator(),
2837 UseInst->getDebugLoc(), TII->get(TargetOpcode::COPY))
2838 .addDef(NewUseReg, {}, 0)
2839 .addUse(DstReg, {}, 0);
2840 DAG.LIS->InsertMachineInstrInMaps(*VGPRCopy);
2841 // Since we know this use has only one reaching def, we can replace the
2842 // use reg.
2843 RU->setReg(NewUseReg);
2844 // Track the copy source operand for r eplacement.
2845 DstRegSet.insert(&VGPRCopy->getOperand(1));
2846 }
2847
2848 // Track the register for reclassification
2849 RewriteRegs.insert(DstReg);
2850
2851 // Insert the dst operand for replacement. If this dst is in a chain of
2852 // tied-def MFMAs, and the first src2 needs to be replaced with a new reg,
2853 // all the correspond operands need to be replaced.
2854 DstRegSet.insert(Dst);
2855 }
2856
2857 // Handle the copies for dst uses.
2858 using RUBType =
2859 std::pair<unsigned, DenseMap<Register, SmallPtrSet<MachineOperand *, 8>>>;
2860 for (RUBType RUBlockEntry : ReachingUseTracker) {
2861 using RUDType = std::pair<Register, SmallPtrSet<MachineOperand *, 8>>;
2862 for (RUDType RUDst : RUBlockEntry.second) {
2863 MachineOperand *OpBegin = *RUDst.second.begin();
2864 SlotIndex InstPt = DAG.LIS->getInstructionIndex(*OpBegin->getParent());
2865
2866 // Find the earliest use in this block.
2867 for (MachineOperand *User : RUDst.second) {
2868 SlotIndex NewInstPt = DAG.LIS->getInstructionIndex(*User->getParent());
2869 if (SlotIndex::isEarlierInstr(NewInstPt, InstPt))
2870 InstPt = NewInstPt;
2871 }
2872
2873 const TargetRegisterClass *DstRC = DAG.MRI.getRegClass(RUDst.first);
2874 const TargetRegisterClass *VGPRRC = SRI->getEquivalentVGPRClass(DstRC);
2875 Register NewUseReg = DAG.MRI.createVirtualRegister(VGPRRC);
2876 MachineInstr *UseInst = DAG.LIS->getInstructionFromIndex(InstPt);
2877
2878 MachineInstrBuilder VGPRCopy =
2879 BuildMI(*UseInst->getParent(), UseInst->getIterator(),
2880 UseInst->getDebugLoc(), TII->get(TargetOpcode::COPY))
2881 .addDef(NewUseReg, {}, 0)
2882 .addUse(RUDst.first, {}, 0);
2883 DAG.LIS->InsertMachineInstrInMaps(*VGPRCopy);
2884
2885 // If this UseInst was the first MI in the region, update the region
2886 // boundaries.
2887 auto FI = FirstMIToRegion.find(UseInst);
2888 if (FI != FirstMIToRegion.end()) {
2889 unsigned UpdateRegion = FI->second;
2890 DAG.Regions[UpdateRegion].first = VGPRCopy;
2891 FirstMIToRegion.erase(UseInst);
2892 }
2893
2894 // Replace the operand for all users.
2895 for (MachineOperand *User : RUDst.second) {
2896 User->setReg(NewUseReg);
2897 }
2898
2899 // Track the copy source operand for replacement.
2900 ReplaceMap[RUDst.first].insert(&VGPRCopy->getOperand(1));
2901 }
2902 }
2903
2904 // We may have needed to insert copies after the reaching defs of the MFMAs.
2905 // Replace the original register with the result of the copy for all relevant
2906 // operands.
2907 for (std::pair<Register, Register> NewDef : RedefMap) {
2908 Register OldReg = NewDef.first;
2909 Register NewReg = NewDef.second;
2910
2911 // Replace the register for any associated operand in the MFMA chain.
2912 for (MachineOperand *ReplaceOp : ReplaceMap[OldReg])
2913 ReplaceOp->setReg(NewReg);
2914 }
2915
2916 // Finally, do the reclassification of the MFMA registers.
2917 for (Register RewriteReg : RewriteRegs) {
2918 Register RegToRewrite = RewriteReg;
2919
2920 // Be sure to update the replacement register and not the original.
2921 auto RI = RedefMap.find(RewriteReg);
2922 if (RI != RedefMap.end())
2923 RegToRewrite = RI->second;
2924
2925 const TargetRegisterClass *CurrRC = DAG.MRI.getRegClass(RegToRewrite);
2926 const TargetRegisterClass *AGPRRC = SRI->getEquivalentAGPRClass(CurrRC);
2927
2928 DAG.MRI.setRegClass(RegToRewrite, AGPRRC);
2929 }
2930
2931 // Bulk update the LIS.
2932 DAG.LIS->reanalyze(DAG.MF);
2933 // Liveins may have been modified for cross RC copies
2934 RegionPressureMap LiveInUpdater(&DAG, false);
2935 LiveInUpdater.buildLiveRegMap();
2936
2937 for (unsigned Region = 0; Region < DAG.Regions.size(); Region++)
2938 DAG.LiveIns[Region] = LiveInUpdater.getLiveRegsForRegionIdx(Region);
2939
2940 DAG.Pressure[RegionIdx] = DAG.getRealRegPressure(RegionIdx);
2941
2942 return true;
2943}
2944
2945unsigned PreRARematStage::getStageTargetOccupancy() const {
2946 return TargetOcc ? *TargetOcc : MFI.getMinWavesPerEU();
2947}
2948
2949bool PreRARematStage::setObjective() {
2950 const Function &F = MF.getFunction();
2951
2952 // Set up "spilling targets" for all regions.
2953 unsigned MaxSGPRs = ST.getMaxNumSGPRs(F);
2954 unsigned MaxVGPRs = ST.getMaxNumVGPRs(F);
2955 bool HasVectorRegisterExcess = false;
2956 for (unsigned I = 0, E = DAG.Regions.size(); I != E; ++I) {
2957 const GCNRegPressure &RP = DAG.Pressure[I];
2958 GCNRPTarget &Target = RPTargets.emplace_back(MaxSGPRs, MaxVGPRs, MF, RP);
2959 if (!Target.satisfied())
2960 TargetRegions.set(I);
2961 HasVectorRegisterExcess |= Target.hasVectorRegisterExcess();
2962 }
2963
2964 if (HasVectorRegisterExcess || DAG.MinOccupancy >= MFI.getMaxWavesPerEU()) {
2965 // In addition to register usage being above addressable limits, occupancy
2966 // below the minimum is considered like "spilling" as well.
2967 TargetOcc = std::nullopt;
2968 } else {
2969 // There is no spilling and room to improve occupancy; set up "increased
2970 // occupancy targets" for all regions.
2971 TargetOcc = DAG.MinOccupancy + 1;
2972 const unsigned VGPRBlockSize = MFI.getDynamicVGPRBlockSize();
2973 MaxSGPRs = ST.getMaxNumSGPRs(*TargetOcc, false);
2974 MaxVGPRs = ST.getMaxNumVGPRs(*TargetOcc, VGPRBlockSize);
2975 for (auto [I, Target] : enumerate(RPTargets)) {
2976 Target.setTarget(MaxSGPRs, MaxVGPRs);
2977 if (!Target.satisfied())
2978 TargetRegions.set(I);
2979 }
2980 }
2981
2982 return TargetRegions.any();
2983}
2984
2985bool PreRARematStage::ScoredRemat::maybeBeneficial(
2986 const BitVector &TargetRegions, ArrayRef<GCNRPTarget> RPTargets) const {
2987 for (unsigned I : TargetRegions.set_bits()) {
2988 if (Live[I] && RPTargets[I].isSaveBeneficial(RPSave))
2989 return true;
2990 }
2991 return false;
2992}
2993
2996 assert(DAG.MLI && "MLI not defined in DAG");
2998 MachineBlockFrequencyInfo MBFI(MF, MBPI, *DAG.MLI);
2999
3000 const unsigned NumRegions = DAG.Regions.size();
3002 MaxFreq = 0;
3003 Regions.reserve(NumRegions);
3004 for (unsigned I = 0; I < NumRegions; ++I) {
3005 MachineBasicBlock *MBB = DAG.Regions[I].first->getParent();
3006 uint64_t BlockFreq = MBFI.getBlockFreq(MBB).getFrequency();
3007 Regions.push_back(BlockFreq);
3008 if (BlockFreq && BlockFreq < MinFreq)
3009 MinFreq = BlockFreq;
3010 else if (BlockFreq > MaxFreq)
3011 MaxFreq = BlockFreq;
3012 }
3013 if (!MinFreq)
3014 return;
3015
3016 // Scale everything down if frequencies are high.
3017 if (MinFreq >= ScaleFactor * ScaleFactor) {
3018 for (uint64_t &Freq : Regions)
3019 Freq /= ScaleFactor;
3020 MinFreq /= ScaleFactor;
3021 MaxFreq /= ScaleFactor;
3022 }
3023}
3024
3025void PreRARematStage::ScoredRemat::init(RegisterIdx RegIdx,
3026 const FreqInfo &Freq,
3027 const Rematerializer &Remater,
3029 this->RegIdx = RegIdx;
3030 const unsigned NumRegions = DAG.Regions.size();
3031 LiveIn.resize(NumRegions);
3032 LiveOut.resize(NumRegions);
3033 Live.resize(NumRegions);
3034 UnpredictableRPSave.resize(NumRegions);
3035
3036 const Rematerializer::Reg &Reg = Remater.getReg(RegIdx);
3037 Register DefReg = Reg.getDefReg();
3038 assert(Reg.Uses.size() == 1 && "expected users in single region");
3039 const unsigned UseRegion = Reg.Uses.begin()->first;
3040
3041 // Mark regions in which the rematerializable register is live.
3042 for (unsigned I = 0, E = NumRegions; I != E; ++I) {
3043 if (DAG.LiveIns[I].contains(DefReg))
3044 LiveIn.set(I);
3045 if (DAG.RegionLiveOuts.getLiveRegsForRegionIdx(I).contains(DefReg))
3046 LiveOut.set(I);
3047
3048 // If the register is both unused and live-through in the region, the
3049 // latter's RP is guaranteed to decrease.
3050 if (!LiveIn[I] || !LiveOut[I] || I == UseRegion)
3051 UnpredictableRPSave.set(I);
3052 }
3053 Live |= LiveIn;
3054 Live |= LiveOut;
3055 RPSave.inc(DefReg, LaneBitmask::getNone(), Reg.Mask, DAG.MRI);
3056
3057 // Get frequencies of defining and using regions. A rematerialization from the
3058 // least frequent region to the most frequent region will yield the greatest
3059 // in order to penalize rematerializations from or into regions whose
3060 int64_t DefOrMin = std::max(Freq.Regions[Reg.DefRegion], Freq.MinFreq);
3061 int64_t UseOrMax = Freq.Regions[UseRegion];
3062 if (!UseOrMax)
3063 UseOrMax = Freq.MaxFreq;
3064 FreqDiff = DefOrMin - UseOrMax;
3065}
3066
3067void PreRARematStage::ScoredRemat::update(const BitVector &TargetRegions,
3068 ArrayRef<GCNRPTarget> RPTargets,
3069 const FreqInfo &FreqInfo,
3070 bool ReduceSpill) {
3071 MaxFreq = 0;
3072 RegionImpact = 0;
3073 for (unsigned I : TargetRegions.set_bits()) {
3074 if (!Live[I])
3075 continue;
3076
3077 // The rematerialization must contribute positively in at least one
3078 // register class with usage above the RP target for this region to
3079 // contribute to the score.
3080 const GCNRPTarget &RegionTarget = RPTargets[I];
3081 const unsigned NumRegsBenefit = RegionTarget.getNumRegsBenefit(RPSave);
3082 if (!NumRegsBenefit)
3083 continue;
3084
3085 // Regions in which RP is guaranteed to decrease have more weight.
3086 RegionImpact += (UnpredictableRPSave[I] ? 1 : 2) * NumRegsBenefit;
3087
3088 if (ReduceSpill) {
3089 uint64_t Freq = FreqInfo.Regions[I];
3090 if (UnpredictableRPSave[I]) {
3091 // Apply a frequency penalty in regions in which we are not sure that RP
3092 // will decrease.
3093 Freq /= 2;
3094 }
3095 MaxFreq = std::max(MaxFreq, Freq);
3096 }
3097 }
3098}
3099
3100void PreRARematStage::ScoredRemat::rematerialize(
3101 Rematerializer &Remater) const {
3102 const Rematerializer::Reg &Reg = Remater.getReg(RegIdx);
3103 Rematerializer::DependencyReuseInfo DRI;
3104 for (RegisterIdx DepRegIdx : Reg.Dependencies)
3105 DRI.reuse(DepRegIdx);
3106 unsigned UseRegion = Reg.Uses.begin()->first;
3107 Remater.rematerializeToRegion(RegIdx, UseRegion, DRI);
3108}
3109
3110void PreRARematStage::updateRPTargets(const BitVector &Regions,
3111 const GCNRegPressure &RPSave) {
3112 for (unsigned I : Regions.set_bits()) {
3113 RPTargets[I].saveRP(RPSave);
3114 if (TargetRegions[I] && RPTargets[I].satisfied()) {
3115 REMAT_DEBUG(dbgs() << " [" << I << "] Target reached!\n");
3116 TargetRegions.reset(I);
3117 }
3118 }
3119}
3120
3121bool PreRARematStage::updateAndVerifyRPTargets(const BitVector &Regions) {
3122 bool TooOptimistic = false;
3123 for (unsigned I : Regions.set_bits()) {
3124 GCNRPTarget &Target = RPTargets[I];
3125 Target.setRP(DAG.getRealRegPressure(I));
3126
3127 // Since we were optimistic in assessing RP decreases in these regions, we
3128 // may need to remark the target as a target region if RP didn't decrease
3129 // as expected.
3130 if (!TargetRegions[I] && !Target.satisfied()) {
3131 REMAT_DEBUG(dbgs() << " [" << I << "] Incorrect RP estimation\n");
3132 TooOptimistic = true;
3133 TargetRegions.set(I);
3134 }
3135 }
3136 return TooOptimistic;
3137}
3138
3139void PreRARematStage::removeFromLiveMaps(Register Reg, const BitVector &LiveIn,
3140 const BitVector &LiveOut) {
3141 assert(LiveIn.size() == DAG.Regions.size() &&
3142 LiveOut.size() == DAG.Regions.size() && "region num mismatch");
3143 for (unsigned I : LiveIn.set_bits())
3144 DAG.LiveIns[I].erase(Reg);
3145 for (unsigned I : LiveOut.set_bits())
3146 DAG.RegionLiveOuts.getLiveRegsForRegionIdx(I).erase(Reg);
3147}
3148
3149void PreRARematStage::addToLiveMaps(Register Reg, LaneBitmask Mask,
3150 const BitVector &LiveIn,
3151 const BitVector &LiveOut) {
3152 assert(LiveIn.size() == DAG.Regions.size() &&
3153 LiveOut.size() == DAG.Regions.size() && "region num mismatch");
3154 std::pair<Register, LaneBitmask> LiveReg(Reg, Mask);
3155 for (unsigned I : LiveIn.set_bits())
3156 DAG.LiveIns[I].insert(LiveReg);
3157 for (unsigned I : LiveOut.set_bits())
3158 DAG.RegionLiveOuts.getLiveRegsForRegionIdx(I).insert(LiveReg);
3159}
3160
3162 // We consider that reducing spilling is always beneficial so we never
3163 // rollback rematerializations or revert scheduling in such cases.
3164 if (!TargetOcc)
3165 return;
3166
3167 // When increasing occupancy, it is possible that re-scheduling is not able to
3168 // achieve the target occupancy in all regions, in which case re-scheduling in
3169 // all regions should be reverted.
3170 if (DAG.MinOccupancy >= *TargetOcc)
3171 return;
3172
3173 // Revert re-scheduling in all affected regions.
3174 for (const auto &[RegionIdx, OrigMIOrder, MaxPressure] : RegionReverts) {
3175 REMAT_DEBUG(dbgs() << "Reverting re-scheduling in region " << RegionIdx
3176 << '\n');
3177 DAG.Pressure[RegionIdx] = MaxPressure;
3178 modifyRegionSchedule(RegionIdx, OrigMIOrder);
3179 }
3180
3181 // It is possible that re-scheduling lowers occupancy over the one achieved
3182 // just through rematerializations, in which case we revert re-scheduling in
3183 // all regions but do not roll back rematerializations.
3184 if (AchievedOcc >= *TargetOcc) {
3185 DAG.setTargetOccupancy(AchievedOcc);
3186 return;
3187 }
3188
3189 // Reset the target occupancy to what it was pre-rematerialization.
3190 DAG.setTargetOccupancy(*TargetOcc - 1);
3191
3192 // Roll back changes made by the stage, then recompute pressure in all
3193 // affected regions.
3194 REMAT_DEBUG(dbgs() << "==== ROLLBACK ====\n");
3195 assert(Rollback && "rollbacker should be defined");
3196 Rollback->Listener.rollback(Remater);
3197 for (const auto &[RegIdx, LiveIn, LiveOut] : Rollback->LiveMapUpdates) {
3198 const Rematerializer::Reg &Reg = Remater.getReg(RegIdx);
3199 addToLiveMaps(Reg.getDefReg(), Reg.Mask, LiveIn, LiveOut);
3200 }
3201
3202#ifdef EXPENSIVE_CHECKS
3203 // In particular, we want to check for coherent MI/slot order in regions in
3204 // which reverts and/or rollbacks may have happened.
3205 MF.verify();
3206#endif
3207 for (unsigned I : RescheduleRegions.set_bits())
3208 DAG.Pressure[I] = DAG.getRealRegPressure(I);
3209
3211}
3212
3213void GCNScheduleDAGMILive::setTargetOccupancy(unsigned TargetOccupancy) {
3214 MinOccupancy = TargetOccupancy;
3215 if (MFI.getOccupancy() < TargetOccupancy)
3216 MFI.increaseOccupancy(MF, MinOccupancy);
3217 else
3218 MFI.limitOccupancy(MinOccupancy);
3219}
3220
3222 const SIInstrInfo *SII = static_cast<const SIInstrInfo *>(DAG->TII);
3223 return any_of(*DAG, [SII](MachineBasicBlock::iterator MI) {
3224 return SII->isIGLPMutationOnly(MI->getOpcode());
3225 });
3226}
3227
3232
3234 HasIGLPInstrs = hasIGLPInstrs(this);
3235 if (HasIGLPInstrs) {
3236 SavedMutations.clear();
3237 SavedMutations.swap(Mutations);
3239 }
3240
3242}
3243
3245 if (HasIGLPInstrs)
3246 SavedMutations.swap(Mutations);
3247
3249}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static SUnit * pickOnlyChoice(SchedBoundary &Zone)
MachineBasicBlock & MBB
This file implements the BitVector class.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the GCNRegPressure class, which tracks registry pressure by bookkeeping number of S...
static cl::opt< bool > GCNTrackers("amdgpu-use-amdgpu-trackers", cl::Hidden, cl::desc("Use the AMDGPU specific RPTrackers during scheduling"), cl::init(false))
static cl::opt< bool > DisableClusteredLowOccupancy("amdgpu-disable-clustered-low-occupancy-reschedule", cl::Hidden, cl::desc("Disable clustered low occupancy " "rescheduling for ILP scheduling stage."), cl::init(false))
#define REMAT_PREFIX
Allows to easily filter for this stage's debug output.
static cl::opt< unsigned, false, VGPRThresholdParser > VGPRThresholdPercentOpt("amdgpu-vgpr-threshold-percent", cl::Hidden, cl::desc("Percent of VGPR limits that we should use as RP threshold " "during scheduling. We have two limits relevant to scheduling: " "Critical (avoid decreasing occupancy), Excess (avoid spilling). " "This flag scales both limits back by an equal percent: (0 = use " " default calculation, 1-100 = use percentage), default: 0"), cl::init(0))
static MachineInstr * getLastMIForRegion(MachineBasicBlock::iterator RegionBegin, MachineBasicBlock::iterator RegionEnd)
static bool shouldCheckPending(SchedBoundary &Zone, const TargetSchedModel *SchedModel)
static cl::opt< bool > RelaxedOcc("amdgpu-schedule-relaxed-occupancy", cl::Hidden, cl::desc("Relax occupancy targets for kernels which are memory " "bound (amdgpu-membound-threshold), or " "Wave Limited (amdgpu-limit-wave-threshold)."), cl::init(false))
#define REMAT_DEBUG(X)
static cl::opt< bool > DisableUnclusterHighRP("amdgpu-disable-unclustered-high-rp-reschedule", cl::Hidden, cl::desc("Disable unclustered high register pressure " "reduction scheduling stage."), cl::init(false))
static void printScheduleModel(std::set< std::pair< MachineInstr *, unsigned >, EarlierIssuingCycle > &ReadyCycles)
static bool isReachingDefAGPRForm(MachineInstr *RD, const SmallPtrSetImpl< MachineInstr * > &RewriteSet, const DenseSet< Register > &CandSrc2Regs, const SIInstrInfo &TII)
Returns true if reaching def RD will be in AGPR form after the rewrite and so needs no bridge copy: a...
static cl::opt< bool > PrintMaxRPRegUsageAfterScheduler("amdgpu-print-max-reg-pressure-regusage-after-scheduler", cl::Hidden, cl::desc("Print a list of live registers along with their def/uses at the " "point of maximum register pressure after scheduling."), cl::init(false))
static bool hasIGLPInstrs(ScheduleDAGInstrs *DAG)
static cl::opt< bool > DisableRewriteMFMAFormSchedStage("amdgpu-disable-rewrite-mfma-form-sched-stage", cl::Hidden, cl::desc("Disable rewrite mfma rewrite scheduling stage"), cl::init(true))
static bool canUsePressureDiffs(const SUnit &SU)
Checks whether SU can use the cached DAG pressure diffs to compute the current register pressure.
static cl::opt< unsigned > PendingQueueLimit("amdgpu-scheduler-pending-queue-limit", cl::Hidden, cl::desc("Max (Available+Pending) size to inspect pending queue (0 disables)"), cl::init(256))
static cl::opt< bool > PrintMaxRPRegUsageBeforeScheduler("amdgpu-print-max-reg-pressure-regusage-before-scheduler", cl::Hidden, cl::desc("Print a list of live registers along with their def/uses at the " "point of maximum register pressure before scheduling."), cl::init(false))
static cl::opt< unsigned > ScheduleMetricBias("amdgpu-schedule-metric-bias", cl::Hidden, cl::desc("Sets the bias which adds weight to occupancy vs latency. Set it to " "100 to chase the occupancy only."), cl::init(10))
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
#define _
static constexpr std::pair< StringLiteral, StringLiteral > ReplaceMap[]
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
static llvm::Error parse(GsymDataExtractor &Data, uint64_t BaseAddr, LineEntryCallback const &Callback)
Definition LineTable.cpp:54
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static constexpr unsigned SM(unsigned Version)
if(PassOpts->AAPipeline)
MIR-level target-independent rematerialization helpers.
This file contains some templates that are useful if you are working with the STL at all.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:178
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
bool shouldRevertScheduling(unsigned WavesAfter) override
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool erase(const KeyT &Val)
Definition DenseMap.h:377
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
bool reset(const MachineInstr &MI, MachineBasicBlock::const_iterator End, const LiveRegSet *LiveRegs=nullptr)
Reset tracker to the point before the MI filling LiveRegs upon this point using LIS.
GCNRegPressure bumpDownwardPressure(const MachineInstr *MI, const SIRegisterInfo *TRI) const
Mostly copy/paste from CodeGen/RegisterPressure.cpp Calculate the impact MI will have on CurPressure ...
GCNMaxILPSchedStrategy(const MachineSchedContext *C)
bool tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const override
Apply a set of heuristics to a new candidate.
bool tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const override
GCNMaxMemoryClauseSchedStrategy tries best to clause memory instructions as much as possible.
GCNMaxMemoryClauseSchedStrategy(const MachineSchedContext *C)
GCNMaxOccupancySchedStrategy(const MachineSchedContext *C, bool IsLegacyScheduler=false)
void finalizeSchedule() override
Allow targets to perform final scheduling actions at the level of the whole MachineFunction.
void schedule() override
Orders nodes according to selected style.
GCNPostScheduleDAGMILive(MachineSchedContext *C, std::unique_ptr< MachineSchedStrategy > S, bool RemoveKillFlags)
Models a register pressure target, allowing to evaluate and track register savings against that targe...
unsigned getNumRegsBenefit(const GCNRegPressure &SaveRP) const
Returns the benefit towards achieving the RP target that saving SaveRP represents,...
GCNRegPressure getPressure() const
GCNSchedStrategy & S
GCNRegPressure PressureBefore
bool isRegionWithExcessRP() const
void modifyRegionSchedule(unsigned RegionIdx, ArrayRef< MachineInstr * > MIOrder)
Sets the schedule of region RegionIdx to MIOrder.
bool mayCauseSpilling(unsigned WavesAfter)
ScheduleMetrics getScheduleMetrics(const std::vector< SUnit > &InputSchedule)
GCNScheduleDAGMILive & DAG
const GCNSchedStageID StageID
std::vector< MachineInstr * > Unsched
GCNRegPressure PressureAfter
MachineFunction & MF
virtual void finalizeGCNRegion()
SIMachineFunctionInfo & MFI
unsigned computeSUnitReadyCycle(const SUnit &SU, unsigned CurrCycle, DenseMap< unsigned, unsigned > &ReadyCycles, const TargetSchedModel &SM)
virtual void finalizeGCNSchedStage()
virtual bool initGCNSchedStage()
virtual bool shouldRevertScheduling(unsigned WavesAfter)
std::vector< std::unique_ptr< ScheduleDAGMutation > > SavedMutations
GCNSchedStage(GCNSchedStageID StageID, GCNScheduleDAGMILive &DAG)
MachineBasicBlock * CurrentMBB
const GCNSubtarget & ST
This is a minimal scheduler strategy.
GCNDownwardRPTracker DownwardTracker
void getRegisterPressures(bool AtTop, const RegPressureTracker &RPTracker, SUnit *SU, std::vector< unsigned > &Pressure, std::vector< unsigned > &MaxPressure, GCNDownwardRPTracker &DownwardTracker, GCNUpwardRPTracker &UpwardTracker, ScheduleDAGMI *DAG, const SIRegisterInfo *SRI)
GCNSchedStrategy(const MachineSchedContext *C)
SmallVector< GCNSchedStageID, 4 > SchedStages
std::vector< unsigned > MaxPressure
SUnit * pickNodeBidirectional(bool &IsTopNode, bool &PickedPending)
GCNSchedStageID getCurrentStage()
bool tryPendingCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const
Evaluates instructions in the pending queue using a subset of scheduling heuristics.
SmallVectorImpl< GCNSchedStageID >::iterator CurrentStage
void schedNode(SUnit *SU, bool IsTopNode) override
Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an instruction and updated scheduled/rem...
std::optional< bool > GCNTrackersOverride
GCNDownwardRPTracker * getDownwardTracker()
std::vector< unsigned > Pressure
void initialize(ScheduleDAGMI *DAG) override
Initialize the strategy after building the DAG for a new region.
GCNUpwardRPTracker UpwardTracker
void printCandidateDecision(const SchedCandidate &Current, const SchedCandidate &Preferred)
void pickNodeFromQueue(SchedBoundary &Zone, const CandPolicy &ZonePolicy, const RegPressureTracker &RPTracker, SchedCandidate &Cand, bool &IsPending, bool IsBottomUp)
unsigned getStructuralStallCycles(SchedBoundary &Zone, SUnit *SU) const
Estimate how many cycles SU must wait due to structural hazards at the current boundary cycle.
void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop, const RegPressureTracker &RPTracker, const SIRegisterInfo *SRI, unsigned SGPRPressure, unsigned VGPRPressure, bool IsBottomUp)
SUnit * pickNode(bool &IsTopNode) override
Pick the next node to schedule, or return NULL.
GCNUpwardRPTracker * getUpwardTracker()
GCNSchedStageID getNextStage() const
void finalizeSchedule() override
Allow targets to perform final scheduling actions at the level of the whole MachineFunction.
void schedule() override
Orders nodes according to selected style.
GCNScheduleDAGMILive(MachineSchedContext *C, std::unique_ptr< MachineSchedStrategy > S)
void recede(const MachineInstr &MI)
Move to the state of RP just before the MI .
void reset(const MachineInstr &MI)
Resets tracker to the point just after MI (in program order), which can be a debug instruction.
void traceCandidate(const SchedCandidate &Cand)
LLVM_ABI void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone, SchedBoundary *OtherZone)
Set the CandPolicy given a scheduling zone given the current resources and latencies inside and outsi...
MachineSchedPolicy RegionPolicy
const TargetSchedModel * SchedModel
const MachineSchedContext * Context
const TargetRegisterInfo * TRI
SchedCandidate BotCand
Candidate last picked from Bot boundary.
SchedCandidate TopCand
Candidate last picked from Top boundary.
virtual bool tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const
Apply a set of heuristics to a new candidate.
ScheduleDAGMILive * DAG
void initialize(ScheduleDAGMI *dag) override
Initialize the strategy after building the DAG for a new region.
void schedNode(SUnit *SU, bool IsTopNode) override
Update the scheduler's state after scheduling a node.
GenericScheduler(const MachineSchedContext *C)
bool shouldRevertScheduling(unsigned WavesAfter) override
LiveInterval - This class represents the liveness of a register, or stack slot.
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
LLVM_ABI void dump() const
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
uint8_t getCopyCost() const
getCopyCost - Return the cost of copying a value between two registers in this class.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI BlockFrequency getEntryFreq() const
Divide a block's BlockFrequency::getFrequency() value by this value to obtain the entry block - relat...
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isCopy() const
const MachineBasicBlock * getParent() const
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
mop_range operands()
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
bool shouldRevertScheduling(unsigned WavesAfter) override
bool shouldRevertScheduling(unsigned WavesAfter) override
bool shouldRevertScheduling(unsigned WavesAfter) override
void finalizeGCNRegion() override
bool initGCNSchedStage() override
Capture a change in pressure for a single pressure set.
Simple wrapper around std::function<void(raw_ostream&)>.
Definition Printable.h:38
Helpers for implementing custom MachineSchedStrategy classes.
unsigned size() const
Track the current register pressure at some position in the instruction stream, and remember the high...
LLVM_ABI void advance()
Advance across the current instruction.
LLVM_ABI void getDownwardPressure(const MachineInstr *MI, std::vector< unsigned > &PressureResult, std::vector< unsigned > &MaxPressureResult)
Get the pressure of each PSet after traversing this instruction top-down.
const std::vector< unsigned > & getRegSetPressureAtPos() const
Get the register set pressure at the current position, which may be less than the pressure across the...
LLVM_ABI void getUpwardPressure(const MachineInstr *MI, std::vector< unsigned > &PressureResult, std::vector< unsigned > &MaxPressureResult)
Get the pressure of each PSet after traversing this instruction bottom-up.
List of registers defined and used by a machine instruction.
LLVM_ABI void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, bool TrackLaneMasks, bool IgnoreDead)
Analyze the given instruction MI and fill in the Uses, Defs and DeadDefs list based on the MachineOpe...
LLVM_ABI void adjustLaneLiveness(const LiveIntervals &LIS, const MachineRegisterInfo &MRI, SlotIndex Pos, MachineInstr *AddFlagsMI=nullptr)
Use liveness information to find out which uses/defs are partially undefined/dead and adjust the VReg...
LLVM_ABI void detectDeadDefs(const MachineInstr &MI, const LiveIntervals &LIS)
Use liveness information to find dead defs not marked with a dead flag and move them to the DeadDefs ...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
MIR-level target-independent rematerializer.
bool isIGLPMutationOnly(unsigned Opcode) const
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
Scheduling unit. This is a node in the scheduling DAG.
bool isInstr() const
Returns true if this SUnit refers to a machine instruction as opposed to an SDNode.
unsigned TopReadyCycle
Cycle relative to start when node is ready.
unsigned NodeNum
Entry # of node in the node vector.
unsigned short Latency
Node latency.
bool isScheduled
True once scheduled.
unsigned ParentClusterIdx
The parent cluster id.
unsigned BotReadyCycle
Cycle relative to end when node is ready.
bool hasReservedResource
Uses a reserved resource.
bool isBottomReady() const
bool isTopReady() const
SmallVector< SDep, 4 > Preds
All sunit predecessors.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
Each Scheduling boundary is associated with ready queues.
LLVM_ABI void releasePending()
Release pending ready nodes in to the available queue.
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.
ScheduleHazardRecognizer * HazardRec
LLVM_ABI void bumpCycle(unsigned NextCycle)
Move the boundary of scheduled code by one cycle.
unsigned getCurrMOps() const
Micro-ops issued in the current cycle.
unsigned getCurrCycle() const
Number of cycles to issue the instructions scheduled in this zone.
LLVM_ABI bool checkHazard(SUnit *SU)
Does this SU have a hazard within the current instruction group.
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.
bool ScheduleSingleMIRegions
True if regions with a single MI should be scheduled.
MachineBasicBlock::iterator RegionEnd
The end of the range to be scheduled.
virtual void finalizeSchedule()
Allow targets to perform final scheduling actions at the level of the whole MachineFunction.
virtual void exitRegion()
Called when the scheduler has finished scheduling the current region.
const MachineLoopInfo * MLI
bool RemoveKillFlags
True if the DAG builder should remove kill flags (in preparation for rescheduling).
MachineBasicBlock::iterator RegionBegin
The beginning of the range to be scheduled.
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
ScheduleDAGMILive(MachineSchedContext *C, std::unique_ptr< MachineSchedStrategy > S)
RegPressureTracker RPTracker
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.
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
ScheduleDAGMI(MachineSchedContext *C, std::unique_ptr< MachineSchedStrategy > S, bool RemoveKillFlags)
std::vector< std::unique_ptr< ScheduleDAGMutation > > Mutations
Ordered list of DAG postprocessing steps.
MachineRegisterInfo & MRI
Virtual/real register map.
const TargetInstrInfo * TII
Target instruction information.
MachineFunction & MF
Machine function.
static const unsigned ScaleFactor
unsigned getMetric() const
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
static bool isEarlierInstr(SlotIndex A, SlotIndex B)
isEarlierInstr - Return true if A refers to an instruction earlier than B.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
Provide an instruction scheduling machine model to CodeGen passes.
LLVM_ABI bool hasInstrSchedModel() const
Return true if this machine model includes an instruction-level scheduling model.
unsigned getMicroOpBufferSize() const
Number of micro-ops that may be buffered for OOO execution.
bool shouldRevertScheduling(unsigned WavesAfter) override
VNInfo - Value Number Information.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned getAddressableNumVGPRs(const MCSubtargetInfo &STI, unsigned DynamicVGPRBlockSize)
unsigned getAllocatedNumVGPRBlocks(const MCSubtargetInfo &STI, unsigned NumVGPRs, unsigned DynamicVGPRBlockSize, std::optional< bool > EnableWavefrontSize32)
unsigned getVGPRAllocGranule(const MCSubtargetInfo &STI, unsigned DynamicVGPRBlockSize, std::optional< bool > EnableWavefrontSize32)
LLVM_READONLY int32_t getMFMASrcCVDstAGPROp(uint32_t Opcode)
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This namespace contains all of the command line option processing machinery.
Definition MCSchedule.h:35
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:387
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.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI unsigned getWeakLeft(const SUnit *SU, bool isTop)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
InstructionCost Cost
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
GCNRegPressure getRegPressure(const MachineRegisterInfo &MRI, Range &&LiveRegs)
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.
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:547
std::pair< MachineBasicBlock::iterator, MachineBasicBlock::iterator > RegionBoundaries
A region's boundaries i.e.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool tryPressure(const PressureChange &TryP, const PressureChange &CandP, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason, const TargetRegisterInfo *TRI, const MachineFunction &MF)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI cl::opt< bool > VerifyScheduling
LLVM_ABI bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary &Zone)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IterT skipDebugInstructionsBackward(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It until it points to a non-debug instruction or to Begin and return the resulting iterator...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
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)
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
DenseMap< MachineInstr *, GCNRPTracker::LiveRegSet > getLiveRegMap(Range &&R, bool After, LiveIntervals &LIS)
creates a map MachineInstr -> LiveRegSet R - range of iterators on instructions After - upon entry or...
GCNRPTracker::LiveRegSet getLiveRegsBefore(const MachineInstr &MI, const LiveIntervals &LIS)
LLVM_ABI bool tryLess(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
Return true if this heuristic determines order.
LLVM_ABI void dumpMaxRegPressure(MachineFunction &MF, GCNRegPressure::RegKind Kind, LiveIntervals &LIS, const MachineLoopInfo *MLI)
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
bool operator()(std::pair< MachineInstr *, unsigned > A, std::pair< MachineInstr *, unsigned > B) const
unsigned getArchVGPRNum() const
unsigned getAGPRNum() const
unsigned getSGPRNum() const
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...
void reset(const CandPolicy &NewPolicy)
LLVM_ABI void initResourceDelta(const ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
Status of an instruction's critical resource consumption.
constexpr bool any() const
Definition LaneBitmask.h:53
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition MCSchedule.h:129
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
Definition MCSchedule.h:74
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
Execution frequency information required by scoring heuristics.
SmallVector< uint64_t > Regions
Per-region execution frequencies. 0 when unknown.
uint64_t MinFreq
Minimum and maximum observed frequencies.
FreqInfo(MachineFunction &MF, const GCNScheduleDAGMILive &DAG)
DependencyReuseInfo & reuse(RegisterIdx DepIdx)
A rematerializable register defined by a single machine instruction.
MachineInstr * DefMI
Single MI defining the rematerializable register.
SmallDenseMap< unsigned, RegionUsers, 2 > Uses
Uses of the register, mapped by region.
SmallVector< RegisterIdx, 2 > Dependencies
This register's rematerializable dependencies, one per unique rematerializable register operand.