LLVM 22.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 "GCNRegPressure.h"
31#include "llvm/ADT/STLExtras.h"
34#include "llvm/MC/LaneBitmask.h"
36
37#define DEBUG_TYPE "machine-scheduler"
38
39using namespace llvm;
40
42 "amdgpu-disable-unclustered-high-rp-reschedule", cl::Hidden,
43 cl::desc("Disable unclustered high register pressure "
44 "reduction scheduling stage."),
45 cl::init(false));
46
48 "amdgpu-disable-clustered-low-occupancy-reschedule", cl::Hidden,
49 cl::desc("Disable clustered low occupancy "
50 "rescheduling for ILP scheduling stage."),
51 cl::init(false));
52
54 "amdgpu-schedule-metric-bias", cl::Hidden,
56 "Sets the bias which adds weight to occupancy vs latency. Set it to "
57 "100 to chase the occupancy only."),
58 cl::init(10));
59
60static cl::opt<bool>
61 RelaxedOcc("amdgpu-schedule-relaxed-occupancy", cl::Hidden,
62 cl::desc("Relax occupancy targets for kernels which are memory "
63 "bound (amdgpu-membound-threshold), or "
64 "Wave Limited (amdgpu-limit-wave-threshold)."),
65 cl::init(false));
66
68 "amdgpu-use-amdgpu-trackers", cl::Hidden,
69 cl::desc("Use the AMDGPU specific RPTrackers during scheduling"),
70 cl::init(false));
71
73 "amdgpu-scheduler-pending-queue-limit", cl::Hidden,
75 "Max (Available+Pending) size to inspect pending queue (0 disables)"),
76 cl::init(256));
77
78#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
79#define DUMP_MAX_REG_PRESSURE
81 "amdgpu-print-max-reg-pressure-regusage-before-scheduler", cl::Hidden,
82 cl::desc("Print a list of live registers along with their def/uses at the "
83 "point of maximum register pressure before scheduling."),
84 cl::init(false));
85
87 "amdgpu-print-max-reg-pressure-regusage-after-scheduler", cl::Hidden,
88 cl::desc("Print a list of live registers along with their def/uses at the "
89 "point of maximum register pressure after scheduling."),
90 cl::init(false));
91#endif
92
93const unsigned ScheduleMetrics::ScaleFactor = 100;
94
99
102
103 MF = &DAG->MF;
104
105 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
106
108 Context->RegClassInfo->getNumAllocatableRegs(&AMDGPU::SGPR_32RegClass);
110 Context->RegClassInfo->getNumAllocatableRegs(&AMDGPU::VGPR_32RegClass);
111
113 // Set the initial TargetOccupnacy to the maximum occupancy that we can
114 // achieve for this function. This effectively sets a lower bound on the
115 // 'Critical' register limits in the scheduler.
116 // Allow for lower occupancy targets if kernel is wave limited or memory
117 // bound, and using the relaxed occupancy feature.
121 std::min(ST.getMaxNumSGPRs(TargetOccupancy, true), SGPRExcessLimit);
122
123 if (!KnownExcessRP) {
124 VGPRCriticalLimit = std::min(
125 ST.getMaxNumVGPRs(TargetOccupancy, MFI.getDynamicVGPRBlockSize()),
127 } else {
128 // This is similar to ST.getMaxNumVGPRs(TargetOccupancy) result except
129 // returns a reasonably small number for targets with lots of VGPRs, such
130 // as GFX10 and GFX11.
131 LLVM_DEBUG(dbgs() << "Region is known to spill, use alternative "
132 "VGPRCriticalLimit calculation method.\n");
133 unsigned DynamicVGPRBlockSize = MFI.getDynamicVGPRBlockSize();
134 unsigned Granule =
135 AMDGPU::IsaInfo::getVGPRAllocGranule(&ST, DynamicVGPRBlockSize);
136 unsigned Addressable =
137 AMDGPU::IsaInfo::getAddressableNumVGPRs(&ST, DynamicVGPRBlockSize);
138 unsigned VGPRBudget = alignDown(Addressable / TargetOccupancy, Granule);
139 VGPRBudget = std::max(VGPRBudget, Granule);
140 VGPRCriticalLimit = std::min(VGPRBudget, VGPRExcessLimit);
141 }
142
143 // Subtract error margin and bias from register limits and avoid overflow.
148
149 LLVM_DEBUG(dbgs() << "VGPRCriticalLimit = " << VGPRCriticalLimit
150 << ", VGPRExcessLimit = " << VGPRExcessLimit
151 << ", SGPRCriticalLimit = " << SGPRCriticalLimit
152 << ", SGPRExcessLimit = " << SGPRExcessLimit << "\n\n");
153}
154
155/// Checks whether \p SU can use the cached DAG pressure diffs to compute the
156/// current register pressure.
157///
158/// This works for the common case, but it has a few exceptions that have been
159/// observed through trial and error:
160/// - Explicit physical register operands
161/// - Subregister definitions
162///
163/// In both of those cases, PressureDiff doesn't represent the actual pressure,
164/// and querying LiveIntervals through the RegPressureTracker is needed to get
165/// an accurate value.
166///
167/// We should eventually only use PressureDiff for maximum performance, but this
168/// already allows 80% of SUs to take the fast path without changing scheduling
169/// at all. Further changes would either change scheduling, or require a lot
170/// more logic to recover an accurate pressure estimate from the PressureDiffs.
171static bool canUsePressureDiffs(const SUnit &SU) {
172 if (!SU.isInstr())
173 return false;
174
175 // Cannot use pressure diffs for subregister defs or with physregs, it's
176 // imprecise in both cases.
177 for (const auto &Op : SU.getInstr()->operands()) {
178 if (!Op.isReg() || Op.isImplicit())
179 continue;
180 if (Op.getReg().isPhysical() ||
181 (Op.isDef() && Op.getSubReg() != AMDGPU::NoSubRegister))
182 return false;
183 }
184 return true;
185}
186
188 bool AtTop, const RegPressureTracker &RPTracker, SUnit *SU,
189 std::vector<unsigned> &Pressure, std::vector<unsigned> &MaxPressure,
190 GCNDownwardRPTracker &DownwardTracker, GCNUpwardRPTracker &UpwardTracker,
191 ScheduleDAGMI *DAG, const SIRegisterInfo *SRI) {
192 // getDownwardPressure() and getUpwardPressure() make temporary changes to
193 // the tracker, so we need to pass those function a non-const copy.
194 RegPressureTracker &TempTracker = const_cast<RegPressureTracker &>(RPTracker);
195 if (!GCNTrackers) {
196 AtTop
197 ? TempTracker.getDownwardPressure(SU->getInstr(), Pressure, MaxPressure)
198 : TempTracker.getUpwardPressure(SU->getInstr(), Pressure, MaxPressure);
199
200 return;
201 }
202
203 // GCNTrackers
204 Pressure.resize(4, 0);
205 MachineInstr *MI = SU->getInstr();
206 GCNRegPressure NewPressure;
207 if (AtTop) {
208 GCNDownwardRPTracker TempDownwardTracker(DownwardTracker);
209 NewPressure = TempDownwardTracker.bumpDownwardPressure(MI, SRI);
210 } else {
211 GCNUpwardRPTracker TempUpwardTracker(UpwardTracker);
212 TempUpwardTracker.recede(*MI);
213 NewPressure = TempUpwardTracker.getPressure();
214 }
215 Pressure[AMDGPU::RegisterPressureSets::SReg_32] = NewPressure.getSGPRNum();
216 Pressure[AMDGPU::RegisterPressureSets::VGPR_32] =
217 NewPressure.getArchVGPRNum();
218 Pressure[AMDGPU::RegisterPressureSets::AGPR_32] = NewPressure.getAGPRNum();
219}
220
222 bool AtTop,
223 const RegPressureTracker &RPTracker,
224 const SIRegisterInfo *SRI,
225 unsigned SGPRPressure,
226 unsigned VGPRPressure, bool IsBottomUp) {
227 Cand.SU = SU;
228 Cand.AtTop = AtTop;
229
230 if (!DAG->isTrackingPressure())
231 return;
232
233 Pressure.clear();
234 MaxPressure.clear();
235
236 // We try to use the cached PressureDiffs in the ScheduleDAG whenever
237 // possible over querying the RegPressureTracker.
238 //
239 // RegPressureTracker will make a lot of LIS queries which are very
240 // expensive, it is considered a slow function in this context.
241 //
242 // PressureDiffs are precomputed and cached, and getPressureDiff is just a
243 // trivial lookup into an array. It is pretty much free.
244 //
245 // In EXPENSIVE_CHECKS, we always query RPTracker to verify the results of
246 // PressureDiffs.
247 if (AtTop || !canUsePressureDiffs(*SU) || GCNTrackers) {
248 getRegisterPressures(AtTop, RPTracker, SU, Pressure, MaxPressure,
250 } else {
251 // Reserve 4 slots.
252 Pressure.resize(4, 0);
253 Pressure[AMDGPU::RegisterPressureSets::SReg_32] = SGPRPressure;
254 Pressure[AMDGPU::RegisterPressureSets::VGPR_32] = VGPRPressure;
255
256 for (const auto &Diff : DAG->getPressureDiff(SU)) {
257 if (!Diff.isValid())
258 continue;
259 // PressureDiffs is always bottom-up so if we're working top-down we need
260 // to invert its sign.
261 Pressure[Diff.getPSet()] +=
262 (IsBottomUp ? Diff.getUnitInc() : -Diff.getUnitInc());
263 }
264
265#ifdef EXPENSIVE_CHECKS
266 std::vector<unsigned> CheckPressure, CheckMaxPressure;
267 getRegisterPressures(AtTop, RPTracker, SU, CheckPressure, CheckMaxPressure,
269 if (Pressure[AMDGPU::RegisterPressureSets::SReg_32] !=
270 CheckPressure[AMDGPU::RegisterPressureSets::SReg_32] ||
271 Pressure[AMDGPU::RegisterPressureSets::VGPR_32] !=
272 CheckPressure[AMDGPU::RegisterPressureSets::VGPR_32]) {
273 errs() << "Register Pressure is inaccurate when calculated through "
274 "PressureDiff\n"
275 << "SGPR got " << Pressure[AMDGPU::RegisterPressureSets::SReg_32]
276 << ", expected "
277 << CheckPressure[AMDGPU::RegisterPressureSets::SReg_32] << "\n"
278 << "VGPR got " << Pressure[AMDGPU::RegisterPressureSets::VGPR_32]
279 << ", expected "
280 << CheckPressure[AMDGPU::RegisterPressureSets::VGPR_32] << "\n";
281 report_fatal_error("inaccurate register pressure calculation");
282 }
283#endif
284 }
285
286 unsigned NewSGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
287 unsigned NewVGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
288
289 // If two instructions increase the pressure of different register sets
290 // by the same amount, the generic scheduler will prefer to schedule the
291 // instruction that increases the set with the least amount of registers,
292 // which in our case would be SGPRs. This is rarely what we want, so
293 // when we report excess/critical register pressure, we do it either
294 // only for VGPRs or only for SGPRs.
295
296 // FIXME: Better heuristics to determine whether to prefer SGPRs or VGPRs.
297 const unsigned MaxVGPRPressureInc = 16;
298 bool ShouldTrackVGPRs = VGPRPressure + MaxVGPRPressureInc >= VGPRExcessLimit;
299 bool ShouldTrackSGPRs = !ShouldTrackVGPRs && SGPRPressure >= SGPRExcessLimit;
300
301 // FIXME: We have to enter REG-EXCESS before we reach the actual threshold
302 // to increase the likelihood we don't go over the limits. We should improve
303 // the analysis to look through dependencies to find the path with the least
304 // register pressure.
305
306 // We only need to update the RPDelta for instructions that increase register
307 // pressure. Instructions that decrease or keep reg pressure the same will be
308 // marked as RegExcess in tryCandidate() when they are compared with
309 // instructions that increase the register pressure.
310 if (ShouldTrackVGPRs && NewVGPRPressure >= VGPRExcessLimit) {
311 HasHighPressure = true;
312 Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
313 Cand.RPDelta.Excess.setUnitInc(NewVGPRPressure - VGPRExcessLimit);
314 }
315
316 if (ShouldTrackSGPRs && NewSGPRPressure >= SGPRExcessLimit) {
317 HasHighPressure = true;
318 Cand.RPDelta.Excess = PressureChange(AMDGPU::RegisterPressureSets::SReg_32);
319 Cand.RPDelta.Excess.setUnitInc(NewSGPRPressure - SGPRExcessLimit);
320 }
321
322 // Register pressure is considered 'CRITICAL' if it is approaching a value
323 // that would reduce the wave occupancy for the execution unit. When
324 // register pressure is 'CRITICAL', increasing SGPR and VGPR pressure both
325 // has the same cost, so we don't need to prefer one over the other.
326
327 int SGPRDelta = NewSGPRPressure - SGPRCriticalLimit;
328 int VGPRDelta = NewVGPRPressure - VGPRCriticalLimit;
329
330 if (SGPRDelta >= 0 || VGPRDelta >= 0) {
331 HasHighPressure = true;
332 if (SGPRDelta > VGPRDelta) {
333 Cand.RPDelta.CriticalMax =
334 PressureChange(AMDGPU::RegisterPressureSets::SReg_32);
335 Cand.RPDelta.CriticalMax.setUnitInc(SGPRDelta);
336 } else {
337 Cand.RPDelta.CriticalMax =
338 PressureChange(AMDGPU::RegisterPressureSets::VGPR_32);
339 Cand.RPDelta.CriticalMax.setUnitInc(VGPRDelta);
340 }
341 }
342}
343
345 const TargetSchedModel *SchedModel) {
346 bool HasBufferedModel =
347 SchedModel->hasInstrSchedModel() && SchedModel->getMicroOpBufferSize();
348 unsigned Combined = Zone.Available.size() + Zone.Pending.size();
349 return Combined <= PendingQueueLimit && HasBufferedModel;
350}
351
353 const TargetSchedModel *SchedModel) {
354 // pickOnlyChoice() releases pending instructions and checks for new hazards.
355 SUnit *OnlyChoice = Zone.pickOnlyChoice();
356 if (!shouldCheckPending(Zone, SchedModel) || Zone.Pending.empty())
357 return OnlyChoice;
358
359 return nullptr;
360}
361
363 const SchedCandidate &Preferred) {
364 LLVM_DEBUG({
365 dbgs() << "Prefer:\t\t";
366 DAG->dumpNode(*Preferred.SU);
367
368 if (Current.SU) {
369 dbgs() << "Not:\t";
370 DAG->dumpNode(*Current.SU);
371 }
372
373 dbgs() << "Reason:\t\t";
374 traceCandidate(Preferred);
375 });
376}
377
378// This function is mostly cut and pasted from
379// GenericScheduler::pickNodeFromQueue()
381 const CandPolicy &ZonePolicy,
382 const RegPressureTracker &RPTracker,
383 SchedCandidate &Cand, bool &IsPending,
384 bool IsBottomUp) {
385 const SIRegisterInfo *SRI = static_cast<const SIRegisterInfo *>(TRI);
387 unsigned SGPRPressure = 0;
388 unsigned VGPRPressure = 0;
389 IsPending = false;
390 if (DAG->isTrackingPressure()) {
391 if (!GCNTrackers) {
392 SGPRPressure = Pressure[AMDGPU::RegisterPressureSets::SReg_32];
393 VGPRPressure = Pressure[AMDGPU::RegisterPressureSets::VGPR_32];
394 } else {
395 GCNRPTracker *T = IsBottomUp
396 ? static_cast<GCNRPTracker *>(&UpwardTracker)
397 : static_cast<GCNRPTracker *>(&DownwardTracker);
398 SGPRPressure = T->getPressure().getSGPRNum();
399 VGPRPressure = T->getPressure().getArchVGPRNum();
400 }
401 }
402 LLVM_DEBUG(dbgs() << "Available Q:\n");
403 ReadyQueue &AQ = Zone.Available;
404 for (SUnit *SU : AQ) {
405
406 SchedCandidate TryCand(ZonePolicy);
407 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, SRI, SGPRPressure,
408 VGPRPressure, IsBottomUp);
409 // Pass SchedBoundary only when comparing nodes from the same boundary.
410 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
411 tryCandidate(Cand, TryCand, ZoneArg);
412 if (TryCand.Reason != NoCand) {
413 // Initialize resource delta if needed in case future heuristics query it.
414 if (TryCand.ResDelta == SchedResourceDelta())
415 TryCand.initResourceDelta(Zone.DAG, SchedModel);
416 LLVM_DEBUG(printCandidateDecision(Cand, TryCand));
417 Cand.setBest(TryCand);
418 } else {
419 printCandidateDecision(TryCand, Cand);
420 }
421 }
422
423 if (!shouldCheckPending(Zone, SchedModel))
424 return;
425
426 LLVM_DEBUG(dbgs() << "Pending Q:\n");
427 ReadyQueue &PQ = Zone.Pending;
428 for (SUnit *SU : PQ) {
429
430 SchedCandidate TryCand(ZonePolicy);
431 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, SRI, SGPRPressure,
432 VGPRPressure, IsBottomUp);
433 // Pass SchedBoundary only when comparing nodes from the same boundary.
434 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
435 tryPendingCandidate(Cand, TryCand, ZoneArg);
436 if (TryCand.Reason != NoCand) {
437 // Initialize resource delta if needed in case future heuristics query it.
438 if (TryCand.ResDelta == SchedResourceDelta())
439 TryCand.initResourceDelta(Zone.DAG, SchedModel);
440 LLVM_DEBUG(printCandidateDecision(Cand, TryCand));
441 IsPending = true;
442 Cand.setBest(TryCand);
443 } else {
444 printCandidateDecision(TryCand, Cand);
445 }
446 }
447}
448
449// This function is mostly cut and pasted from
450// GenericScheduler::pickNodeBidirectional()
452 bool &PickedPending) {
453 // Schedule as far as possible in the direction of no choice. This is most
454 // efficient, but also provides the best heuristics for CriticalPSets.
455 if (SUnit *SU = pickOnlyChoice(Bot, SchedModel)) {
456 IsTopNode = false;
457 return SU;
458 }
459 if (SUnit *SU = pickOnlyChoice(Top, SchedModel)) {
460 IsTopNode = true;
461 return SU;
462 }
463 // Set the bottom-up policy based on the state of the current bottom zone
464 // and the instructions outside the zone, including the top zone.
465 CandPolicy BotPolicy;
466 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
467 // Set the top-down policy based on the state of the current top zone and
468 // the instructions outside the zone, including the bottom zone.
469 CandPolicy TopPolicy;
470 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
471
472 bool BotPending = false;
473 // See if BotCand is still valid (because we previously scheduled from Top).
474 LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
475 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
476 BotCand.Policy != BotPolicy) {
477 BotCand.reset(CandPolicy());
478 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand,
479 BotPending,
480 /*IsBottomUp=*/true);
481 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
482 } else {
484#ifndef NDEBUG
485 if (VerifyScheduling) {
486 SchedCandidate TCand;
487 TCand.reset(CandPolicy());
488 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand,
489 BotPending,
490 /*IsBottomUp=*/true);
491 assert(TCand.SU == BotCand.SU &&
492 "Last pick result should correspond to re-picking right now");
493 }
494#endif
495 }
496
497 bool TopPending = false;
498 // Check if the top Q has a better candidate.
499 LLVM_DEBUG(dbgs() << "Picking from Top:\n");
500 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
501 TopCand.Policy != TopPolicy) {
502 TopCand.reset(CandPolicy());
503 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand,
504 TopPending,
505 /*IsBottomUp=*/false);
506 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
507 } else {
509#ifndef NDEBUG
510 if (VerifyScheduling) {
511 SchedCandidate TCand;
512 TCand.reset(CandPolicy());
513 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand,
514 TopPending,
515 /*IsBottomUp=*/false);
516 assert(TCand.SU == TopCand.SU &&
517 "Last pick result should correspond to re-picking right now");
518 }
519#endif
520 }
521
522 // Pick best from BotCand and TopCand.
523 LLVM_DEBUG(dbgs() << "Top Cand: "; traceCandidate(TopCand);
524 dbgs() << "Bot Cand: "; traceCandidate(BotCand););
525 SchedCandidate Cand = BotPending ? TopCand : BotCand;
526 SchedCandidate TryCand = BotPending ? BotCand : TopCand;
527 PickedPending = BotPending && TopPending;
528
529 TryCand.Reason = NoCand;
530 if (BotPending || TopPending) {
531 PickedPending |= tryPendingCandidate(Cand, TopCand, nullptr);
532 } else {
533 tryCandidate(Cand, TryCand, nullptr);
534 }
535
536 if (TryCand.Reason != NoCand) {
537 Cand.setBest(TryCand);
538 }
539
540 LLVM_DEBUG(dbgs() << "Picking: "; traceCandidate(Cand););
541
542 IsTopNode = Cand.AtTop;
543 return Cand.SU;
544}
545
546// This function is mostly cut and pasted from
547// GenericScheduler::pickNode()
549 if (DAG->top() == DAG->bottom()) {
550 assert(Top.Available.empty() && Top.Pending.empty() &&
551 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
552 return nullptr;
553 }
554 bool PickedPending;
555 SUnit *SU;
556 do {
557 PickedPending = false;
558 if (RegionPolicy.OnlyTopDown) {
560 if (!SU) {
561 CandPolicy NoPolicy;
562 TopCand.reset(NoPolicy);
563 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand,
564 PickedPending,
565 /*IsBottomUp=*/false);
566 assert(TopCand.Reason != NoCand && "failed to find a candidate");
567 SU = TopCand.SU;
568 }
569 IsTopNode = true;
570 } else if (RegionPolicy.OnlyBottomUp) {
572 if (!SU) {
573 CandPolicy NoPolicy;
574 BotCand.reset(NoPolicy);
575 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand,
576 PickedPending,
577 /*IsBottomUp=*/true);
578 assert(BotCand.Reason != NoCand && "failed to find a candidate");
579 SU = BotCand.SU;
580 }
581 IsTopNode = false;
582 } else {
583 SU = pickNodeBidirectional(IsTopNode, PickedPending);
584 }
585 } while (SU->isScheduled);
586
587 if (PickedPending) {
588 unsigned ReadyCycle = IsTopNode ? SU->TopReadyCycle : SU->BotReadyCycle;
589 SchedBoundary &Zone = IsTopNode ? Top : Bot;
590 unsigned CurrentCycle = Zone.getCurrCycle();
591 if (ReadyCycle > CurrentCycle)
592 Zone.bumpCycle(ReadyCycle);
593
594 // FIXME: checkHazard() doesn't give information about which cycle the
595 // hazard will resolve so just keep bumping the cycle by 1. This could be
596 // made more efficient if checkHazard() returned more details.
597 while (Zone.checkHazard(SU))
598 Zone.bumpCycle(Zone.getCurrCycle() + 1);
599
600 Zone.releasePending();
601 }
602
603 if (SU->isTopReady())
604 Top.removeReady(SU);
605 if (SU->isBottomReady())
606 Bot.removeReady(SU);
607
608 LLVM_DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") "
609 << *SU->getInstr());
610 return SU;
611}
612
613void GCNSchedStrategy::schedNode(SUnit *SU, bool IsTopNode) {
614 if (GCNTrackers) {
615 MachineInstr *MI = SU->getInstr();
616 IsTopNode ? (void)DownwardTracker.advance(MI, false)
617 : UpwardTracker.recede(*MI);
618 }
619
620 return GenericScheduler::schedNode(SU, IsTopNode);
621}
622
627
630 if (!CurrentStage)
631 CurrentStage = SchedStages.begin();
632 else
633 CurrentStage++;
634
635 return CurrentStage != SchedStages.end();
636}
637
640 return std::next(CurrentStage) != SchedStages.end();
641}
642
644 assert(CurrentStage && std::next(CurrentStage) != SchedStages.end());
645 return *std::next(CurrentStage);
646}
647
649 SchedCandidate &TryCand,
650 SchedBoundary *Zone) const {
651 // Initialize the candidate if needed.
652 if (!Cand.isValid()) {
653 TryCand.Reason = NodeOrder;
654 return true;
655 }
656
657 // Bias PhysReg Defs and copies to their uses and defined respectively.
658 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
659 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
660 return TryCand.Reason != NoCand;
661
662 // Avoid exceeding the target's limit.
663 if (DAG->isTrackingPressure() &&
664 tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
665 RegExcess, TRI, DAG->MF))
666 return TryCand.Reason != NoCand;
667
668 // Avoid increasing the max critical pressure in the scheduled region.
669 if (DAG->isTrackingPressure() &&
671 TryCand, Cand, RegCritical, TRI, DAG->MF))
672 return TryCand.Reason != NoCand;
673
674 bool SameBoundary = Zone != nullptr;
675 if (SameBoundary) {
678 TryCand, Cand, ResourceReduce))
679 return TryCand.Reason != NoCand;
681 Cand.ResDelta.DemandedResources, TryCand, Cand,
683 return TryCand.Reason != NoCand;
684 }
685
686 return false;
687}
688
698
703
705 SchedCandidate &TryCand,
706 SchedBoundary *Zone) const {
707 // Initialize the candidate if needed.
708 if (!Cand.isValid()) {
709 TryCand.Reason = NodeOrder;
710 return true;
711 }
712
713 // Avoid spilling by exceeding the register 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 // Bias PhysReg Defs and copies to their uses and defined respectively.
720 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
721 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
722 return TryCand.Reason != NoCand;
723
724 bool SameBoundary = Zone != nullptr;
725 if (SameBoundary) {
726 // Prioritize instructions that read unbuffered resources by stall cycles.
727 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
728 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
729 return TryCand.Reason != NoCand;
730
731 // Avoid critical resource consumption and balance the schedule.
734 TryCand, Cand, ResourceReduce))
735 return TryCand.Reason != NoCand;
737 Cand.ResDelta.DemandedResources, TryCand, Cand,
739 return TryCand.Reason != NoCand;
740
741 // Unconditionally try to reduce latency.
742 if (tryLatency(TryCand, Cand, *Zone))
743 return TryCand.Reason != NoCand;
744
745 // Weak edges are for clustering and other constraints.
746 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
747 getWeakLeft(Cand.SU, Cand.AtTop), TryCand, Cand, Weak))
748 return TryCand.Reason != NoCand;
749 }
750
751 // Keep clustered nodes together to encourage downstream peephole
752 // optimizations which may reduce resource requirements.
753 //
754 // This is a best effort to set things up for a post-RA pass. Optimizations
755 // like generating loads of multiple registers should ideally be done within
756 // the scheduler pass by combining the loads during DAG postprocessing.
757 unsigned CandZoneCluster = Cand.AtTop ? TopClusterID : BotClusterID;
758 unsigned TryCandZoneCluster = TryCand.AtTop ? TopClusterID : BotClusterID;
759 bool CandIsClusterSucc =
760 isTheSameCluster(CandZoneCluster, Cand.SU->ParentClusterIdx);
761 bool TryCandIsClusterSucc =
762 isTheSameCluster(TryCandZoneCluster, TryCand.SU->ParentClusterIdx);
763 if (tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
764 Cluster))
765 return TryCand.Reason != NoCand;
766
767 // Avoid increasing the max critical pressure in the scheduled region.
768 if (DAG->isTrackingPressure() &&
770 TryCand, Cand, RegCritical, TRI, DAG->MF))
771 return TryCand.Reason != NoCand;
772
773 // Avoid increasing the max pressure of the entire region.
774 if (DAG->isTrackingPressure() &&
775 tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax, TryCand,
776 Cand, RegMax, TRI, DAG->MF))
777 return TryCand.Reason != NoCand;
778
779 if (SameBoundary) {
780 // Fall through to original instruction order.
781 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum) ||
782 (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
783 TryCand.Reason = NodeOrder;
784 return true;
785 }
786 }
787 return false;
788}
789
795
796/// GCNMaxMemoryClauseSchedStrategy tries best to clause memory instructions as
797/// much as possible. This is achieved by:
798// 1. Prioritize clustered operations before stall latency heuristic.
799// 2. Prioritize long-latency-load before stall latency heuristic.
800///
801/// \param Cand provides the policy and current best candidate.
802/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
803/// \param Zone describes the scheduled zone that we are extending, or nullptr
804/// if Cand is from a different zone than TryCand.
805/// \return \c true if TryCand is better than Cand (Reason is NOT NoCand)
807 SchedCandidate &TryCand,
808 SchedBoundary *Zone) const {
809 // Initialize the candidate if needed.
810 if (!Cand.isValid()) {
811 TryCand.Reason = NodeOrder;
812 return true;
813 }
814
815 // Bias PhysReg Defs and copies to their uses and defined respectively.
816 if (tryGreater(biasPhysReg(TryCand.SU, TryCand.AtTop),
817 biasPhysReg(Cand.SU, Cand.AtTop), TryCand, Cand, PhysReg))
818 return TryCand.Reason != NoCand;
819
820 if (DAG->isTrackingPressure()) {
821 // Avoid exceeding the target's limit.
822 if (tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
823 RegExcess, TRI, DAG->MF))
824 return TryCand.Reason != NoCand;
825
826 // Avoid increasing the max critical pressure in the scheduled region.
828 TryCand, Cand, RegCritical, TRI, DAG->MF))
829 return TryCand.Reason != NoCand;
830 }
831
832 // MaxMemoryClause-specific: We prioritize clustered instructions as we would
833 // get more benefit from clausing these memory instructions.
834 unsigned CandZoneCluster = Cand.AtTop ? TopClusterID : BotClusterID;
835 unsigned TryCandZoneCluster = TryCand.AtTop ? TopClusterID : BotClusterID;
836 bool CandIsClusterSucc =
837 isTheSameCluster(CandZoneCluster, Cand.SU->ParentClusterIdx);
838 bool TryCandIsClusterSucc =
839 isTheSameCluster(TryCandZoneCluster, TryCand.SU->ParentClusterIdx);
840 if (tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
841 Cluster))
842 return TryCand.Reason != NoCand;
843
844 // We only compare a subset of features when comparing nodes between
845 // Top and Bottom boundary. Some properties are simply incomparable, in many
846 // other instances we should only override the other boundary if something
847 // is a clear good pick on one boundary. Skip heuristics that are more
848 // "tie-breaking" in nature.
849 bool SameBoundary = Zone != nullptr;
850 if (SameBoundary) {
851 // For loops that are acyclic path limited, aggressively schedule for
852 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
853 // heuristics to take precedence.
854 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
855 tryLatency(TryCand, Cand, *Zone))
856 return TryCand.Reason != NoCand;
857
858 // MaxMemoryClause-specific: Prioritize long latency memory load
859 // instructions in top-bottom order to hide more latency. The mayLoad check
860 // is used to exclude store-like instructions, which we do not want to
861 // scheduler them too early.
862 bool TryMayLoad =
863 TryCand.SU->isInstr() && TryCand.SU->getInstr()->mayLoad();
864 bool CandMayLoad = Cand.SU->isInstr() && Cand.SU->getInstr()->mayLoad();
865
866 if (TryMayLoad || CandMayLoad) {
867 bool TryLongLatency =
868 TryCand.SU->Latency > 10 * Cand.SU->Latency && TryMayLoad;
869 bool CandLongLatency =
870 10 * TryCand.SU->Latency < Cand.SU->Latency && CandMayLoad;
871
872 if (tryGreater(Zone->isTop() ? TryLongLatency : CandLongLatency,
873 Zone->isTop() ? CandLongLatency : TryLongLatency, TryCand,
874 Cand, Stall))
875 return TryCand.Reason != NoCand;
876 }
877 // Prioritize instructions that read unbuffered resources by stall cycles.
878 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
879 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
880 return TryCand.Reason != NoCand;
881 }
882
883 if (SameBoundary) {
884 // Weak edges are for clustering and other constraints.
885 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
886 getWeakLeft(Cand.SU, Cand.AtTop), TryCand, Cand, Weak))
887 return TryCand.Reason != NoCand;
888 }
889
890 // Avoid increasing the max pressure of the entire region.
891 if (DAG->isTrackingPressure() &&
892 tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax, TryCand,
893 Cand, RegMax, TRI, DAG->MF))
894 return TryCand.Reason != NoCand;
895
896 if (SameBoundary) {
897 // Avoid critical resource consumption and balance the schedule.
900 TryCand, Cand, ResourceReduce))
901 return TryCand.Reason != NoCand;
903 Cand.ResDelta.DemandedResources, TryCand, Cand,
905 return TryCand.Reason != NoCand;
906
907 // Avoid serializing long latency dependence chains.
908 // For acyclic path limited loops, latency was already checked above.
909 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
910 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
911 return TryCand.Reason != NoCand;
912
913 // Fall through to original instruction order.
914 if (Zone->isTop() == (TryCand.SU->NodeNum < Cand.SU->NodeNum)) {
915 assert(TryCand.SU->NodeNum != Cand.SU->NodeNum);
916 TryCand.Reason = NodeOrder;
917 return true;
918 }
919 }
920
921 return false;
922}
923
925 MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S)
926 : ScheduleDAGMILive(C, std::move(S)), ST(MF.getSubtarget<GCNSubtarget>()),
927 MFI(*MF.getInfo<SIMachineFunctionInfo>()),
928 StartingOccupancy(MFI.getOccupancy()), MinOccupancy(StartingOccupancy),
929 RegionLiveOuts(this, /*IsLiveOut=*/true) {
930
931 // We want regions with a single MI to be scheduled so that we can reason
932 // about them correctly during scheduling stages that move MIs between regions
933 // (e.g., rematerialization).
935 LLVM_DEBUG(dbgs() << "Starting occupancy is " << StartingOccupancy << ".\n");
936 if (RelaxedOcc) {
937 MinOccupancy = std::min(MFI.getMinAllowedOccupancy(), StartingOccupancy);
938 if (MinOccupancy != StartingOccupancy)
939 LLVM_DEBUG(dbgs() << "Allowing Occupancy drops to " << MinOccupancy
940 << ".\n");
941 }
942}
943
944std::unique_ptr<GCNSchedStage>
945GCNScheduleDAGMILive::createSchedStage(GCNSchedStageID SchedStageID) {
946 switch (SchedStageID) {
948 return std::make_unique<OccInitialScheduleStage>(SchedStageID, *this);
950 return std::make_unique<UnclusteredHighRPStage>(SchedStageID, *this);
952 return std::make_unique<ClusteredLowOccStage>(SchedStageID, *this);
954 return std::make_unique<PreRARematStage>(SchedStageID, *this);
956 return std::make_unique<ILPInitialScheduleStage>(SchedStageID, *this);
958 return std::make_unique<MemoryClauseInitialScheduleStage>(SchedStageID,
959 *this);
960 }
961
962 llvm_unreachable("Unknown SchedStageID.");
963}
964
966 // Collect all scheduling regions. The actual scheduling is performed in
967 // GCNScheduleDAGMILive::finalizeSchedule.
968 Regions.push_back(std::pair(RegionBegin, RegionEnd));
969}
970
972GCNScheduleDAGMILive::getRealRegPressure(unsigned RegionIdx) const {
974 RPTracker.advance(Regions[RegionIdx].first, Regions[RegionIdx].second,
975 &LiveIns[RegionIdx]);
976 return RPTracker.moveMaxPressure();
977}
978
980 MachineBasicBlock::iterator RegionEnd) {
981 auto REnd = RegionEnd == RegionBegin->getParent()->end()
982 ? std::prev(RegionEnd)
983 : RegionEnd;
984 return &*skipDebugInstructionsBackward(REnd, RegionBegin);
985}
986
987void GCNScheduleDAGMILive::computeBlockPressure(unsigned RegionIdx,
988 const MachineBasicBlock *MBB) {
989 GCNDownwardRPTracker RPTracker(*LIS);
990
991 // If the block has the only successor then live-ins of that successor are
992 // live-outs of the current block. We can reuse calculated live set if the
993 // successor will be sent to scheduling past current block.
994
995 // However, due to the bug in LiveInterval analysis it may happen that two
996 // predecessors of the same successor block have different lane bitmasks for
997 // a live-out register. Workaround that by sticking to one-to-one relationship
998 // i.e. one predecessor with one successor block.
999 const MachineBasicBlock *OnlySucc = nullptr;
1000 if (MBB->succ_size() == 1) {
1001 auto *Candidate = *MBB->succ_begin();
1002 if (!Candidate->empty() && Candidate->pred_size() == 1) {
1003 SlotIndexes *Ind = LIS->getSlotIndexes();
1004 if (Ind->getMBBStartIdx(MBB) < Ind->getMBBStartIdx(Candidate))
1005 OnlySucc = Candidate;
1006 }
1007 }
1008
1009 // Scheduler sends regions from the end of the block upwards.
1010 size_t CurRegion = RegionIdx;
1011 for (size_t E = Regions.size(); CurRegion != E; ++CurRegion)
1012 if (Regions[CurRegion].first->getParent() != MBB)
1013 break;
1014 --CurRegion;
1015
1016 auto I = MBB->begin();
1017 auto LiveInIt = MBBLiveIns.find(MBB);
1018 auto &Rgn = Regions[CurRegion];
1019 auto *NonDbgMI = &*skipDebugInstructionsForward(Rgn.first, Rgn.second);
1020 if (LiveInIt != MBBLiveIns.end()) {
1021 auto LiveIn = std::move(LiveInIt->second);
1022 RPTracker.reset(*MBB->begin(), &LiveIn);
1023 MBBLiveIns.erase(LiveInIt);
1024 } else {
1025 I = Rgn.first;
1026 auto LRS = BBLiveInMap.lookup(NonDbgMI);
1027#ifdef EXPENSIVE_CHECKS
1028 assert(isEqual(getLiveRegsBefore(*NonDbgMI, *LIS), LRS));
1029#endif
1030 RPTracker.reset(*I, &LRS);
1031 }
1032
1033 for (;;) {
1034 I = RPTracker.getNext();
1035
1036 if (Regions[CurRegion].first == I || NonDbgMI == I) {
1037 LiveIns[CurRegion] = RPTracker.getLiveRegs();
1038 RPTracker.clearMaxPressure();
1039 }
1040
1041 if (Regions[CurRegion].second == I) {
1042 Pressure[CurRegion] = RPTracker.moveMaxPressure();
1043 if (CurRegion-- == RegionIdx)
1044 break;
1045 auto &Rgn = Regions[CurRegion];
1046 NonDbgMI = &*skipDebugInstructionsForward(Rgn.first, Rgn.second);
1047 }
1048 RPTracker.advanceToNext();
1049 RPTracker.advanceBeforeNext();
1050 }
1051
1052 if (OnlySucc) {
1053 if (I != MBB->end()) {
1054 RPTracker.advanceToNext();
1055 RPTracker.advance(MBB->end());
1056 }
1057 RPTracker.advanceBeforeNext();
1058 MBBLiveIns[OnlySucc] = RPTracker.moveLiveRegs();
1059 }
1060}
1061
1063GCNScheduleDAGMILive::getRegionLiveInMap() const {
1064 assert(!Regions.empty());
1065 std::vector<MachineInstr *> RegionFirstMIs;
1066 RegionFirstMIs.reserve(Regions.size());
1067 for (auto &[RegionBegin, RegionEnd] : reverse(Regions))
1068 RegionFirstMIs.push_back(
1070
1071 return getLiveRegMap(RegionFirstMIs, /*After=*/false, *LIS);
1072}
1073
1075GCNScheduleDAGMILive::getRegionLiveOutMap() const {
1076 assert(!Regions.empty());
1077 std::vector<MachineInstr *> RegionLastMIs;
1078 RegionLastMIs.reserve(Regions.size());
1079 for (auto &[RegionBegin, RegionEnd] : reverse(Regions))
1080 RegionLastMIs.push_back(getLastMIForRegion(RegionBegin, RegionEnd));
1081
1082 return getLiveRegMap(RegionLastMIs, /*After=*/true, *LIS);
1083}
1084
1086 IdxToInstruction.clear();
1087
1088 RegionLiveRegMap =
1089 IsLiveOut ? DAG->getRegionLiveOutMap() : DAG->getRegionLiveInMap();
1090 for (unsigned I = 0; I < DAG->Regions.size(); I++) {
1091 MachineInstr *RegionKey =
1092 IsLiveOut
1093 ? getLastMIForRegion(DAG->Regions[I].first, DAG->Regions[I].second)
1094 : &*DAG->Regions[I].first;
1095 IdxToInstruction[I] = RegionKey;
1096 }
1097}
1098
1100 // Start actual scheduling here. This function is called by the base
1101 // MachineScheduler after all regions have been recorded by
1102 // GCNScheduleDAGMILive::schedule().
1103 LiveIns.resize(Regions.size());
1104 Pressure.resize(Regions.size());
1105 RegionsWithHighRP.resize(Regions.size());
1106 RegionsWithExcessRP.resize(Regions.size());
1107 RegionsWithIGLPInstrs.resize(Regions.size());
1108 RegionsWithHighRP.reset();
1109 RegionsWithExcessRP.reset();
1110 RegionsWithIGLPInstrs.reset();
1111
1112 runSchedStages();
1113}
1114
1115void GCNScheduleDAGMILive::runSchedStages() {
1116 LLVM_DEBUG(dbgs() << "All regions recorded, starting actual scheduling.\n");
1117
1118 if (!Regions.empty()) {
1119 BBLiveInMap = getRegionLiveInMap();
1120 if (GCNTrackers)
1121 RegionLiveOuts.buildLiveRegMap();
1122 }
1123
1124#ifdef DUMP_MAX_REG_PRESSURE
1128 LIS->dump();
1129 }
1130#endif
1131
1132 GCNSchedStrategy &S = static_cast<GCNSchedStrategy &>(*SchedImpl);
1133 while (S.advanceStage()) {
1134 auto Stage = createSchedStage(S.getCurrentStage());
1135 if (!Stage->initGCNSchedStage())
1136 continue;
1137
1138 for (auto Region : Regions) {
1139 RegionBegin = Region.first;
1140 RegionEnd = Region.second;
1141 // Setup for scheduling the region and check whether it should be skipped.
1142 if (!Stage->initGCNRegion()) {
1143 Stage->advanceRegion();
1144 exitRegion();
1145 continue;
1146 }
1147
1148 if (GCNTrackers) {
1149 GCNDownwardRPTracker *DownwardTracker = S.getDownwardTracker();
1150 GCNUpwardRPTracker *UpwardTracker = S.getUpwardTracker();
1151 GCNRPTracker::LiveRegSet *RegionLiveIns =
1152 &LiveIns[Stage->getRegionIdx()];
1153
1154 reinterpret_cast<GCNRPTracker *>(DownwardTracker)
1155 ->reset(MRI, *RegionLiveIns);
1156 reinterpret_cast<GCNRPTracker *>(UpwardTracker)
1157 ->reset(MRI, RegionLiveOuts.getLiveRegsForRegionIdx(
1158 Stage->getRegionIdx()));
1159 }
1160
1162 Stage->finalizeGCNRegion();
1163 }
1164
1165 Stage->finalizeGCNSchedStage();
1166 }
1167
1168#ifdef DUMP_MAX_REG_PRESSURE
1172 LIS->dump();
1173 }
1174#endif
1175}
1176
1177#ifndef NDEBUG
1179 switch (StageID) {
1181 OS << "Max Occupancy Initial Schedule";
1182 break;
1184 OS << "Unclustered High Register Pressure Reschedule";
1185 break;
1187 OS << "Clustered Low Occupancy Reschedule";
1188 break;
1190 OS << "Pre-RA Rematerialize";
1191 break;
1193 OS << "Max ILP Initial Schedule";
1194 break;
1196 OS << "Max memory clause Initial Schedule";
1197 break;
1198 }
1199
1200 return OS;
1201}
1202#endif
1203
1207
1209 if (!DAG.LIS)
1210 return false;
1211
1212 LLVM_DEBUG(dbgs() << "Starting scheduling stage: " << StageID << "\n");
1213 return true;
1214}
1215
1218 return false;
1219
1221 return false;
1222
1223 if (DAG.RegionsWithHighRP.none() && DAG.RegionsWithExcessRP.none())
1224 return false;
1225
1226 SavedMutations.swap(DAG.Mutations);
1227 DAG.addMutation(
1229
1230 InitialOccupancy = DAG.MinOccupancy;
1231 // Aggressivly try to reduce register pressure in the unclustered high RP
1232 // stage. Temporarily increase occupancy target in the region.
1233 S.SGPRLimitBias = S.HighRPSGPRBias;
1234 S.VGPRLimitBias = S.HighRPVGPRBias;
1235 if (MFI.getMaxWavesPerEU() > DAG.MinOccupancy)
1236 MFI.increaseOccupancy(MF, ++DAG.MinOccupancy);
1237
1238 LLVM_DEBUG(
1239 dbgs()
1240 << "Retrying function scheduling without clustering. "
1241 "Aggressivly try to reduce register pressure to achieve occupancy "
1242 << DAG.MinOccupancy << ".\n");
1243
1244 return true;
1245}
1246
1249 return false;
1250
1252 return false;
1253
1254 // Don't bother trying to improve ILP in lower RP regions if occupancy has not
1255 // been dropped. All regions will have already been scheduled with the ideal
1256 // occupancy targets.
1257 if (DAG.StartingOccupancy <= DAG.MinOccupancy)
1258 return false;
1259
1260 LLVM_DEBUG(
1261 dbgs() << "Retrying function scheduling with lowest recorded occupancy "
1262 << DAG.MinOccupancy << ".\n");
1263 return true;
1264}
1265
1266/// Allows to easily filter for this stage's debug output.
1267#define REMAT_PREFIX "[PreRARemat] "
1268#define REMAT_DEBUG(X) LLVM_DEBUG(dbgs() << REMAT_PREFIX; X;)
1269
1271 // FIXME: This pass will invalidate cached BBLiveInMap and MBBLiveIns for
1272 // regions inbetween the defs and region we sinked the def to. Will need to be
1273 // fixed if there is another pass after this pass.
1274 assert(!S.hasNextStage());
1275
1276 if (!GCNSchedStage::initGCNSchedStage() || DAG.Regions.size() == 1)
1277 return false;
1278
1279 // Before performing any IR modification record the parent region of each MI
1280 // and the parent MBB of each region.
1281 const unsigned NumRegions = DAG.Regions.size();
1282 RegionBB.reserve(NumRegions);
1283 for (unsigned I = 0; I < NumRegions; ++I) {
1284 RegionBoundaries Region = DAG.Regions[I];
1285 for (auto MI = Region.first; MI != Region.second; ++MI)
1286 MIRegion.insert({&*MI, I});
1287 RegionBB.push_back(Region.first->getParent());
1288 }
1289
1290 if (!canIncreaseOccupancyOrReduceSpill())
1291 return false;
1292
1293 // Rematerialize identified instructions and update scheduler's state.
1294 rematerialize();
1295 if (GCNTrackers)
1296 DAG.RegionLiveOuts.buildLiveRegMap();
1297 REMAT_DEBUG({
1298 dbgs() << "Retrying function scheduling with new min. occupancy of "
1299 << AchievedOcc << " from rematerializing (original was "
1300 << DAG.MinOccupancy;
1301 if (TargetOcc)
1302 dbgs() << ", target was " << *TargetOcc;
1303 dbgs() << ")\n";
1304 });
1305
1306 if (AchievedOcc > DAG.MinOccupancy) {
1307 DAG.MinOccupancy = AchievedOcc;
1309 MFI.increaseOccupancy(MF, DAG.MinOccupancy);
1310 }
1311 return true;
1312}
1313
1315 DAG.finishBlock();
1316 LLVM_DEBUG(dbgs() << "Ending scheduling stage: " << StageID << "\n");
1317}
1318
1320 SavedMutations.swap(DAG.Mutations);
1321 S.SGPRLimitBias = S.VGPRLimitBias = 0;
1322 if (DAG.MinOccupancy > InitialOccupancy) {
1324 << " stage successfully increased occupancy to "
1325 << DAG.MinOccupancy << '\n');
1326 }
1327
1329}
1330
1332 // Check whether this new region is also a new block.
1333 if (DAG.RegionBegin->getParent() != CurrentMBB)
1334 setupNewBlock();
1335
1336 unsigned NumRegionInstrs = std::distance(DAG.begin(), DAG.end());
1337 DAG.enterRegion(CurrentMBB, DAG.begin(), DAG.end(), NumRegionInstrs);
1338
1339 // Skip empty scheduling regions (0 or 1 schedulable instructions).
1340 if (DAG.begin() == DAG.end() || DAG.begin() == std::prev(DAG.end()))
1341 return false;
1342
1343 LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
1344 LLVM_DEBUG(dbgs() << MF.getName() << ":" << printMBBReference(*CurrentMBB)
1345 << " " << CurrentMBB->getName()
1346 << "\n From: " << *DAG.begin() << " To: ";
1347 if (DAG.RegionEnd != CurrentMBB->end()) dbgs() << *DAG.RegionEnd;
1348 else dbgs() << "End";
1349 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
1350
1351 // Save original instruction order before scheduling for possible revert.
1352 Unsched.clear();
1353 Unsched.reserve(DAG.NumRegionInstrs);
1356 const SIInstrInfo *SII = static_cast<const SIInstrInfo *>(DAG.TII);
1357 for (auto &I : DAG) {
1358 Unsched.push_back(&I);
1359 if (SII->isIGLPMutationOnly(I.getOpcode()))
1360 DAG.RegionsWithIGLPInstrs[RegionIdx] = true;
1361 }
1362 } else {
1363 for (auto &I : DAG)
1364 Unsched.push_back(&I);
1365 }
1366
1367 PressureBefore = DAG.Pressure[RegionIdx];
1368
1369 LLVM_DEBUG(
1370 dbgs() << "Pressure before scheduling:\nRegion live-ins:"
1371 << print(DAG.LiveIns[RegionIdx], DAG.MRI)
1372 << "Region live-in pressure: "
1373 << print(llvm::getRegPressure(DAG.MRI, DAG.LiveIns[RegionIdx]))
1374 << "Region register pressure: " << print(PressureBefore));
1375
1376 S.HasHighPressure = false;
1377 S.KnownExcessRP = isRegionWithExcessRP();
1378
1379 if (DAG.RegionsWithIGLPInstrs[RegionIdx] &&
1381 SavedMutations.clear();
1382 SavedMutations.swap(DAG.Mutations);
1383 bool IsInitialStage = StageID == GCNSchedStageID::OccInitialSchedule ||
1385 DAG.addMutation(createIGroupLPDAGMutation(
1386 IsInitialStage ? AMDGPU::SchedulingPhase::Initial
1388 }
1389
1390 return true;
1391}
1392
1394 // Only reschedule regions that have excess register pressure (i.e. spilling)
1395 // or had minimum occupancy at the beginning of the stage (as long as
1396 // rescheduling of previous regions did not make occupancy drop back down to
1397 // the initial minimum).
1398 unsigned DynamicVGPRBlockSize = DAG.MFI.getDynamicVGPRBlockSize();
1399 if (!DAG.RegionsWithExcessRP[RegionIdx] &&
1400 (DAG.MinOccupancy <= InitialOccupancy ||
1401 DAG.Pressure[RegionIdx].getOccupancy(ST, DynamicVGPRBlockSize) !=
1402 InitialOccupancy))
1403 return false;
1404
1406}
1407
1409 // We may need to reschedule this region if it wasn't rescheduled in the last
1410 // stage, or if we found it was testing critical register pressure limits in
1411 // the unclustered reschedule stage. The later is because we may not have been
1412 // able to raise the min occupancy in the previous stage so the region may be
1413 // overly constrained even if it was already rescheduled.
1414 if (!DAG.RegionsWithHighRP[RegionIdx])
1415 return false;
1416
1418}
1419
1421 return RescheduleRegions[RegionIdx] && GCNSchedStage::initGCNRegion();
1422}
1423
1425 if (CurrentMBB)
1426 DAG.finishBlock();
1427
1428 CurrentMBB = DAG.RegionBegin->getParent();
1429 DAG.startBlock(CurrentMBB);
1430 // Get real RP for the region if it hasn't be calculated before. After the
1431 // initial schedule stage real RP will be collected after scheduling.
1435 DAG.computeBlockPressure(RegionIdx, CurrentMBB);
1436}
1437
1439 DAG.Regions[RegionIdx] = std::pair(DAG.RegionBegin, DAG.RegionEnd);
1440 if (S.HasHighPressure)
1441 DAG.RegionsWithHighRP[RegionIdx] = true;
1442
1443 // Revert scheduling if we have dropped occupancy or there is some other
1444 // reason that the original schedule is better.
1446
1447 if (DAG.RegionsWithIGLPInstrs[RegionIdx] &&
1449 SavedMutations.swap(DAG.Mutations);
1450
1451 DAG.exitRegion();
1452 advanceRegion();
1453}
1454
1456 // Check the results of scheduling.
1457 PressureAfter = DAG.getRealRegPressure(RegionIdx);
1458
1459 LLVM_DEBUG(dbgs() << "Pressure after scheduling: " << print(PressureAfter));
1460 LLVM_DEBUG(dbgs() << "Region: " << RegionIdx << ".\n");
1461
1462 unsigned DynamicVGPRBlockSize = DAG.MFI.getDynamicVGPRBlockSize();
1463
1464 if (PressureAfter.getSGPRNum() <= S.SGPRCriticalLimit &&
1465 PressureAfter.getVGPRNum(ST.hasGFX90AInsts()) <= S.VGPRCriticalLimit) {
1466 DAG.Pressure[RegionIdx] = PressureAfter;
1467
1468 // Early out if we have achieved the occupancy target.
1469 LLVM_DEBUG(dbgs() << "Pressure in desired limits, done.\n");
1470 return;
1471 }
1472
1473 unsigned TargetOccupancy = std::min(
1474 S.getTargetOccupancy(), ST.getOccupancyWithWorkGroupSizes(MF).second);
1475 unsigned WavesAfter = std::min(
1476 TargetOccupancy, PressureAfter.getOccupancy(ST, DynamicVGPRBlockSize));
1477 unsigned WavesBefore = std::min(
1478 TargetOccupancy, PressureBefore.getOccupancy(ST, DynamicVGPRBlockSize));
1479 LLVM_DEBUG(dbgs() << "Occupancy before scheduling: " << WavesBefore
1480 << ", after " << WavesAfter << ".\n");
1481
1482 // We may not be able to keep the current target occupancy because of the just
1483 // scheduled region. We might still be able to revert scheduling if the
1484 // occupancy before was higher, or if the current schedule has register
1485 // pressure higher than the excess limits which could lead to more spilling.
1486 unsigned NewOccupancy = std::max(WavesAfter, WavesBefore);
1487
1488 // Allow memory bound functions to drop to 4 waves if not limited by an
1489 // attribute.
1490 if (WavesAfter < WavesBefore && WavesAfter < DAG.MinOccupancy &&
1491 WavesAfter >= MFI.getMinAllowedOccupancy()) {
1492 LLVM_DEBUG(dbgs() << "Function is memory bound, allow occupancy drop up to "
1493 << MFI.getMinAllowedOccupancy() << " waves\n");
1494 NewOccupancy = WavesAfter;
1495 }
1496
1497 if (NewOccupancy < DAG.MinOccupancy) {
1498 DAG.MinOccupancy = NewOccupancy;
1499 MFI.limitOccupancy(DAG.MinOccupancy);
1500 LLVM_DEBUG(dbgs() << "Occupancy lowered for the function to "
1501 << DAG.MinOccupancy << ".\n");
1502 }
1503 // The maximum number of arch VGPR on non-unified register file, or the
1504 // maximum VGPR + AGPR in the unified register file case.
1505 unsigned MaxVGPRs = ST.getMaxNumVGPRs(MF);
1506 // The maximum number of arch VGPR for both unified and non-unified register
1507 // file.
1508 unsigned MaxArchVGPRs = std::min(MaxVGPRs, ST.getAddressableNumArchVGPRs());
1509 unsigned MaxSGPRs = ST.getMaxNumSGPRs(MF);
1510
1511 if (PressureAfter.getVGPRNum(ST.hasGFX90AInsts()) > MaxVGPRs ||
1512 PressureAfter.getArchVGPRNum() > MaxArchVGPRs ||
1513 PressureAfter.getAGPRNum() > MaxArchVGPRs ||
1514 PressureAfter.getSGPRNum() > MaxSGPRs) {
1515 DAG.RegionsWithHighRP[RegionIdx] = true;
1516 DAG.RegionsWithExcessRP[RegionIdx] = true;
1517 }
1518
1519 // Revert if this region's schedule would cause a drop in occupancy or
1520 // spilling.
1521 if (shouldRevertScheduling(WavesAfter))
1523 else
1524 DAG.Pressure[RegionIdx] = PressureAfter;
1525}
1526
1527unsigned
1528GCNSchedStage::computeSUnitReadyCycle(const SUnit &SU, unsigned CurrCycle,
1529 DenseMap<unsigned, unsigned> &ReadyCycles,
1530 const TargetSchedModel &SM) {
1531 unsigned ReadyCycle = CurrCycle;
1532 for (auto &D : SU.Preds) {
1533 if (D.isAssignedRegDep()) {
1534 MachineInstr *DefMI = D.getSUnit()->getInstr();
1535 unsigned Latency = SM.computeInstrLatency(DefMI);
1536 unsigned DefReady = ReadyCycles[DAG.getSUnit(DefMI)->NodeNum];
1537 ReadyCycle = std::max(ReadyCycle, DefReady + Latency);
1538 }
1539 }
1540 ReadyCycles[SU.NodeNum] = ReadyCycle;
1541 return ReadyCycle;
1542}
1543
1544#ifndef NDEBUG
1546 bool operator()(std::pair<MachineInstr *, unsigned> A,
1547 std::pair<MachineInstr *, unsigned> B) const {
1548 return A.second < B.second;
1549 }
1550};
1551
1552static void printScheduleModel(std::set<std::pair<MachineInstr *, unsigned>,
1553 EarlierIssuingCycle> &ReadyCycles) {
1554 if (ReadyCycles.empty())
1555 return;
1556 unsigned BBNum = ReadyCycles.begin()->first->getParent()->getNumber();
1557 dbgs() << "\n################## Schedule time ReadyCycles for MBB : " << BBNum
1558 << " ##################\n# Cycle #\t\t\tInstruction "
1559 " "
1560 " \n";
1561 unsigned IPrev = 1;
1562 for (auto &I : ReadyCycles) {
1563 if (I.second > IPrev + 1)
1564 dbgs() << "****************************** BUBBLE OF " << I.second - IPrev
1565 << " CYCLES DETECTED ******************************\n\n";
1566 dbgs() << "[ " << I.second << " ] : " << *I.first << "\n";
1567 IPrev = I.second;
1568 }
1569}
1570#endif
1571
1573GCNSchedStage::getScheduleMetrics(const std::vector<SUnit> &InputSchedule) {
1574#ifndef NDEBUG
1575 std::set<std::pair<MachineInstr *, unsigned>, EarlierIssuingCycle>
1576 ReadyCyclesSorted;
1577#endif
1578 const TargetSchedModel &SM = ST.getInstrInfo()->getSchedModel();
1579 unsigned SumBubbles = 0;
1580 DenseMap<unsigned, unsigned> ReadyCycles;
1581 unsigned CurrCycle = 0;
1582 for (auto &SU : InputSchedule) {
1583 unsigned ReadyCycle =
1584 computeSUnitReadyCycle(SU, CurrCycle, ReadyCycles, SM);
1585 SumBubbles += ReadyCycle - CurrCycle;
1586#ifndef NDEBUG
1587 ReadyCyclesSorted.insert(std::make_pair(SU.getInstr(), ReadyCycle));
1588#endif
1589 CurrCycle = ++ReadyCycle;
1590 }
1591#ifndef NDEBUG
1592 LLVM_DEBUG(
1593 printScheduleModel(ReadyCyclesSorted);
1594 dbgs() << "\n\t"
1595 << "Metric: "
1596 << (SumBubbles
1597 ? (SumBubbles * ScheduleMetrics::ScaleFactor) / CurrCycle
1598 : 1)
1599 << "\n\n");
1600#endif
1601
1602 return ScheduleMetrics(CurrCycle, SumBubbles);
1603}
1604
1607#ifndef NDEBUG
1608 std::set<std::pair<MachineInstr *, unsigned>, EarlierIssuingCycle>
1609 ReadyCyclesSorted;
1610#endif
1611 const TargetSchedModel &SM = ST.getInstrInfo()->getSchedModel();
1612 unsigned SumBubbles = 0;
1613 DenseMap<unsigned, unsigned> ReadyCycles;
1614 unsigned CurrCycle = 0;
1615 for (auto &MI : DAG) {
1616 SUnit *SU = DAG.getSUnit(&MI);
1617 if (!SU)
1618 continue;
1619 unsigned ReadyCycle =
1620 computeSUnitReadyCycle(*SU, CurrCycle, ReadyCycles, SM);
1621 SumBubbles += ReadyCycle - CurrCycle;
1622#ifndef NDEBUG
1623 ReadyCyclesSorted.insert(std::make_pair(SU->getInstr(), ReadyCycle));
1624#endif
1625 CurrCycle = ++ReadyCycle;
1626 }
1627#ifndef NDEBUG
1628 LLVM_DEBUG(
1629 printScheduleModel(ReadyCyclesSorted);
1630 dbgs() << "\n\t"
1631 << "Metric: "
1632 << (SumBubbles
1633 ? (SumBubbles * ScheduleMetrics::ScaleFactor) / CurrCycle
1634 : 1)
1635 << "\n\n");
1636#endif
1637
1638 return ScheduleMetrics(CurrCycle, SumBubbles);
1639}
1640
1641bool GCNSchedStage::shouldRevertScheduling(unsigned WavesAfter) {
1642 if (WavesAfter < DAG.MinOccupancy)
1643 return true;
1644
1645 // For dynamic VGPR mode, we don't want to waste any VGPR blocks.
1646 if (DAG.MFI.isDynamicVGPREnabled()) {
1647 unsigned BlocksBefore = AMDGPU::IsaInfo::getAllocatedNumVGPRBlocks(
1648 &ST, DAG.MFI.getDynamicVGPRBlockSize(),
1649 PressureBefore.getVGPRNum(false));
1650 unsigned BlocksAfter = AMDGPU::IsaInfo::getAllocatedNumVGPRBlocks(
1651 &ST, DAG.MFI.getDynamicVGPRBlockSize(),
1652 PressureAfter.getVGPRNum(false));
1653 if (BlocksAfter > BlocksBefore)
1654 return true;
1655 }
1656
1657 return false;
1658}
1659
1662 return false;
1663
1665 return true;
1666
1667 if (mayCauseSpilling(WavesAfter))
1668 return true;
1669
1670 return false;
1671}
1672
1674 // If RP is not reduced in the unclustered reschedule stage, revert to the
1675 // old schedule.
1676 if ((WavesAfter <=
1677 PressureBefore.getOccupancy(ST, DAG.MFI.getDynamicVGPRBlockSize()) &&
1678 mayCauseSpilling(WavesAfter)) ||
1680 LLVM_DEBUG(dbgs() << "Unclustered reschedule did not help.\n");
1681 return true;
1682 }
1683
1684 // Do not attempt to relax schedule even more if we are already spilling.
1686 return false;
1687
1688 LLVM_DEBUG(
1689 dbgs()
1690 << "\n\t *** In shouldRevertScheduling ***\n"
1691 << " *********** BEFORE UnclusteredHighRPStage ***********\n");
1692 ScheduleMetrics MBefore = getScheduleMetrics(DAG.SUnits);
1693 LLVM_DEBUG(
1694 dbgs()
1695 << "\n *********** AFTER UnclusteredHighRPStage ***********\n");
1697 unsigned OldMetric = MBefore.getMetric();
1698 unsigned NewMetric = MAfter.getMetric();
1699 unsigned WavesBefore = std::min(
1700 S.getTargetOccupancy(),
1701 PressureBefore.getOccupancy(ST, DAG.MFI.getDynamicVGPRBlockSize()));
1702 unsigned Profit =
1703 ((WavesAfter * ScheduleMetrics::ScaleFactor) / WavesBefore *
1705 NewMetric) /
1707 LLVM_DEBUG(dbgs() << "\tMetric before " << MBefore << "\tMetric after "
1708 << MAfter << "Profit: " << Profit << "\n");
1709 return Profit < ScheduleMetrics::ScaleFactor;
1710}
1711
1714 return false;
1715
1717 return true;
1718
1719 if (mayCauseSpilling(WavesAfter))
1720 return true;
1721
1722 return false;
1723}
1724
1726 return GCNSchedStage::shouldRevertScheduling(WavesAfter) ||
1727 mayCauseSpilling(WavesAfter) || (TargetOcc && WavesAfter < TargetOcc);
1728}
1729
1731 if (mayCauseSpilling(WavesAfter))
1732 return true;
1733
1734 return false;
1735}
1736
1738 unsigned WavesAfter) {
1739 return mayCauseSpilling(WavesAfter);
1740}
1741
1742bool GCNSchedStage::mayCauseSpilling(unsigned WavesAfter) {
1743 if (WavesAfter <= MFI.getMinWavesPerEU() && isRegionWithExcessRP() &&
1745 LLVM_DEBUG(dbgs() << "New pressure will result in more spilling.\n");
1746 return true;
1747 }
1748
1749 return false;
1750}
1751
1753 LLVM_DEBUG(dbgs() << "Attempting to revert scheduling.\n");
1754 DAG.RegionEnd = DAG.RegionBegin;
1755 int SkippedDebugInstr = 0;
1756 for (MachineInstr *MI : Unsched) {
1757 if (MI->isDebugInstr()) {
1758 ++SkippedDebugInstr;
1759 continue;
1760 }
1761
1762 if (MI->getIterator() != DAG.RegionEnd) {
1763 DAG.BB->splice(DAG.RegionEnd, DAG.BB, MI);
1764 if (!MI->isDebugInstr())
1765 DAG.LIS->handleMove(*MI, true);
1766 }
1767
1768 // Reset read-undef flags and update them later.
1769 for (auto &Op : MI->all_defs())
1770 Op.setIsUndef(false);
1771 RegisterOperands RegOpers;
1772 RegOpers.collect(*MI, *DAG.TRI, DAG.MRI, DAG.ShouldTrackLaneMasks, false);
1773 if (!MI->isDebugInstr()) {
1774 if (DAG.ShouldTrackLaneMasks) {
1775 // Adjust liveness and add missing dead+read-undef flags.
1776 SlotIndex SlotIdx = DAG.LIS->getInstructionIndex(*MI).getRegSlot();
1777 RegOpers.adjustLaneLiveness(*DAG.LIS, DAG.MRI, SlotIdx, MI);
1778 } else {
1779 // Adjust for missing dead-def flags.
1780 RegOpers.detectDeadDefs(*MI, *DAG.LIS);
1781 }
1782 }
1783 DAG.RegionEnd = MI->getIterator();
1784 ++DAG.RegionEnd;
1785 LLVM_DEBUG(dbgs() << "Scheduling " << *MI);
1786 }
1787
1788 // After reverting schedule, debug instrs will now be at the end of the block
1789 // and RegionEnd will point to the first debug instr. Increment RegionEnd
1790 // pass debug instrs to the actual end of the scheduling region.
1791 while (SkippedDebugInstr-- > 0)
1792 ++DAG.RegionEnd;
1793
1794 // If Unsched.front() instruction is a debug instruction, this will actually
1795 // shrink the region since we moved all debug instructions to the end of the
1796 // block. Find the first instruction that is not a debug instruction.
1797 DAG.RegionBegin = Unsched.front()->getIterator();
1798 if (DAG.RegionBegin->isDebugInstr()) {
1799 for (MachineInstr *MI : Unsched) {
1800 if (MI->isDebugInstr())
1801 continue;
1802 DAG.RegionBegin = MI->getIterator();
1803 break;
1804 }
1805 }
1806
1807 // Then move the debug instructions back into their correct place and set
1808 // RegionBegin and RegionEnd if needed.
1809 DAG.placeDebugValues();
1810
1811 DAG.Regions[RegionIdx] = std::pair(DAG.RegionBegin, DAG.RegionEnd);
1812}
1813
1814bool PreRARematStage::canIncreaseOccupancyOrReduceSpill() {
1815 const Function &F = MF.getFunction();
1816
1817 // Maps optimizable regions (i.e., regions at minimum and register-limited
1818 // occupancy, or regions with spilling) to the target RP we would like to
1819 // reach.
1821 unsigned MaxSGPRs = ST.getMaxNumSGPRs(F);
1822 unsigned MaxVGPRs = ST.getMaxNumVGPRs(F);
1823 auto ResetTargetRegions = [&]() {
1824 OptRegions.clear();
1825 for (unsigned I = 0, E = DAG.Regions.size(); I != E; ++I) {
1826 const GCNRegPressure &RP = DAG.Pressure[I];
1827 GCNRPTarget Target(MaxSGPRs, MaxVGPRs, MF, RP);
1828 if (!Target.satisfied())
1829 OptRegions.insert({I, Target});
1830 }
1831 };
1832
1833 ResetTargetRegions();
1834 if (!OptRegions.empty() || DAG.MinOccupancy >= MFI.getMaxWavesPerEU()) {
1835 // In addition to register usage being above addressable limits, occupancy
1836 // below the minimum is considered like "spilling" as well.
1837 TargetOcc = std::nullopt;
1838 } else {
1839 // There is no spilling and room to improve occupancy; set up "increased
1840 // occupancy targets" for all regions.
1841 TargetOcc = DAG.MinOccupancy + 1;
1842 unsigned VGPRBlockSize =
1843 MF.getInfo<SIMachineFunctionInfo>()->getDynamicVGPRBlockSize();
1844 MaxSGPRs = ST.getMaxNumSGPRs(*TargetOcc, false);
1845 MaxVGPRs = ST.getMaxNumVGPRs(*TargetOcc, VGPRBlockSize);
1846 ResetTargetRegions();
1847 }
1848 REMAT_DEBUG({
1849 dbgs() << "Analyzing ";
1850 MF.getFunction().printAsOperand(dbgs(), false);
1851 dbgs() << ": ";
1852 if (OptRegions.empty()) {
1853 dbgs() << "no objective to achieve, occupancy is maximal at "
1854 << MFI.getMaxWavesPerEU();
1855 } else if (!TargetOcc) {
1856 dbgs() << "reduce spilling (minimum target occupancy is "
1857 << MFI.getMinWavesPerEU() << ')';
1858 } else {
1859 dbgs() << "increase occupancy from " << DAG.MinOccupancy << " to "
1860 << TargetOcc;
1861 }
1862 dbgs() << '\n';
1863 for (unsigned I = 0, E = DAG.Regions.size(); I != E; ++I) {
1864 if (auto OptIt = OptRegions.find(I); OptIt != OptRegions.end()) {
1865 dbgs() << REMAT_PREFIX << " [" << I << "] " << OptIt->getSecond()
1866 << '\n';
1867 }
1868 }
1869 });
1870 if (OptRegions.empty())
1871 return false;
1872
1873 // Accounts for a reduction in RP in an optimizable region. Returns whether we
1874 // estimate that we have identified enough rematerialization opportunities to
1875 // achieve our goal, and sets Progress to true when this particular reduction
1876 // in pressure was helpful toward that goal.
1877 auto ReduceRPInRegion = [&](auto OptIt, Register Reg, LaneBitmask Mask,
1878 bool &Progress) -> bool {
1879 GCNRPTarget &Target = OptIt->getSecond();
1880 if (!Target.isSaveBeneficial(Reg))
1881 return false;
1882 Progress = true;
1883 Target.saveReg(Reg, Mask, DAG.MRI);
1884 if (Target.satisfied())
1885 OptRegions.erase(OptIt->getFirst());
1886 return OptRegions.empty();
1887 };
1888
1889 // We need up-to-date live-out info. to query live-out register masks in
1890 // regions containing rematerializable instructions.
1891 DAG.RegionLiveOuts.buildLiveRegMap();
1892
1893 // Cache set of registers that are going to be rematerialized.
1894 DenseSet<unsigned> RematRegs;
1895
1896 // Identify rematerializable instructions in the function.
1897 for (unsigned I = 0, E = DAG.Regions.size(); I != E; ++I) {
1898 auto Region = DAG.Regions[I];
1899 for (auto MI = Region.first; MI != Region.second; ++MI) {
1900 // The instruction must be rematerializable.
1901 MachineInstr &DefMI = *MI;
1902 if (!isReMaterializable(DefMI))
1903 continue;
1904
1905 // We only support rematerializing virtual registers with one definition.
1906 Register Reg = DefMI.getOperand(0).getReg();
1907 if (!Reg.isVirtual() || !DAG.MRI.hasOneDef(Reg))
1908 continue;
1909
1910 // We only care to rematerialize the instruction if it has a single
1911 // non-debug user in a different region. The using MI may not belong to a
1912 // region if it is a lone region terminator.
1913 MachineInstr *UseMI = DAG.MRI.getOneNonDBGUser(Reg);
1914 if (!UseMI)
1915 continue;
1916 auto UseRegion = MIRegion.find(UseMI);
1917 if (UseRegion != MIRegion.end() && UseRegion->second == I)
1918 continue;
1919
1920 // Do not rematerialize an instruction if it uses or is used by an
1921 // instruction that we have designated for rematerialization.
1922 // FIXME: Allow for rematerialization chains: this requires 1. updating
1923 // remat points to account for uses that are rematerialized, and 2. either
1924 // rematerializing the candidates in careful ordering, or deferring the
1925 // MBB RP walk until the entire chain has been rematerialized.
1926 if (Rematerializations.contains(UseMI) ||
1927 llvm::any_of(DefMI.operands(), [&RematRegs](MachineOperand &MO) {
1928 return MO.isReg() && RematRegs.contains(MO.getReg());
1929 }))
1930 continue;
1931
1932 // Do not rematerialize an instruction it it uses registers that aren't
1933 // available at its use. This ensures that we are not extending any live
1934 // range while rematerializing.
1935 SlotIndex UseIdx = DAG.LIS->getInstructionIndex(*UseMI).getRegSlot(true);
1936 if (!VirtRegAuxInfo::allUsesAvailableAt(&DefMI, UseIdx, *DAG.LIS, DAG.MRI,
1937 *DAG.TII))
1938 continue;
1939
1940 REMAT_DEBUG(dbgs() << "Region " << I << ": remat instruction " << DefMI);
1941 RematInstruction &Remat =
1942 Rematerializations.try_emplace(&DefMI, UseMI).first->second;
1943
1944 bool RematUseful = false;
1945 if (auto It = OptRegions.find(I); It != OptRegions.end()) {
1946 // Optimistically consider that moving the instruction out of its
1947 // defining region will reduce RP in the latter; this assumes that
1948 // maximum RP in the region is reached somewhere between the defining
1949 // instruction and the end of the region.
1950 REMAT_DEBUG(dbgs() << " Defining region is optimizable\n");
1951 LaneBitmask Mask = DAG.RegionLiveOuts.getLiveRegsForRegionIdx(I)[Reg];
1952 if (ReduceRPInRegion(It, Reg, Mask, RematUseful))
1953 return true;
1954 }
1955
1956 for (unsigned LIRegion = 0; LIRegion != E; ++LIRegion) {
1957 // We are only collecting regions in which the register is a live-in
1958 // (and may be live-through).
1959 auto It = DAG.LiveIns[LIRegion].find(Reg);
1960 if (It == DAG.LiveIns[LIRegion].end() || It->second.none())
1961 continue;
1962 Remat.LiveInRegions.insert(LIRegion);
1963
1964 // Account for the reduction in RP due to the rematerialization in an
1965 // optimizable region in which the defined register is a live-in. This
1966 // is exact for live-through region but optimistic in the using region,
1967 // where RP is actually reduced only if maximum RP is reached somewhere
1968 // between the beginning of the region and the rematerializable
1969 // instruction's use.
1970 if (auto It = OptRegions.find(LIRegion); It != OptRegions.end()) {
1971 REMAT_DEBUG(dbgs() << " Live-in in region " << LIRegion << '\n');
1972 if (ReduceRPInRegion(It, Reg, DAG.LiveIns[LIRegion][Reg],
1973 RematUseful))
1974 return true;
1975 }
1976 }
1977
1978 // If the instruction is not a live-in or live-out in any optimizable
1979 // region then there is no point in rematerializing it.
1980 if (!RematUseful) {
1981 Rematerializations.pop_back();
1982 REMAT_DEBUG(dbgs() << " No impact, not rematerializing instruction\n");
1983 } else {
1984 RematRegs.insert(Reg);
1985 }
1986 }
1987 }
1988
1989 if (TargetOcc) {
1990 // We were trying to increase occupancy but failed, abort the stage.
1991 REMAT_DEBUG(dbgs() << "Cannot increase occupancy\n");
1992 Rematerializations.clear();
1993 return false;
1994 }
1995 REMAT_DEBUG(dbgs() << "Can reduce but not eliminate spilling\n");
1996 return !Rematerializations.empty();
1997}
1998
1999void PreRARematStage::rematerialize() {
2000 const SIInstrInfo *TII = MF.getSubtarget<GCNSubtarget>().getInstrInfo();
2001
2002 // Collect regions whose RP changes in unpredictable way; we will have to
2003 // fully recompute their RP after all rematerailizations.
2004 DenseSet<unsigned> RecomputeRP;
2005
2006 // Rematerialize all instructions.
2007 for (auto &[DefMI, Remat] : Rematerializations) {
2008 MachineBasicBlock::iterator InsertPos(Remat.UseMI);
2010 unsigned DefRegion = MIRegion.at(DefMI);
2011
2012 // Rematerialize DefMI to its use block.
2013 TII->reMaterialize(*InsertPos->getParent(), InsertPos, Reg,
2014 AMDGPU::NoSubRegister, *DefMI, *DAG.TRI);
2015 Remat.RematMI = &*std::prev(InsertPos);
2016 DAG.LIS->InsertMachineInstrInMaps(*Remat.RematMI);
2017
2018 // Update region boundaries in regions we sinked from (remove defining MI)
2019 // and to (insert MI rematerialized in use block). Only then we can erase
2020 // the original MI.
2021 DAG.updateRegionBoundaries(DAG.Regions[DefRegion], DefMI, nullptr);
2022 auto UseRegion = MIRegion.find(Remat.UseMI);
2023 if (UseRegion != MIRegion.end()) {
2024 DAG.updateRegionBoundaries(DAG.Regions[UseRegion->second], InsertPos,
2025 Remat.RematMI);
2026 }
2027 DAG.LIS->RemoveMachineInstrFromMaps(*DefMI);
2029
2030 // Collect all regions impacted by the rematerialization and update their
2031 // live-in/RP information.
2032 for (unsigned I : Remat.LiveInRegions) {
2033 ImpactedRegions.insert({I, DAG.Pressure[I]});
2034 GCNRPTracker::LiveRegSet &RegionLiveIns = DAG.LiveIns[I];
2035
2036#ifdef EXPENSIVE_CHECKS
2037 // All uses are known to be available / live at the remat point. Thus, the
2038 // uses should already be live in to the region.
2039 for (MachineOperand &MO : DefMI->operands()) {
2040 if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
2041 continue;
2042
2043 Register UseReg = MO.getReg();
2044 if (!UseReg.isVirtual())
2045 continue;
2046
2047 LiveInterval &LI = DAG.LIS->getInterval(UseReg);
2048 LaneBitmask LM = DAG.MRI.getMaxLaneMaskForVReg(MO.getReg());
2049 if (LI.hasSubRanges() && MO.getSubReg())
2050 LM = DAG.TRI->getSubRegIndexLaneMask(MO.getSubReg());
2051
2052 LaneBitmask LiveInMask = RegionLiveIns.at(UseReg);
2053 LaneBitmask UncoveredLanes = LM & ~(LiveInMask & LM);
2054 // If this register has lanes not covered by the LiveIns, be sure they
2055 // do not map to any subrange. ref:
2056 // machine-scheduler-sink-trivial-remats.mir::omitted_subrange
2057 if (UncoveredLanes.any()) {
2058 assert(LI.hasSubRanges());
2059 for (LiveInterval::SubRange &SR : LI.subranges())
2060 assert((SR.LaneMask & UncoveredLanes).none());
2061 }
2062 }
2063#endif
2064
2065 // The register is no longer a live-in in all regions but the one that
2066 // contains the single use. In live-through regions, maximum register
2067 // pressure decreases predictably so we can directly update it. In the
2068 // using region, maximum RP may or may not decrease, so we will mark it
2069 // for re-computation after all materializations have taken place.
2070 LaneBitmask PrevMask = RegionLiveIns[Reg];
2071 RegionLiveIns.erase(Reg);
2072 RegMasks.insert({{I, Remat.RematMI->getOperand(0).getReg()}, PrevMask});
2073 if (Remat.UseMI->getParent() != DAG.Regions[I].first->getParent())
2074 DAG.Pressure[I].inc(Reg, PrevMask, LaneBitmask::getNone(), DAG.MRI);
2075 else
2076 RecomputeRP.insert(I);
2077 }
2078 // RP in the region from which the instruction was rematerialized may or may
2079 // not decrease.
2080 ImpactedRegions.insert({DefRegion, DAG.Pressure[DefRegion]});
2081 RecomputeRP.insert(DefRegion);
2082
2083 // Recompute live interval to reflect the register's rematerialization.
2084 Register RematReg = Remat.RematMI->getOperand(0).getReg();
2085 DAG.LIS->removeInterval(RematReg);
2086 DAG.LIS->createAndComputeVirtRegInterval(RematReg);
2087 }
2088
2089 // All regions impacted by at least one rematerialization must be rescheduled.
2090 // Maximum pressure must also be recomputed for all regions where it changed
2091 // non-predictably and checked against the target occupancy.
2092 unsigned DynamicVGPRBlockSize =
2093 MF.getInfo<SIMachineFunctionInfo>()->getDynamicVGPRBlockSize();
2094 AchievedOcc = MFI.getMaxWavesPerEU();
2095 for (auto &[I, OriginalRP] : ImpactedRegions) {
2096 bool IsEmptyRegion = DAG.Regions[I].first == DAG.Regions[I].second;
2097 RescheduleRegions[I] = !IsEmptyRegion;
2098 if (!RecomputeRP.contains(I))
2099 continue;
2100
2101 GCNRegPressure RP;
2102 if (IsEmptyRegion) {
2103 RP = getRegPressure(DAG.MRI, DAG.LiveIns[I]);
2104 } else {
2105 GCNDownwardRPTracker RPT(*DAG.LIS);
2106 auto *NonDbgMI = &*skipDebugInstructionsForward(DAG.Regions[I].first,
2107 DAG.Regions[I].second);
2108 if (NonDbgMI == DAG.Regions[I].second) {
2109 // Region is non-empty but contains only debug instructions.
2110 RP = getRegPressure(DAG.MRI, DAG.LiveIns[I]);
2111 } else {
2112 RPT.reset(*NonDbgMI, &DAG.LiveIns[I]);
2113 RPT.advance(DAG.Regions[I].second);
2114 RP = RPT.moveMaxPressure();
2115 }
2116 }
2117 DAG.Pressure[I] = RP;
2118 AchievedOcc =
2119 std::min(AchievedOcc, RP.getOccupancy(ST, DynamicVGPRBlockSize));
2120 }
2121 REMAT_DEBUG(dbgs() << "Achieved occupancy " << AchievedOcc << "\n");
2122}
2123
2124// Copied from MachineLICM
2125bool PreRARematStage::isReMaterializable(const MachineInstr &MI) {
2126 if (!DAG.TII->isReMaterializable(MI))
2127 return false;
2128
2129 for (const MachineOperand &MO : MI.all_uses()) {
2130 // We can't remat physreg uses, unless it is a constant or an ignorable
2131 // use (e.g. implicit exec use on VALU instructions)
2132 if (MO.getReg().isPhysical()) {
2133 if (DAG.MRI.isConstantPhysReg(MO.getReg()) || DAG.TII->isIgnorableUse(MO))
2134 continue;
2135 return false;
2136 }
2137 }
2138
2139 return true;
2140}
2141
2143 // We consider that reducing spilling is always beneficial so we never
2144 // rollback rematerializations in such cases. It's also possible that
2145 // rescheduling lowers occupancy over the one achieved just through remats, in
2146 // which case we do not want to rollback either (the rescheduling was already
2147 // reverted in PreRARematStage::shouldRevertScheduling in such cases).
2148 unsigned MaxOcc = std::max(AchievedOcc, DAG.MinOccupancy);
2149 if (!TargetOcc || MaxOcc >= *TargetOcc)
2150 return;
2151
2152 REMAT_DEBUG(dbgs() << "Rolling back all rematerializations\n");
2153 const SIInstrInfo *TII = MF.getSubtarget<GCNSubtarget>().getInstrInfo();
2154
2155 // Rollback the rematerializations.
2156 for (const auto &[DefMI, Remat] : Rematerializations) {
2157 MachineInstr &RematMI = *Remat.RematMI;
2158 unsigned DefRegion = MIRegion.at(DefMI);
2159 MachineBasicBlock::iterator InsertPos(DAG.Regions[DefRegion].second);
2160 MachineBasicBlock *MBB = RegionBB[DefRegion];
2161 Register Reg = RematMI.getOperand(0).getReg();
2162
2163 // Re-rematerialize MI at the end of its original region. Note that it may
2164 // not be rematerialized exactly in the same position as originally within
2165 // the region, but it should not matter much.
2166 TII->reMaterialize(*MBB, InsertPos, Reg, AMDGPU::NoSubRegister, RematMI,
2167 *DAG.TRI);
2168 MachineInstr *NewMI = &*std::prev(InsertPos);
2169 DAG.LIS->InsertMachineInstrInMaps(*NewMI);
2170
2171 auto UseRegion = MIRegion.find(Remat.UseMI);
2172 if (UseRegion != MIRegion.end()) {
2173 DAG.updateRegionBoundaries(DAG.Regions[UseRegion->second], RematMI,
2174 nullptr);
2175 }
2176 DAG.updateRegionBoundaries(DAG.Regions[DefRegion], InsertPos, NewMI);
2177
2178 // Erase rematerialized MI.
2179 DAG.LIS->RemoveMachineInstrFromMaps(RematMI);
2180 RematMI.eraseFromParent();
2181
2182 // Recompute live interval for the re-rematerialized register
2183 DAG.LIS->removeInterval(Reg);
2184 DAG.LIS->createAndComputeVirtRegInterval(Reg);
2185
2186 // Re-add the register as a live-in in all regions it used to be one in.
2187 for (unsigned LIRegion : Remat.LiveInRegions)
2188 DAG.LiveIns[LIRegion].insert({Reg, RegMasks.at({LIRegion, Reg})});
2189 }
2190
2191 // Reset RP in all impacted regions.
2192 for (auto &[I, OriginalRP] : ImpactedRegions)
2193 DAG.Pressure[I] = OriginalRP;
2194
2196}
2197
2198void GCNScheduleDAGMILive::updateRegionBoundaries(
2200 MachineInstr *NewMI) {
2201 assert((!NewMI || NewMI != RegionBounds.second) &&
2202 "cannot remove at region end");
2203
2204 if (RegionBounds.first == RegionBounds.second) {
2205 assert(NewMI && "cannot remove from an empty region");
2206 RegionBounds.first = NewMI;
2207 return;
2208 }
2209
2210 // We only care for modifications at the beginning of a non-empty region since
2211 // the upper region boundary is exclusive.
2212 if (MI != RegionBounds.first)
2213 return;
2214 if (!NewMI)
2215 RegionBounds.first = std::next(MI); // Removal
2216 else
2217 RegionBounds.first = NewMI; // Insertion
2218}
2219
2221 const SIInstrInfo *SII = static_cast<const SIInstrInfo *>(DAG->TII);
2222 return any_of(*DAG, [SII](MachineBasicBlock::iterator MI) {
2223 return SII->isIGLPMutationOnly(MI->getOpcode());
2224 });
2225}
2226
2228 MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S,
2229 bool RemoveKillFlags)
2231
2233 HasIGLPInstrs = hasIGLPInstrs(this);
2234 if (HasIGLPInstrs) {
2235 SavedMutations.clear();
2236 SavedMutations.swap(Mutations);
2238 }
2239
2241}
2242
2244 if (HasIGLPInstrs)
2245 SavedMutations.swap(Mutations);
2246
2248}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
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 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 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)
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 SUnit * pickOnlyChoice(SchedBoundary &Zone, const TargetSchedModel *SchedModel)
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
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
if(PassOpts->AAPipeline)
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:41
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:322
bool empty() const
Definition DenseMap.h:109
iterator end()
Definition DenseMap.h:81
const ValueT & at(const_arg_type_t< KeyT > Val) const
at - Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:224
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:233
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...
GCNRegPressure getPressure() const
DenseMap< unsigned, LaneBitmask > LiveRegSet
GCNSchedStrategy & S
GCNRegPressure PressureBefore
bool isRegionWithExcessRP() const
bool mayCauseSpilling(unsigned WavesAfter)
ScheduleMetrics getScheduleMetrics(const std::vector< SUnit > &InputSchedule)
GCNScheduleDAGMILive & DAG
const GCNSchedStageID StageID
std::vector< MachineInstr * > Unsched
GCNRegPressure PressureAfter
MachineFunction & MF
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
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...
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)
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)
unsigned getMaxNumVGPRs(unsigned WavesPerEU, unsigned DynamicVGPRBlockSize) const
unsigned getMaxNumSGPRs(unsigned WavesPerEU, bool Addressable) const
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
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
LLVM_ABI void dump() const
MachineInstrBundleIterator< MachineInstr > iterator
Function & getFunction()
Return the LLVM function that this machine code represents.
Register getReg(unsigned Idx) const
Get the register for the operand index.
Representation of each machine instruction.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
mop_range operands()
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const MachineOperand & getOperand(unsigned i) const
unsigned getSubReg() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
bool shouldRevertScheduling(unsigned WavesAfter) override
bool shouldRevertScheduling(unsigned WavesAfter) override
bool shouldRevertScheduling(unsigned WavesAfter) override
bool initGCNSchedStage() override
Capture a change in pressure for a single pressure set.
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.
RegionT * getParent() const
Get the parent of the Region.
Definition RegionInfo.h:362
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 ...
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:74
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:78
bool isIGLPMutationOnly(unsigned Opcode) const
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
Scheduling unit. This is a node in the scheduling DAG.
bool isInstr() const
Returns true if this SUnit refers to a machine instruction as opposed to an SDNode.
unsigned TopReadyCycle
Cycle relative to start when node is ready.
unsigned NodeNum
Entry # of node in the node vector.
unsigned short Latency
Node latency.
bool isScheduled
True once scheduled.
unsigned ParentClusterIdx
The parent cluster id.
unsigned BotReadyCycle
Cycle relative to end when node is ready.
bool 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.
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.
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
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
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.
Target - Wrapper for Target specific information.
bool shouldRevertScheduling(unsigned WavesAfter) override
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
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#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)
unsigned getDynamicVGPRBlockSize(const Function &F)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
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)
GCNRegPressure getRegPressure(const MachineRegisterInfo &MRI, Range &&LiveRegs)
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:1732
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:406
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:167
LLVM_ABI cl::opt< bool > VerifyScheduling
LLVM_ABI bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary &Zone)
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)
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:1867
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.
LLVM_ABI int biasPhysReg(const SUnit *SU, bool isTop)
Minimize physical register live ranges.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
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
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...