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 // Aggressively try to reduce register pressure in the unclustered high RP
1232 // stage. Temporarily increase occupancy target in the region.
1233 TempTargetOccupancy = MFI.getMaxWavesPerEU() > DAG.MinOccupancy
1234 ? InitialOccupancy + 1
1235 : InitialOccupancy;
1236 IsAnyRegionScheduled = false;
1237 S.SGPRLimitBias = S.HighRPSGPRBias;
1238 S.VGPRLimitBias = S.HighRPVGPRBias;
1239
1240 LLVM_DEBUG(
1241 dbgs()
1242 << "Retrying function scheduling without clustering. "
1243 "Aggressively try to reduce register pressure to achieve occupancy "
1244 << TempTargetOccupancy << ".\n");
1245
1246 return true;
1247}
1248
1251 return false;
1252
1254 return false;
1255
1256 // Don't bother trying to improve ILP in lower RP regions if occupancy has not
1257 // been dropped. All regions will have already been scheduled with the ideal
1258 // occupancy targets.
1259 if (DAG.StartingOccupancy <= DAG.MinOccupancy)
1260 return false;
1261
1262 LLVM_DEBUG(
1263 dbgs() << "Retrying function scheduling with lowest recorded occupancy "
1264 << DAG.MinOccupancy << ".\n");
1265 return true;
1266}
1267
1268/// Allows to easily filter for this stage's debug output.
1269#define REMAT_PREFIX "[PreRARemat] "
1270#define REMAT_DEBUG(X) LLVM_DEBUG(dbgs() << REMAT_PREFIX; X;)
1271
1273 // FIXME: This pass will invalidate cached BBLiveInMap and MBBLiveIns for
1274 // regions inbetween the defs and region we sinked the def to. Will need to be
1275 // fixed if there is another pass after this pass.
1276 assert(!S.hasNextStage());
1277
1278 if (!GCNSchedStage::initGCNSchedStage() || DAG.Regions.size() == 1)
1279 return false;
1280
1281 // Before performing any IR modification record the parent region of each MI
1282 // and the parent MBB of each region.
1283 const unsigned NumRegions = DAG.Regions.size();
1284 RegionBB.reserve(NumRegions);
1285 for (unsigned I = 0; I < NumRegions; ++I) {
1286 RegionBoundaries Region = DAG.Regions[I];
1287 for (auto MI = Region.first; MI != Region.second; ++MI)
1288 MIRegion.insert({&*MI, I});
1289 RegionBB.push_back(Region.first->getParent());
1290 }
1291
1292 if (!canIncreaseOccupancyOrReduceSpill())
1293 return false;
1294
1295 // Rematerialize identified instructions and update scheduler's state.
1296 rematerialize();
1297 if (GCNTrackers)
1298 DAG.RegionLiveOuts.buildLiveRegMap();
1299 REMAT_DEBUG({
1300 dbgs() << "Retrying function scheduling with new min. occupancy of "
1301 << AchievedOcc << " from rematerializing (original was "
1302 << DAG.MinOccupancy;
1303 if (TargetOcc)
1304 dbgs() << ", target was " << *TargetOcc;
1305 dbgs() << ")\n";
1306 });
1307
1308 if (AchievedOcc > DAG.MinOccupancy) {
1309 DAG.MinOccupancy = AchievedOcc;
1311 MFI.increaseOccupancy(MF, DAG.MinOccupancy);
1312 }
1313 return true;
1314}
1315
1317 DAG.finishBlock();
1318 LLVM_DEBUG(dbgs() << "Ending scheduling stage: " << StageID << "\n");
1319}
1320
1322 SavedMutations.swap(DAG.Mutations);
1323 S.SGPRLimitBias = S.VGPRLimitBias = 0;
1324 if (DAG.MinOccupancy > InitialOccupancy) {
1325 assert(IsAnyRegionScheduled);
1327 << " stage successfully increased occupancy to "
1328 << DAG.MinOccupancy << '\n');
1329 } else if (!IsAnyRegionScheduled) {
1330 assert(DAG.MinOccupancy == InitialOccupancy);
1332 << ": No regions scheduled, min occupancy stays at "
1333 << DAG.MinOccupancy << ", MFI occupancy stays at "
1334 << MFI.getOccupancy() << ".\n");
1335 }
1336
1338}
1339
1341 // Check whether this new region is also a new block.
1342 if (DAG.RegionBegin->getParent() != CurrentMBB)
1343 setupNewBlock();
1344
1345 unsigned NumRegionInstrs = std::distance(DAG.begin(), DAG.end());
1346 DAG.enterRegion(CurrentMBB, DAG.begin(), DAG.end(), NumRegionInstrs);
1347
1348 // Skip empty scheduling regions (0 or 1 schedulable instructions).
1349 if (DAG.begin() == DAG.end() || DAG.begin() == std::prev(DAG.end()))
1350 return false;
1351
1352 LLVM_DEBUG(dbgs() << "********** MI Scheduling **********\n");
1353 LLVM_DEBUG(dbgs() << MF.getName() << ":" << printMBBReference(*CurrentMBB)
1354 << " " << CurrentMBB->getName()
1355 << "\n From: " << *DAG.begin() << " To: ";
1356 if (DAG.RegionEnd != CurrentMBB->end()) dbgs() << *DAG.RegionEnd;
1357 else dbgs() << "End";
1358 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
1359
1360 // Save original instruction order before scheduling for possible revert.
1361 Unsched.clear();
1362 Unsched.reserve(DAG.NumRegionInstrs);
1365 const SIInstrInfo *SII = static_cast<const SIInstrInfo *>(DAG.TII);
1366 for (auto &I : DAG) {
1367 Unsched.push_back(&I);
1368 if (SII->isIGLPMutationOnly(I.getOpcode()))
1369 DAG.RegionsWithIGLPInstrs[RegionIdx] = true;
1370 }
1371 } else {
1372 for (auto &I : DAG)
1373 Unsched.push_back(&I);
1374 }
1375
1376 PressureBefore = DAG.Pressure[RegionIdx];
1377
1378 LLVM_DEBUG(
1379 dbgs() << "Pressure before scheduling:\nRegion live-ins:"
1380 << print(DAG.LiveIns[RegionIdx], DAG.MRI)
1381 << "Region live-in pressure: "
1382 << print(llvm::getRegPressure(DAG.MRI, DAG.LiveIns[RegionIdx]))
1383 << "Region register pressure: " << print(PressureBefore));
1384
1385 S.HasHighPressure = false;
1386 S.KnownExcessRP = isRegionWithExcessRP();
1387
1388 if (DAG.RegionsWithIGLPInstrs[RegionIdx] &&
1390 SavedMutations.clear();
1391 SavedMutations.swap(DAG.Mutations);
1392 bool IsInitialStage = StageID == GCNSchedStageID::OccInitialSchedule ||
1394 DAG.addMutation(createIGroupLPDAGMutation(
1395 IsInitialStage ? AMDGPU::SchedulingPhase::Initial
1397 }
1398
1399 return true;
1400}
1401
1403 // Only reschedule regions that have excess register pressure (i.e. spilling)
1404 // or had minimum occupancy at the beginning of the stage (as long as
1405 // rescheduling of previous regions did not make occupancy drop back down to
1406 // the initial minimum).
1407 unsigned DynamicVGPRBlockSize = DAG.MFI.getDynamicVGPRBlockSize();
1408 // If no region has been scheduled yet, the DAG has not yet been updated with
1409 // the occupancy target. So retrieve it from the temporary.
1410 unsigned CurrentTargetOccupancy =
1411 IsAnyRegionScheduled ? DAG.MinOccupancy : TempTargetOccupancy;
1412 if (!DAG.RegionsWithExcessRP[RegionIdx] &&
1413 (CurrentTargetOccupancy <= InitialOccupancy ||
1414 DAG.Pressure[RegionIdx].getOccupancy(ST, DynamicVGPRBlockSize) !=
1415 InitialOccupancy))
1416 return false;
1417
1418 bool IsSchedulingThisRegion = GCNSchedStage::initGCNRegion();
1419 // If this is the first region scheduled during this stage, make the target
1420 // occupancy changes in the DAG and MFI.
1421 if (!IsAnyRegionScheduled && IsSchedulingThisRegion) {
1422 IsAnyRegionScheduled = true;
1423 if (MFI.getMaxWavesPerEU() > DAG.MinOccupancy) {
1424 DAG.MinOccupancy = TempTargetOccupancy;
1425 MFI.increaseOccupancy(MF, TempTargetOccupancy);
1426 }
1427 }
1428 return IsSchedulingThisRegion;
1429}
1430
1432 // We may need to reschedule this region if it wasn't rescheduled in the last
1433 // stage, or if we found it was testing critical register pressure limits in
1434 // the unclustered reschedule stage. The later is because we may not have been
1435 // able to raise the min occupancy in the previous stage so the region may be
1436 // overly constrained even if it was already rescheduled.
1437 if (!DAG.RegionsWithHighRP[RegionIdx])
1438 return false;
1439
1441}
1442
1444 return RescheduleRegions[RegionIdx] && GCNSchedStage::initGCNRegion();
1445}
1446
1448 if (CurrentMBB)
1449 DAG.finishBlock();
1450
1451 CurrentMBB = DAG.RegionBegin->getParent();
1452 DAG.startBlock(CurrentMBB);
1453 // Get real RP for the region if it hasn't be calculated before. After the
1454 // initial schedule stage real RP will be collected after scheduling.
1458 DAG.computeBlockPressure(RegionIdx, CurrentMBB);
1459}
1460
1462 DAG.Regions[RegionIdx] = std::pair(DAG.RegionBegin, DAG.RegionEnd);
1463 if (S.HasHighPressure)
1464 DAG.RegionsWithHighRP[RegionIdx] = true;
1465
1466 // Revert scheduling if we have dropped occupancy or there is some other
1467 // reason that the original schedule is better.
1469
1470 if (DAG.RegionsWithIGLPInstrs[RegionIdx] &&
1472 SavedMutations.swap(DAG.Mutations);
1473
1474 DAG.exitRegion();
1475 advanceRegion();
1476}
1477
1479 // Check the results of scheduling.
1480 PressureAfter = DAG.getRealRegPressure(RegionIdx);
1481
1482 LLVM_DEBUG(dbgs() << "Pressure after scheduling: " << print(PressureAfter));
1483 LLVM_DEBUG(dbgs() << "Region: " << RegionIdx << ".\n");
1484
1485 unsigned DynamicVGPRBlockSize = DAG.MFI.getDynamicVGPRBlockSize();
1486
1487 if (PressureAfter.getSGPRNum() <= S.SGPRCriticalLimit &&
1488 PressureAfter.getVGPRNum(ST.hasGFX90AInsts()) <= S.VGPRCriticalLimit) {
1489 DAG.Pressure[RegionIdx] = PressureAfter;
1490
1491 // Early out if we have achieved the occupancy target.
1492 LLVM_DEBUG(dbgs() << "Pressure in desired limits, done.\n");
1493 return;
1494 }
1495
1496 unsigned TargetOccupancy = std::min(
1497 S.getTargetOccupancy(), ST.getOccupancyWithWorkGroupSizes(MF).second);
1498 unsigned WavesAfter = std::min(
1499 TargetOccupancy, PressureAfter.getOccupancy(ST, DynamicVGPRBlockSize));
1500 unsigned WavesBefore = std::min(
1501 TargetOccupancy, PressureBefore.getOccupancy(ST, DynamicVGPRBlockSize));
1502 LLVM_DEBUG(dbgs() << "Occupancy before scheduling: " << WavesBefore
1503 << ", after " << WavesAfter << ".\n");
1504
1505 // We may not be able to keep the current target occupancy because of the just
1506 // scheduled region. We might still be able to revert scheduling if the
1507 // occupancy before was higher, or if the current schedule has register
1508 // pressure higher than the excess limits which could lead to more spilling.
1509 unsigned NewOccupancy = std::max(WavesAfter, WavesBefore);
1510
1511 // Allow memory bound functions to drop to 4 waves if not limited by an
1512 // attribute.
1513 if (WavesAfter < WavesBefore && WavesAfter < DAG.MinOccupancy &&
1514 WavesAfter >= MFI.getMinAllowedOccupancy()) {
1515 LLVM_DEBUG(dbgs() << "Function is memory bound, allow occupancy drop up to "
1516 << MFI.getMinAllowedOccupancy() << " waves\n");
1517 NewOccupancy = WavesAfter;
1518 }
1519
1520 if (NewOccupancy < DAG.MinOccupancy) {
1521 DAG.MinOccupancy = NewOccupancy;
1522 MFI.limitOccupancy(DAG.MinOccupancy);
1523 LLVM_DEBUG(dbgs() << "Occupancy lowered for the function to "
1524 << DAG.MinOccupancy << ".\n");
1525 }
1526 // The maximum number of arch VGPR on non-unified register file, or the
1527 // maximum VGPR + AGPR in the unified register file case.
1528 unsigned MaxVGPRs = ST.getMaxNumVGPRs(MF);
1529 // The maximum number of arch VGPR for both unified and non-unified register
1530 // file.
1531 unsigned MaxArchVGPRs = std::min(MaxVGPRs, ST.getAddressableNumArchVGPRs());
1532 unsigned MaxSGPRs = ST.getMaxNumSGPRs(MF);
1533
1534 if (PressureAfter.getVGPRNum(ST.hasGFX90AInsts()) > MaxVGPRs ||
1535 PressureAfter.getArchVGPRNum() > MaxArchVGPRs ||
1536 PressureAfter.getAGPRNum() > MaxArchVGPRs ||
1537 PressureAfter.getSGPRNum() > MaxSGPRs) {
1538 DAG.RegionsWithHighRP[RegionIdx] = true;
1539 DAG.RegionsWithExcessRP[RegionIdx] = true;
1540 }
1541
1542 // Revert if this region's schedule would cause a drop in occupancy or
1543 // spilling.
1544 if (shouldRevertScheduling(WavesAfter))
1546 else
1547 DAG.Pressure[RegionIdx] = PressureAfter;
1548}
1549
1550unsigned
1551GCNSchedStage::computeSUnitReadyCycle(const SUnit &SU, unsigned CurrCycle,
1552 DenseMap<unsigned, unsigned> &ReadyCycles,
1553 const TargetSchedModel &SM) {
1554 unsigned ReadyCycle = CurrCycle;
1555 for (auto &D : SU.Preds) {
1556 if (D.isAssignedRegDep()) {
1557 MachineInstr *DefMI = D.getSUnit()->getInstr();
1558 unsigned Latency = SM.computeInstrLatency(DefMI);
1559 unsigned DefReady = ReadyCycles[DAG.getSUnit(DefMI)->NodeNum];
1560 ReadyCycle = std::max(ReadyCycle, DefReady + Latency);
1561 }
1562 }
1563 ReadyCycles[SU.NodeNum] = ReadyCycle;
1564 return ReadyCycle;
1565}
1566
1567#ifndef NDEBUG
1569 bool operator()(std::pair<MachineInstr *, unsigned> A,
1570 std::pair<MachineInstr *, unsigned> B) const {
1571 return A.second < B.second;
1572 }
1573};
1574
1575static void printScheduleModel(std::set<std::pair<MachineInstr *, unsigned>,
1576 EarlierIssuingCycle> &ReadyCycles) {
1577 if (ReadyCycles.empty())
1578 return;
1579 unsigned BBNum = ReadyCycles.begin()->first->getParent()->getNumber();
1580 dbgs() << "\n################## Schedule time ReadyCycles for MBB : " << BBNum
1581 << " ##################\n# Cycle #\t\t\tInstruction "
1582 " "
1583 " \n";
1584 unsigned IPrev = 1;
1585 for (auto &I : ReadyCycles) {
1586 if (I.second > IPrev + 1)
1587 dbgs() << "****************************** BUBBLE OF " << I.second - IPrev
1588 << " CYCLES DETECTED ******************************\n\n";
1589 dbgs() << "[ " << I.second << " ] : " << *I.first << "\n";
1590 IPrev = I.second;
1591 }
1592}
1593#endif
1594
1596GCNSchedStage::getScheduleMetrics(const std::vector<SUnit> &InputSchedule) {
1597#ifndef NDEBUG
1598 std::set<std::pair<MachineInstr *, unsigned>, EarlierIssuingCycle>
1599 ReadyCyclesSorted;
1600#endif
1601 const TargetSchedModel &SM = ST.getInstrInfo()->getSchedModel();
1602 unsigned SumBubbles = 0;
1603 DenseMap<unsigned, unsigned> ReadyCycles;
1604 unsigned CurrCycle = 0;
1605 for (auto &SU : InputSchedule) {
1606 unsigned ReadyCycle =
1607 computeSUnitReadyCycle(SU, CurrCycle, ReadyCycles, SM);
1608 SumBubbles += ReadyCycle - CurrCycle;
1609#ifndef NDEBUG
1610 ReadyCyclesSorted.insert(std::make_pair(SU.getInstr(), ReadyCycle));
1611#endif
1612 CurrCycle = ++ReadyCycle;
1613 }
1614#ifndef NDEBUG
1615 LLVM_DEBUG(
1616 printScheduleModel(ReadyCyclesSorted);
1617 dbgs() << "\n\t"
1618 << "Metric: "
1619 << (SumBubbles
1620 ? (SumBubbles * ScheduleMetrics::ScaleFactor) / CurrCycle
1621 : 1)
1622 << "\n\n");
1623#endif
1624
1625 return ScheduleMetrics(CurrCycle, SumBubbles);
1626}
1627
1630#ifndef NDEBUG
1631 std::set<std::pair<MachineInstr *, unsigned>, EarlierIssuingCycle>
1632 ReadyCyclesSorted;
1633#endif
1634 const TargetSchedModel &SM = ST.getInstrInfo()->getSchedModel();
1635 unsigned SumBubbles = 0;
1636 DenseMap<unsigned, unsigned> ReadyCycles;
1637 unsigned CurrCycle = 0;
1638 for (auto &MI : DAG) {
1639 SUnit *SU = DAG.getSUnit(&MI);
1640 if (!SU)
1641 continue;
1642 unsigned ReadyCycle =
1643 computeSUnitReadyCycle(*SU, CurrCycle, ReadyCycles, SM);
1644 SumBubbles += ReadyCycle - CurrCycle;
1645#ifndef NDEBUG
1646 ReadyCyclesSorted.insert(std::make_pair(SU->getInstr(), ReadyCycle));
1647#endif
1648 CurrCycle = ++ReadyCycle;
1649 }
1650#ifndef NDEBUG
1651 LLVM_DEBUG(
1652 printScheduleModel(ReadyCyclesSorted);
1653 dbgs() << "\n\t"
1654 << "Metric: "
1655 << (SumBubbles
1656 ? (SumBubbles * ScheduleMetrics::ScaleFactor) / CurrCycle
1657 : 1)
1658 << "\n\n");
1659#endif
1660
1661 return ScheduleMetrics(CurrCycle, SumBubbles);
1662}
1663
1664bool GCNSchedStage::shouldRevertScheduling(unsigned WavesAfter) {
1665 if (WavesAfter < DAG.MinOccupancy)
1666 return true;
1667
1668 // For dynamic VGPR mode, we don't want to waste any VGPR blocks.
1669 if (DAG.MFI.isDynamicVGPREnabled()) {
1670 unsigned BlocksBefore = AMDGPU::IsaInfo::getAllocatedNumVGPRBlocks(
1671 &ST, DAG.MFI.getDynamicVGPRBlockSize(),
1672 PressureBefore.getVGPRNum(false));
1673 unsigned BlocksAfter = AMDGPU::IsaInfo::getAllocatedNumVGPRBlocks(
1674 &ST, DAG.MFI.getDynamicVGPRBlockSize(),
1675 PressureAfter.getVGPRNum(false));
1676 if (BlocksAfter > BlocksBefore)
1677 return true;
1678 }
1679
1680 return false;
1681}
1682
1685 return false;
1686
1688 return true;
1689
1690 if (mayCauseSpilling(WavesAfter))
1691 return true;
1692
1693 return false;
1694}
1695
1697 // If RP is not reduced in the unclustered reschedule stage, revert to the
1698 // old schedule.
1699 if ((WavesAfter <=
1700 PressureBefore.getOccupancy(ST, DAG.MFI.getDynamicVGPRBlockSize()) &&
1701 mayCauseSpilling(WavesAfter)) ||
1703 LLVM_DEBUG(dbgs() << "Unclustered reschedule did not help.\n");
1704 return true;
1705 }
1706
1707 // Do not attempt to relax schedule even more if we are already spilling.
1709 return false;
1710
1711 LLVM_DEBUG(
1712 dbgs()
1713 << "\n\t *** In shouldRevertScheduling ***\n"
1714 << " *********** BEFORE UnclusteredHighRPStage ***********\n");
1715 ScheduleMetrics MBefore = getScheduleMetrics(DAG.SUnits);
1716 LLVM_DEBUG(
1717 dbgs()
1718 << "\n *********** AFTER UnclusteredHighRPStage ***********\n");
1720 unsigned OldMetric = MBefore.getMetric();
1721 unsigned NewMetric = MAfter.getMetric();
1722 unsigned WavesBefore = std::min(
1723 S.getTargetOccupancy(),
1724 PressureBefore.getOccupancy(ST, DAG.MFI.getDynamicVGPRBlockSize()));
1725 unsigned Profit =
1726 ((WavesAfter * ScheduleMetrics::ScaleFactor) / WavesBefore *
1728 NewMetric) /
1730 LLVM_DEBUG(dbgs() << "\tMetric before " << MBefore << "\tMetric after "
1731 << MAfter << "Profit: " << Profit << "\n");
1732 return Profit < ScheduleMetrics::ScaleFactor;
1733}
1734
1737 return false;
1738
1740 return true;
1741
1742 if (mayCauseSpilling(WavesAfter))
1743 return true;
1744
1745 return false;
1746}
1747
1749 return GCNSchedStage::shouldRevertScheduling(WavesAfter) ||
1750 mayCauseSpilling(WavesAfter) || (TargetOcc && WavesAfter < TargetOcc);
1751}
1752
1754 if (mayCauseSpilling(WavesAfter))
1755 return true;
1756
1757 return false;
1758}
1759
1761 unsigned WavesAfter) {
1762 return mayCauseSpilling(WavesAfter);
1763}
1764
1765bool GCNSchedStage::mayCauseSpilling(unsigned WavesAfter) {
1766 if (WavesAfter <= MFI.getMinWavesPerEU() && isRegionWithExcessRP() &&
1768 LLVM_DEBUG(dbgs() << "New pressure will result in more spilling.\n");
1769 return true;
1770 }
1771
1772 return false;
1773}
1774
1776 LLVM_DEBUG(dbgs() << "Attempting to revert scheduling.\n");
1777 DAG.RegionEnd = DAG.RegionBegin;
1778 int SkippedDebugInstr = 0;
1779 for (MachineInstr *MI : Unsched) {
1780 if (MI->isDebugInstr()) {
1781 ++SkippedDebugInstr;
1782 continue;
1783 }
1784
1785 if (MI->getIterator() != DAG.RegionEnd) {
1786 DAG.BB->splice(DAG.RegionEnd, DAG.BB, MI);
1787 if (!MI->isDebugInstr())
1788 DAG.LIS->handleMove(*MI, true);
1789 }
1790
1791 // Reset read-undef flags and update them later.
1792 for (auto &Op : MI->all_defs())
1793 Op.setIsUndef(false);
1794 RegisterOperands RegOpers;
1795 RegOpers.collect(*MI, *DAG.TRI, DAG.MRI, DAG.ShouldTrackLaneMasks, false);
1796 if (!MI->isDebugInstr()) {
1797 if (DAG.ShouldTrackLaneMasks) {
1798 // Adjust liveness and add missing dead+read-undef flags.
1799 SlotIndex SlotIdx = DAG.LIS->getInstructionIndex(*MI).getRegSlot();
1800 RegOpers.adjustLaneLiveness(*DAG.LIS, DAG.MRI, SlotIdx, MI);
1801 } else {
1802 // Adjust for missing dead-def flags.
1803 RegOpers.detectDeadDefs(*MI, *DAG.LIS);
1804 }
1805 }
1806 DAG.RegionEnd = MI->getIterator();
1807 ++DAG.RegionEnd;
1808 LLVM_DEBUG(dbgs() << "Scheduling " << *MI);
1809 }
1810
1811 // After reverting schedule, debug instrs will now be at the end of the block
1812 // and RegionEnd will point to the first debug instr. Increment RegionEnd
1813 // pass debug instrs to the actual end of the scheduling region.
1814 while (SkippedDebugInstr-- > 0)
1815 ++DAG.RegionEnd;
1816
1817 // If Unsched.front() instruction is a debug instruction, this will actually
1818 // shrink the region since we moved all debug instructions to the end of the
1819 // block. Find the first instruction that is not a debug instruction.
1820 DAG.RegionBegin = Unsched.front()->getIterator();
1821 if (DAG.RegionBegin->isDebugInstr()) {
1822 for (MachineInstr *MI : Unsched) {
1823 if (MI->isDebugInstr())
1824 continue;
1825 DAG.RegionBegin = MI->getIterator();
1826 break;
1827 }
1828 }
1829
1830 // Then move the debug instructions back into their correct place and set
1831 // RegionBegin and RegionEnd if needed.
1832 DAG.placeDebugValues();
1833
1834 DAG.Regions[RegionIdx] = std::pair(DAG.RegionBegin, DAG.RegionEnd);
1835}
1836
1837bool PreRARematStage::canIncreaseOccupancyOrReduceSpill() {
1838 const Function &F = MF.getFunction();
1839
1840 // Maps optimizable regions (i.e., regions at minimum and register-limited
1841 // occupancy, or regions with spilling) to the target RP we would like to
1842 // reach.
1844 unsigned MaxSGPRs = ST.getMaxNumSGPRs(F);
1845 unsigned MaxVGPRs = ST.getMaxNumVGPRs(F);
1846 auto ResetTargetRegions = [&]() {
1847 OptRegions.clear();
1848 for (unsigned I = 0, E = DAG.Regions.size(); I != E; ++I) {
1849 const GCNRegPressure &RP = DAG.Pressure[I];
1850 GCNRPTarget Target(MaxSGPRs, MaxVGPRs, MF, RP);
1851 if (!Target.satisfied())
1852 OptRegions.insert({I, Target});
1853 }
1854 };
1855
1856 ResetTargetRegions();
1857 if (!OptRegions.empty() || DAG.MinOccupancy >= MFI.getMaxWavesPerEU()) {
1858 // In addition to register usage being above addressable limits, occupancy
1859 // below the minimum is considered like "spilling" as well.
1860 TargetOcc = std::nullopt;
1861 } else {
1862 // There is no spilling and room to improve occupancy; set up "increased
1863 // occupancy targets" for all regions.
1864 TargetOcc = DAG.MinOccupancy + 1;
1865 unsigned VGPRBlockSize =
1866 MF.getInfo<SIMachineFunctionInfo>()->getDynamicVGPRBlockSize();
1867 MaxSGPRs = ST.getMaxNumSGPRs(*TargetOcc, false);
1868 MaxVGPRs = ST.getMaxNumVGPRs(*TargetOcc, VGPRBlockSize);
1869 ResetTargetRegions();
1870 }
1871 REMAT_DEBUG({
1872 dbgs() << "Analyzing ";
1873 MF.getFunction().printAsOperand(dbgs(), false);
1874 dbgs() << ": ";
1875 if (OptRegions.empty()) {
1876 dbgs() << "no objective to achieve, occupancy is maximal at "
1877 << MFI.getMaxWavesPerEU();
1878 } else if (!TargetOcc) {
1879 dbgs() << "reduce spilling (minimum target occupancy is "
1880 << MFI.getMinWavesPerEU() << ')';
1881 } else {
1882 dbgs() << "increase occupancy from " << DAG.MinOccupancy << " to "
1883 << TargetOcc;
1884 }
1885 dbgs() << '\n';
1886 for (unsigned I = 0, E = DAG.Regions.size(); I != E; ++I) {
1887 if (auto OptIt = OptRegions.find(I); OptIt != OptRegions.end()) {
1888 dbgs() << REMAT_PREFIX << " [" << I << "] " << OptIt->getSecond()
1889 << '\n';
1890 }
1891 }
1892 });
1893 if (OptRegions.empty())
1894 return false;
1895
1896 // Accounts for a reduction in RP in an optimizable region. Returns whether we
1897 // estimate that we have identified enough rematerialization opportunities to
1898 // achieve our goal, and sets Progress to true when this particular reduction
1899 // in pressure was helpful toward that goal.
1900 auto ReduceRPInRegion = [&](auto OptIt, Register Reg, LaneBitmask Mask,
1901 bool &Progress) -> bool {
1902 GCNRPTarget &Target = OptIt->getSecond();
1903 if (!Target.isSaveBeneficial(Reg))
1904 return false;
1905 Progress = true;
1906 Target.saveReg(Reg, Mask, DAG.MRI);
1907 if (Target.satisfied())
1908 OptRegions.erase(OptIt->getFirst());
1909 return OptRegions.empty();
1910 };
1911
1912 // We need up-to-date live-out info. to query live-out register masks in
1913 // regions containing rematerializable instructions.
1914 DAG.RegionLiveOuts.buildLiveRegMap();
1915
1916 // Cache set of registers that are going to be rematerialized.
1917 DenseSet<unsigned> RematRegs;
1918
1919 // Identify rematerializable instructions in the function.
1920 for (unsigned I = 0, E = DAG.Regions.size(); I != E; ++I) {
1921 auto Region = DAG.Regions[I];
1922 for (auto MI = Region.first; MI != Region.second; ++MI) {
1923 // The instruction must be rematerializable.
1924 MachineInstr &DefMI = *MI;
1925 if (!isReMaterializable(DefMI))
1926 continue;
1927
1928 // We only support rematerializing virtual registers with one definition.
1929 Register Reg = DefMI.getOperand(0).getReg();
1930 if (!Reg.isVirtual() || !DAG.MRI.hasOneDef(Reg))
1931 continue;
1932
1933 // We only care to rematerialize the instruction if it has a single
1934 // non-debug user in a different region. The using MI may not belong to a
1935 // region if it is a lone region terminator.
1936 MachineInstr *UseMI = DAG.MRI.getOneNonDBGUser(Reg);
1937 if (!UseMI)
1938 continue;
1939 auto UseRegion = MIRegion.find(UseMI);
1940 if (UseRegion != MIRegion.end() && UseRegion->second == I)
1941 continue;
1942
1943 // Do not rematerialize an instruction if it uses or is used by an
1944 // instruction that we have designated for rematerialization.
1945 // FIXME: Allow for rematerialization chains: this requires 1. updating
1946 // remat points to account for uses that are rematerialized, and 2. either
1947 // rematerializing the candidates in careful ordering, or deferring the
1948 // MBB RP walk until the entire chain has been rematerialized.
1949 if (Rematerializations.contains(UseMI) ||
1950 llvm::any_of(DefMI.operands(), [&RematRegs](MachineOperand &MO) {
1951 return MO.isReg() && RematRegs.contains(MO.getReg());
1952 }))
1953 continue;
1954
1955 // Do not rematerialize an instruction it it uses registers that aren't
1956 // available at its use. This ensures that we are not extending any live
1957 // range while rematerializing.
1958 SlotIndex UseIdx = DAG.LIS->getInstructionIndex(*UseMI).getRegSlot(true);
1959 if (!VirtRegAuxInfo::allUsesAvailableAt(&DefMI, UseIdx, *DAG.LIS, DAG.MRI,
1960 *DAG.TII))
1961 continue;
1962
1963 REMAT_DEBUG(dbgs() << "Region " << I << ": remat instruction " << DefMI);
1964 RematInstruction &Remat =
1965 Rematerializations.try_emplace(&DefMI, UseMI).first->second;
1966
1967 bool RematUseful = false;
1968 if (auto It = OptRegions.find(I); It != OptRegions.end()) {
1969 // Optimistically consider that moving the instruction out of its
1970 // defining region will reduce RP in the latter; this assumes that
1971 // maximum RP in the region is reached somewhere between the defining
1972 // instruction and the end of the region.
1973 REMAT_DEBUG(dbgs() << " Defining region is optimizable\n");
1974 LaneBitmask Mask = DAG.RegionLiveOuts.getLiveRegsForRegionIdx(I)[Reg];
1975 if (ReduceRPInRegion(It, Reg, Mask, RematUseful))
1976 return true;
1977 }
1978
1979 for (unsigned LIRegion = 0; LIRegion != E; ++LIRegion) {
1980 // We are only collecting regions in which the register is a live-in
1981 // (and may be live-through).
1982 auto It = DAG.LiveIns[LIRegion].find(Reg);
1983 if (It == DAG.LiveIns[LIRegion].end() || It->second.none())
1984 continue;
1985 Remat.LiveInRegions.insert(LIRegion);
1986
1987 // Account for the reduction in RP due to the rematerialization in an
1988 // optimizable region in which the defined register is a live-in. This
1989 // is exact for live-through region but optimistic in the using region,
1990 // where RP is actually reduced only if maximum RP is reached somewhere
1991 // between the beginning of the region and the rematerializable
1992 // instruction's use.
1993 if (auto It = OptRegions.find(LIRegion); It != OptRegions.end()) {
1994 REMAT_DEBUG(dbgs() << " Live-in in region " << LIRegion << '\n');
1995 if (ReduceRPInRegion(It, Reg, DAG.LiveIns[LIRegion][Reg],
1996 RematUseful))
1997 return true;
1998 }
1999 }
2000
2001 // If the instruction is not a live-in or live-out in any optimizable
2002 // region then there is no point in rematerializing it.
2003 if (!RematUseful) {
2004 Rematerializations.pop_back();
2005 REMAT_DEBUG(dbgs() << " No impact, not rematerializing instruction\n");
2006 } else {
2007 RematRegs.insert(Reg);
2008 }
2009 }
2010 }
2011
2012 if (TargetOcc) {
2013 // We were trying to increase occupancy but failed, abort the stage.
2014 REMAT_DEBUG(dbgs() << "Cannot increase occupancy\n");
2015 Rematerializations.clear();
2016 return false;
2017 }
2018 REMAT_DEBUG(dbgs() << "Can reduce but not eliminate spilling\n");
2019 return !Rematerializations.empty();
2020}
2021
2022void PreRARematStage::rematerialize() {
2023 const SIInstrInfo *TII = MF.getSubtarget<GCNSubtarget>().getInstrInfo();
2024
2025 // Collect regions whose RP changes in unpredictable way; we will have to
2026 // fully recompute their RP after all rematerailizations.
2027 DenseSet<unsigned> RecomputeRP;
2028
2029 // Rematerialize all instructions.
2030 for (auto &[DefMI, Remat] : Rematerializations) {
2031 MachineBasicBlock::iterator InsertPos(Remat.UseMI);
2033 unsigned DefRegion = MIRegion.at(DefMI);
2034
2035 // Rematerialize DefMI to its use block.
2036 TII->reMaterialize(*InsertPos->getParent(), InsertPos, Reg,
2037 AMDGPU::NoSubRegister, *DefMI);
2038 Remat.RematMI = &*std::prev(InsertPos);
2039 DAG.LIS->InsertMachineInstrInMaps(*Remat.RematMI);
2040
2041 // Update region boundaries in regions we sinked from (remove defining MI)
2042 // and to (insert MI rematerialized in use block). Only then we can erase
2043 // the original MI.
2044 DAG.updateRegionBoundaries(DAG.Regions[DefRegion], DefMI, nullptr);
2045 auto UseRegion = MIRegion.find(Remat.UseMI);
2046 if (UseRegion != MIRegion.end()) {
2047 DAG.updateRegionBoundaries(DAG.Regions[UseRegion->second], InsertPos,
2048 Remat.RematMI);
2049 }
2050 DAG.LIS->RemoveMachineInstrFromMaps(*DefMI);
2052
2053 // Collect all regions impacted by the rematerialization and update their
2054 // live-in/RP information.
2055 for (unsigned I : Remat.LiveInRegions) {
2056 ImpactedRegions.insert({I, DAG.Pressure[I]});
2057 GCNRPTracker::LiveRegSet &RegionLiveIns = DAG.LiveIns[I];
2058
2059#ifdef EXPENSIVE_CHECKS
2060 // All uses are known to be available / live at the remat point. Thus, the
2061 // uses should already be live in to the region.
2062 for (MachineOperand &MO : DefMI->operands()) {
2063 if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
2064 continue;
2065
2066 Register UseReg = MO.getReg();
2067 if (!UseReg.isVirtual())
2068 continue;
2069
2070 LiveInterval &LI = DAG.LIS->getInterval(UseReg);
2071 LaneBitmask LM = DAG.MRI.getMaxLaneMaskForVReg(MO.getReg());
2072 if (LI.hasSubRanges() && MO.getSubReg())
2073 LM = DAG.TRI->getSubRegIndexLaneMask(MO.getSubReg());
2074
2075 LaneBitmask LiveInMask = RegionLiveIns.at(UseReg);
2076 LaneBitmask UncoveredLanes = LM & ~(LiveInMask & LM);
2077 // If this register has lanes not covered by the LiveIns, be sure they
2078 // do not map to any subrange. ref:
2079 // machine-scheduler-sink-trivial-remats.mir::omitted_subrange
2080 if (UncoveredLanes.any()) {
2081 assert(LI.hasSubRanges());
2082 for (LiveInterval::SubRange &SR : LI.subranges())
2083 assert((SR.LaneMask & UncoveredLanes).none());
2084 }
2085 }
2086#endif
2087
2088 // The register is no longer a live-in in all regions but the one that
2089 // contains the single use. In live-through regions, maximum register
2090 // pressure decreases predictably so we can directly update it. In the
2091 // using region, maximum RP may or may not decrease, so we will mark it
2092 // for re-computation after all materializations have taken place.
2093 LaneBitmask PrevMask = RegionLiveIns[Reg];
2094 RegionLiveIns.erase(Reg);
2095 RegMasks.insert({{I, Remat.RematMI->getOperand(0).getReg()}, PrevMask});
2096 if (Remat.UseMI->getParent() != DAG.Regions[I].first->getParent())
2097 DAG.Pressure[I].inc(Reg, PrevMask, LaneBitmask::getNone(), DAG.MRI);
2098 else
2099 RecomputeRP.insert(I);
2100 }
2101 // RP in the region from which the instruction was rematerialized may or may
2102 // not decrease.
2103 ImpactedRegions.insert({DefRegion, DAG.Pressure[DefRegion]});
2104 RecomputeRP.insert(DefRegion);
2105
2106 // Recompute live interval to reflect the register's rematerialization.
2107 Register RematReg = Remat.RematMI->getOperand(0).getReg();
2108 DAG.LIS->removeInterval(RematReg);
2109 DAG.LIS->createAndComputeVirtRegInterval(RematReg);
2110 }
2111
2112 // All regions impacted by at least one rematerialization must be rescheduled.
2113 // Maximum pressure must also be recomputed for all regions where it changed
2114 // non-predictably and checked against the target occupancy.
2115 unsigned DynamicVGPRBlockSize =
2116 MF.getInfo<SIMachineFunctionInfo>()->getDynamicVGPRBlockSize();
2117 AchievedOcc = MFI.getMaxWavesPerEU();
2118 for (auto &[I, OriginalRP] : ImpactedRegions) {
2119 bool IsEmptyRegion = DAG.Regions[I].first == DAG.Regions[I].second;
2120 RescheduleRegions[I] = !IsEmptyRegion;
2121 if (!RecomputeRP.contains(I))
2122 continue;
2123
2124 GCNRegPressure RP;
2125 if (IsEmptyRegion) {
2126 RP = getRegPressure(DAG.MRI, DAG.LiveIns[I]);
2127 } else {
2128 GCNDownwardRPTracker RPT(*DAG.LIS);
2129 auto *NonDbgMI = &*skipDebugInstructionsForward(DAG.Regions[I].first,
2130 DAG.Regions[I].second);
2131 if (NonDbgMI == DAG.Regions[I].second) {
2132 // Region is non-empty but contains only debug instructions.
2133 RP = getRegPressure(DAG.MRI, DAG.LiveIns[I]);
2134 } else {
2135 RPT.reset(*NonDbgMI, &DAG.LiveIns[I]);
2136 RPT.advance(DAG.Regions[I].second);
2137 RP = RPT.moveMaxPressure();
2138 }
2139 }
2140 DAG.Pressure[I] = RP;
2141 AchievedOcc =
2142 std::min(AchievedOcc, RP.getOccupancy(ST, DynamicVGPRBlockSize));
2143 }
2144 REMAT_DEBUG(dbgs() << "Achieved occupancy " << AchievedOcc << "\n");
2145}
2146
2147// Copied from MachineLICM
2148bool PreRARematStage::isReMaterializable(const MachineInstr &MI) {
2149 if (!DAG.TII->isReMaterializable(MI))
2150 return false;
2151
2152 for (const MachineOperand &MO : MI.all_uses()) {
2153 // We can't remat physreg uses, unless it is a constant or an ignorable
2154 // use (e.g. implicit exec use on VALU instructions)
2155 if (MO.getReg().isPhysical()) {
2156 if (DAG.MRI.isConstantPhysReg(MO.getReg()) || DAG.TII->isIgnorableUse(MO))
2157 continue;
2158 return false;
2159 }
2160 }
2161
2162 return true;
2163}
2164
2166 // We consider that reducing spilling is always beneficial so we never
2167 // rollback rematerializations in such cases. It's also possible that
2168 // rescheduling lowers occupancy over the one achieved just through remats, in
2169 // which case we do not want to rollback either (the rescheduling was already
2170 // reverted in PreRARematStage::shouldRevertScheduling in such cases).
2171 unsigned MaxOcc = std::max(AchievedOcc, DAG.MinOccupancy);
2172 if (!TargetOcc || MaxOcc >= *TargetOcc)
2173 return;
2174
2175 REMAT_DEBUG(dbgs() << "Rolling back all rematerializations\n");
2176 const SIInstrInfo *TII = MF.getSubtarget<GCNSubtarget>().getInstrInfo();
2177
2178 // Rollback the rematerializations.
2179 for (const auto &[DefMI, Remat] : Rematerializations) {
2180 MachineInstr &RematMI = *Remat.RematMI;
2181 unsigned DefRegion = MIRegion.at(DefMI);
2182 MachineBasicBlock::iterator InsertPos(DAG.Regions[DefRegion].second);
2183 MachineBasicBlock *MBB = RegionBB[DefRegion];
2184 Register Reg = RematMI.getOperand(0).getReg();
2185
2186 // Re-rematerialize MI at the end of its original region. Note that it may
2187 // not be rematerialized exactly in the same position as originally within
2188 // the region, but it should not matter much.
2189 TII->reMaterialize(*MBB, InsertPos, Reg, AMDGPU::NoSubRegister, RematMI);
2190 MachineInstr *NewMI = &*std::prev(InsertPos);
2191 DAG.LIS->InsertMachineInstrInMaps(*NewMI);
2192
2193 auto UseRegion = MIRegion.find(Remat.UseMI);
2194 if (UseRegion != MIRegion.end()) {
2195 DAG.updateRegionBoundaries(DAG.Regions[UseRegion->second], RematMI,
2196 nullptr);
2197 }
2198 DAG.updateRegionBoundaries(DAG.Regions[DefRegion], InsertPos, NewMI);
2199
2200 // Erase rematerialized MI.
2201 DAG.LIS->RemoveMachineInstrFromMaps(RematMI);
2202 RematMI.eraseFromParent();
2203
2204 // Recompute live interval for the re-rematerialized register
2205 DAG.LIS->removeInterval(Reg);
2206 DAG.LIS->createAndComputeVirtRegInterval(Reg);
2207
2208 // Re-add the register as a live-in in all regions it used to be one in.
2209 for (unsigned LIRegion : Remat.LiveInRegions)
2210 DAG.LiveIns[LIRegion].insert({Reg, RegMasks.at({LIRegion, Reg})});
2211 }
2212
2213 // Reset RP in all impacted regions.
2214 for (auto &[I, OriginalRP] : ImpactedRegions)
2215 DAG.Pressure[I] = OriginalRP;
2216
2218}
2219
2220void GCNScheduleDAGMILive::updateRegionBoundaries(
2222 MachineInstr *NewMI) {
2223 assert((!NewMI || NewMI != RegionBounds.second) &&
2224 "cannot remove at region end");
2225
2226 if (RegionBounds.first == RegionBounds.second) {
2227 assert(NewMI && "cannot remove from an empty region");
2228 RegionBounds.first = NewMI;
2229 return;
2230 }
2231
2232 // We only care for modifications at the beginning of a non-empty region since
2233 // the upper region boundary is exclusive.
2234 if (MI != RegionBounds.first)
2235 return;
2236 if (!NewMI)
2237 RegionBounds.first = std::next(MI); // Removal
2238 else
2239 RegionBounds.first = NewMI; // Insertion
2240}
2241
2243 const SIInstrInfo *SII = static_cast<const SIInstrInfo *>(DAG->TII);
2244 return any_of(*DAG, [SII](MachineBasicBlock::iterator MI) {
2245 return SII->isIGLPMutationOnly(MI->getOpcode());
2246 });
2247}
2248
2250 MachineSchedContext *C, std::unique_ptr<MachineSchedStrategy> S,
2251 bool RemoveKillFlags)
2253
2255 HasIGLPInstrs = hasIGLPInstrs(this);
2256 if (HasIGLPInstrs) {
2257 SavedMutations.clear();
2258 SavedMutations.swap(Mutations);
2260 }
2261
2263}
2264
2266 if (HasIGLPInstrs)
2267 SavedMutations.swap(Mutations);
2268
2270}
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:54
#define I(x, y, z)
Definition MD5.cpp:57
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:40
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:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
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...