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