LLVM 24.0.0git
GCNHazardRecognizer.cpp
Go to the documentation of this file.
1//===-- GCNHazardRecognizers.cpp - GCN Hazard Recognizer Impls ------------===//
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// This file implements hazard recognizers for scheduling on GCN processors.
10//
11//===----------------------------------------------------------------------===//
12
13#include "GCNHazardRecognizer.h"
14#include "AMDGPUTargetMachine.h"
15#include "AMDGPUWaitcntUtils.h"
16#include "GCNSubtarget.h"
18#include "llvm/ADT/Statistic.h"
23#include "llvm/Support/Debug.h"
25
26using namespace llvm;
27
28#define DEBUG_TYPE "gcn-hazard-recognizer"
29// Opt-in debug type for the per-candidate co-execution slot traces, which are
30// far too noisy for the normal debug output. Pass both types to get everything.
31#define DEBUG_TYPE_VERBOSE "gcn-hazard-recognizer-verbose"
32
33STATISTIC(NumWMMANopsHoisted,
34 "Number of WMMA hazard V_NOPs hoisted from loops");
35STATISTIC(NumWMMAHoistingBailed,
36 "Number of WMMA hazards where V_NOP hoisting was not possible");
37
38namespace {
39
40struct MFMAPaddingRatioParser : public cl::parser<unsigned> {
41 MFMAPaddingRatioParser(cl::Option &O) : cl::parser<unsigned>(O) {}
42
43 bool parse(cl::Option &O, StringRef ArgName, StringRef Arg, unsigned &Value) {
44 if (Arg.getAsInteger(0, Value))
45 return O.error("'" + Arg + "' value invalid for uint argument!");
46
47 if (Value > 100)
48 return O.error("'" + Arg + "' value must be in the range [0, 100]!");
49
50 return false;
51 }
52};
53
54} // end anonymous namespace
55
57 MFMAPaddingRatio("amdgpu-mfma-padding-ratio", cl::init(0), cl::Hidden,
58 cl::desc("Fill a percentage of the latency between "
59 "neighboring MFMA with s_nops."));
60
61//===----------------------------------------------------------------------===//
62// Hazard Recognizer Implementation
63//===----------------------------------------------------------------------===//
64
66 const GCNSubtarget &ST);
67
70 MachineLoopInfo *MLI)
71 : Mode(Mode), CurrCycleInstr(nullptr), MF(MF),
72 ST(MF.getSubtarget<GCNSubtarget>()), TII(*ST.getInstrInfo()),
73 TRI(TII.getRegisterInfo()), TSchedModel(TII.getSchedModel()), MLI(MLI),
74 ClauseUses(TRI.getNumRegUnits()), ClauseDefs(TRI.getNumRegUnits()) {
75 MaxLookAhead = MF.getRegInfo().isPhysRegUsed(AMDGPU::AGPR0) ? 19 : 5;
76 RunLdsBranchVmemWARHazardFixup = shouldRunLdsBranchVmemWARHazardFixup(MF, ST);
78 if (isPreRA())
79 dbgs() << " PreRA hazard recognizer: " << MF.getName() << "\n";
80 });
81}
82
86
88 // Dump any active co-execution window that did not complete naturally
89 // (e.g. region ended before the window expired).
91 if (CurrentCoExecStage.has_value()) {
92 unsigned Stage = *CurrentCoExecStage;
93 if (Stage < AMDGPU::MaxCoExecStages)
94 CoExecWindowLog[Stage] = ActiveCoExecInfo.Pattern[Stage];
95 dbgs() << " CoExec window ended at stage " << Stage << ":\n";
96 dumpCoExecWindow();
97 }
98 });
99}
100
102 EmittedInstrs.clear();
103 EmittedVALUInstrs.clear();
104 HasPendingWMMACoexecHazard = false;
105 if (isSchedulerMode())
106 schedulerReset();
107}
108
109void GCNHazardRecognizer::schedulerReset() {
110 LLVM_DEBUG({
111 if (CurrentCoExecStage.has_value() || CyclesUntilTRANS > 0 ||
112 CyclesUntilVALU > 0)
113 dbgs() << " Scheduler Reset: clearing co-exec window, TRANS="
114 << CyclesUntilTRANS << ", VALU=" << CyclesUntilVALU << "\n";
115 });
116 CurrentCoExecStage = std::nullopt;
117 CyclesUntilTRANS = 0;
118 CyclesUntilVALU = 0;
119 ActiveCoExecInfo = AMDGPU::CoExecInfo();
120 CoExecWindowLog.fill('.');
121}
122
123void GCNHazardRecognizer::dumpCoExecWindow() const {
124 unsigned W = ActiveCoExecInfo.TotalWindow;
125 if (W == 0)
126 return;
127
128 // Print the stage numbers row.
129 dbgs() << " Stages: ";
130 for (unsigned I = 0; I < W; ++I)
131 dbgs() << I % 10 << ' ';
132 dbgs() << '\n';
133
134 // Print the pattern row.
135 dbgs() << " Slots: ";
136 for (unsigned I = 0; I < W; ++I)
137 dbgs() << ActiveCoExecInfo.Pattern[I] << ' ';
138 dbgs() << '\n';
139
140 // Print the scheduled row.
141 dbgs() << " Scheduled: ";
142 for (unsigned I = 0; I < W; ++I)
143 dbgs() << CoExecWindowLog[I] << ' ';
144 dbgs() << '\n';
145}
146
147void GCNHazardRecognizer::schedulerAdvanceCycle() {
148 // Record what happened at the current stage of the co-exec window.
149 if (CurrentCoExecStage.has_value()) {
150 unsigned Stage = *CurrentCoExecStage;
151 if (Stage < AMDGPU::MaxCoExecStages) {
152 if (CurrCycleInstr)
153 CoExecWindowLog[Stage] = ActiveCoExecInfo.Pattern[Stage];
154 else
155 CoExecWindowLog[Stage] = '-';
156 }
157 }
158
159 LLVM_DEBUG({
160 bool HasState = CurrentCoExecStage.has_value() || CyclesUntilTRANS > 0 ||
161 CyclesUntilVALU > 0;
162 if (HasState) {
163 dbgs() << " Scheduler AdvanceCycle:";
164 if (CurrentCoExecStage.has_value()) {
165 unsigned Stage = *CurrentCoExecStage;
166 unsigned Next = Stage + 1;
167 if (Next >= ActiveCoExecInfo.TotalWindow)
168 dbgs() << " stage " << Stage << "->expired";
169 else
170 dbgs() << " stage " << Stage << "->" << Next;
171 }
172 if (CyclesUntilTRANS > 0)
173 dbgs() << " TRANS=" << CyclesUntilTRANS << "->"
174 << (CyclesUntilTRANS - 1);
175 if (CyclesUntilVALU > 0)
176 dbgs() << " VALU=" << CyclesUntilVALU << "->" << (CyclesUntilVALU - 1);
177 dbgs() << "\n";
178 }
179 });
180
181 // Decrement hazard counters.
182 if (CyclesUntilTRANS > 0)
183 --CyclesUntilTRANS;
184 if (CyclesUntilVALU > 0)
185 --CyclesUntilVALU;
186
187 // Advance WMMA co-execution window.
188 if (CurrentCoExecStage.has_value()) {
189 unsigned Stage = *CurrentCoExecStage + 1;
190 if (Stage >= ActiveCoExecInfo.TotalWindow) {
191 // Window expired.
192 LLVM_DEBUG({
193 dbgs() << " CoExec window complete:\n";
194 dumpCoExecWindow();
195 });
196 CurrentCoExecStage = std::nullopt;
197 } else {
198 CurrentCoExecStage = Stage;
199 }
200 }
201}
202
203bool GCNHazardRecognizer::hasCoExecWindowModel() const {
204 // The co-execution slot patterns returned by getCoExecInfo() are derived from
205 // gfx1250 timings, so the window model is restricted to gfx1250 for now.
206 // gfx1251 and gfx12.5-generic report the same co-execution hazard features
207 // but have different WMMA latencies, so they need their own slot patterns
208 // before they can be modeled here.
209 if (ST.hasWMMACoexecutionHazards() && ST.hasTransCoexecutionHazard() &&
211 return true;
212
213 if (ST.hasGFX940Insts() &&
214 AMDGPU::getSchedStrategy(ST.getCLOpts(), MF.getFunction()) == "coexec")
215 return true;
216
217 return false;
218}
219
220void GCNHazardRecognizer::updateWMMAWindowState(const MachineInstr &MI) {
221 if (!hasCoExecWindowModel())
222 return;
223
226 return;
227
228 // If a previous window was still active, dump it before starting a new one.
229 // Record the current stage (filled by this new WMMA) before dumping.
230 LLVM_DEBUG({
231 if (CurrentCoExecStage.has_value()) {
232 unsigned Stage = *CurrentCoExecStage;
233 if (Stage < AMDGPU::MaxCoExecStages)
234 CoExecWindowLog[Stage] = ActiveCoExecInfo.Pattern[Stage];
235 dbgs() << " CoExec window interrupted at stage " << Stage << ":\n";
236 dumpCoExecWindow();
237 }
238 });
239
240 // Start a new co-execution window.
241 ActiveCoExecInfo = AMDGPU::getCoExecInfo(MI, TII);
242 CurrentCoExecStage = 0;
243 CoExecWindowLog.fill('.');
244
245 LLVM_DEBUG(dbgs() << " WMMA window started: " << ActiveCoExecInfo.Pattern
246 << " (window=" << ActiveCoExecInfo.TotalWindow << ")\n"
247 << " " << MI);
248}
249
250void GCNHazardRecognizer::updateTRANSState(const MachineInstr &MI) {
251 if (!hasCoExecWindowModel())
252 return;
254 return;
255
256 // Back-to-back TRANS instructions have a 1-cycle hazard.
257 // This is checked via checkTRANSHazard() and does not create a co-exec
258 // window. The TRANS shadow slot allows anything except TRANS and
259 // multi-cycle VALU.
260 // Set to 2: bumpCycle advances to the next pick's cycle (decrementing
261 // by 1 via AdvanceCycle) before the next instruction's hazard check, so
262 // the counter is observed at 1 there. That 1-cycle stall lets the
263 // strategy pick a non-TRANS, non-multi-cycle-VALU candidate to fill the
264 // shadow slot.
265 CyclesUntilTRANS = 2;
266 LLVM_DEBUG(dbgs() << " TRANS hazard set: CyclesUntilTRANS=2\n");
267}
268
269void GCNHazardRecognizer::updateMultiCycleVALUState(const MachineInstr &MI) {
270 if (!hasCoExecWindowModel())
271 return;
272 // Multi-cycle VALU (CVT, etc.) blocks subsequent VALU for BlockingCycles
273 // cycles.
274 if (!SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/true))
275 return;
276
277 // Skip WMMA, MFMA, and TRANS - they have their own tracking.
280 return;
281
282 unsigned BlockingCycles = TII.getBlockingCycles(MI);
283 if (BlockingCycles > 1) {
284 // bumpCycle's AdvanceCycle decrements once before the next pick's
285 // hazard check (same convention as CyclesUntilTRANS), so to expose
286 // BlockingCycles-1 cycles of shadow we must seed with BlockingCycles.
287 CyclesUntilVALU = BlockingCycles;
288 LLVM_DEBUG(dbgs() << " Multi-cycle VALU: BlockingCycles="
289 << BlockingCycles
290 << ", CyclesUntilVALU=" << CyclesUntilVALU << "\n");
291 }
292}
293
299
300unsigned GCNHazardRecognizer::checkTRANSHazard(const MachineInstr &MI) const {
301 if (!CyclesUntilTRANS)
302 return 0;
303
304 // Only TRANS and multi-cycle VALU are blocked by the TRANS shadow.
306 return CyclesUntilTRANS;
307
308 if (SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/true) &&
310 TII.getBlockingCycles(MI) > 1)
311 return CyclesUntilTRANS;
312
313 return 0;
314}
315
316unsigned
317GCNHazardRecognizer::checkMultiCycleVALUHazard(const MachineInstr &MI) const {
318 if (!CyclesUntilVALU)
319 return 0;
320
321 // Multi-cycle VALU blocks anything on the VALU pipe - VALU, WMMA, SWMMAC,
322 // and TRANS - for BlockingCycles-1 cycles. Only off-pipe instructions (MEM,
323 // SALU, control) can fill the shadow.
324 if (!SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/true) &&
327 return 0;
328
329 return CyclesUntilVALU;
330}
331
332unsigned
333GCNHazardRecognizer::checkWMMACoexecSlot(const MachineInstr &MI) const {
334 // No hazard if not in a WMMA window.
335 if (!CurrentCoExecStage.has_value())
336 return 0;
337
338 unsigned Stage = *CurrentCoExecStage;
340 unsigned StallCycles = ActiveCoExecInfo.getStallCycles(InstMask, Stage);
341
342 // No stall required if the instruction can co-execute at the current stage.
343 if (StallCycles == 0)
344 return 0;
345
346 // Stall for the required number of cycles until the next allowed stage.
347 unsigned NextStage = Stage + StallCycles;
348 if (NextStage < ActiveCoExecInfo.TotalWindow) {
351 dbgs() << " CoExec stall: stage=" << Stage << "("
352 << AMDGPU::getStageTypeName(ActiveCoExecInfo.getType(Stage))
353 << ") mask=" << AMDGPU::getCoExecMaskName(InstMask)
354 << " -> stall " << StallCycles << " (next allowed=" << NextStage
355 << ")\n"
356 << " " << MI);
357 return StallCycles;
358 }
359
360 // No compatible slot in window - stall until window ends.
363 dbgs() << " CoExec stall: stage=" << Stage << "("
364 << AMDGPU::getStageTypeName(ActiveCoExecInfo.getType(Stage))
365 << ") mask=" << AMDGPU::getCoExecMaskName(InstMask) << " -> stall "
366 << StallCycles << " (window ends)\n"
367 << " " << MI);
368 return StallCycles;
369}
370
371unsigned
372GCNHazardRecognizer::checkMultiShadowHazard(const MachineInstr &MI) const {
373 // This models a VALU caught in both a WMMA and a TRANS shadow.
374 if (!hasCoExecWindowModel())
375 return 0;
376
377 // No hazard if not in a WMMA window.
378 if (!CurrentCoExecStage.has_value())
379 return 0;
380
381 if (!CyclesUntilTRANS)
382 return 0;
383
384 if (!SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false))
385 return 0;
386
387 // We have a VALU instruction that is under both a TRANS and WMMA shadow.
388 // We need to wait for at least one to clear.
389
390 unsigned LookAheadStage = *CurrentCoExecStage + CyclesUntilTRANS;
392 return CyclesUntilTRANS +
393 ActiveCoExecInfo.getStallCycles(InstMask, LookAheadStage);
394}
395
396void GCNHazardRecognizer::schedulerEmitInstruction(MachineInstr *MI) {
397 LLVM_DEBUG({
398 bool InWindow = CurrentCoExecStage.has_value();
399 bool HasActiveState =
400 InWindow || CyclesUntilTRANS > 0 || CyclesUntilVALU > 0;
401 if (HasActiveState) {
402 if (InWindow) {
403 unsigned Stage = *CurrentCoExecStage;
404 dbgs() << " Stage " << Stage << "("
405 << AMDGPU::getStageTypeName(ActiveCoExecInfo.getType(Stage))
406 << ") Emit ["
408 << "]: " << *MI;
409 } else {
410 dbgs() << " Emit ["
412 << "]: " << *MI;
413 }
414 }
415 });
417 bool HasActiveState = CurrentCoExecStage.has_value() ||
418 CyclesUntilTRANS > 0 || CyclesUntilVALU > 0;
419 if (!HasActiveState)
420 dbgs() << " Emit ["
422 << "]: " << *MI;
423 });
424 updateWMMAWindowState(*MI);
425 updateTRANSState(*MI);
426 updateMultiCycleVALUState(*MI);
427}
428
432
434 CurrCycleInstr = MI;
435 if (isSchedulerMode())
436 schedulerEmitInstruction(MI);
437}
438
439static bool isDivFMas(unsigned Opcode) {
440 return Opcode == AMDGPU::V_DIV_FMAS_F32_e64 || Opcode == AMDGPU::V_DIV_FMAS_F64_e64;
441}
442
443static bool isSGetReg(unsigned Opcode) {
444 return Opcode == AMDGPU::S_GETREG_B32 || Opcode == AMDGPU::S_GETREG_B32_const;
445}
446
447static bool isSSetReg(unsigned Opcode) {
448 switch (Opcode) {
449 case AMDGPU::S_SETREG_B32:
450 case AMDGPU::S_SETREG_B32_mode:
451 case AMDGPU::S_SETREG_IMM32_B32:
452 case AMDGPU::S_SETREG_IMM32_B32_mode:
453 return true;
454 }
455 return false;
456}
457
458static bool isRWLane(unsigned Opcode) {
459 return Opcode == AMDGPU::V_READLANE_B32 || Opcode == AMDGPU::V_WRITELANE_B32;
460}
461
462static bool isRFE(unsigned Opcode) {
463 return Opcode == AMDGPU::S_RFE_B64;
464}
465
466static bool isSMovRel(unsigned Opcode) {
467 switch (Opcode) {
468 case AMDGPU::S_MOVRELS_B32:
469 case AMDGPU::S_MOVRELS_B64:
470 case AMDGPU::S_MOVRELD_B32:
471 case AMDGPU::S_MOVRELD_B64:
472 return true;
473 default:
474 return false;
475 }
476}
477
479 const MachineInstr &MI) {
480 if (TII.isAlwaysGDS(MI.getOpcode()))
481 return true;
482
483 switch (MI.getOpcode()) {
484 case AMDGPU::S_SENDMSG:
485 case AMDGPU::S_SENDMSGHALT:
486 case AMDGPU::S_TTRACEDATA:
487 return true;
488 // These DS opcodes don't support GDS.
489 case AMDGPU::DS_NOP:
490 case AMDGPU::DS_PERMUTE_B32:
491 case AMDGPU::DS_BPERMUTE_B32:
492 return false;
493 default:
494 if (TII.isDS(MI.getOpcode())) {
495 int GDS = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
496 AMDGPU::OpName::gds);
497 if (MI.getOperand(GDS).getImm())
498 return true;
499 }
500 return false;
501 }
502}
503
504static bool isPermlane(const MachineInstr &MI) {
505 unsigned Opcode = MI.getOpcode();
506 return Opcode == AMDGPU::V_PERMLANE16_B32_e64 ||
507 Opcode == AMDGPU::V_PERMLANE64_B32 ||
508 Opcode == AMDGPU::V_PERMLANEX16_B32_e64 ||
509 Opcode == AMDGPU::V_PERMLANE16_VAR_B32_e64 ||
510 Opcode == AMDGPU::V_PERMLANEX16_VAR_B32_e64 ||
511 Opcode == AMDGPU::V_PERMLANE16_SWAP_B32_e32 ||
512 Opcode == AMDGPU::V_PERMLANE16_SWAP_B32_e64 ||
513 Opcode == AMDGPU::V_PERMLANE32_SWAP_B32_e32 ||
514 Opcode == AMDGPU::V_PERMLANE32_SWAP_B32_e64 ||
515 Opcode == AMDGPU::V_PERMLANE_BCAST_B32_e64 ||
516 Opcode == AMDGPU::V_PERMLANE_UP_B32_e64 ||
517 Opcode == AMDGPU::V_PERMLANE_DOWN_B32_e64 ||
518 Opcode == AMDGPU::V_PERMLANE_XOR_B32_e64 ||
519 Opcode == AMDGPU::V_PERMLANE_IDX_GEN_B32_e64;
520}
521
522static bool isLdsDma(const MachineInstr &MI) {
524}
525
526static unsigned getHWReg(const SIInstrInfo *TII, const MachineInstr &RegInstr) {
527 const MachineOperand *RegOp = TII->getNamedOperand(RegInstr,
528 AMDGPU::OpName::simm16);
529 return std::get<0>(AMDGPU::Hwreg::HwregEncoding::decode(RegOp->getImm()));
530}
531
534 MachineInstr *MI = SU->getInstr();
535 // If we are not in "HazardRecognizerMode" and therefore not being run from
536 // the scheduler, track possible stalls from hazards but don't insert noops.
538
539 if (MI->isBundle())
540 return NoHazard;
541
542 // Check co-execution slot hazards and pipeline stalls in scheduler modes.
543 if (isSchedulerMode()) {
544 if (checkMultiShadowHazard(*MI) > 0)
545 return Hazard;
546 if (checkWMMACoexecSlot(*MI) > 0)
547 return Hazard;
548 if (checkTRANSHazard(*MI) > 0)
549 return Hazard;
550 if (checkMultiCycleVALUHazard(*MI) > 0)
551 return Hazard;
552 // The remaining checks are all defined by register dependences.
553 if (!hasPhysRegs())
554 return NoHazard;
555 }
556
557 if (SIInstrInfo::isSMRD(*MI) && checkSMRDHazards(MI) > 0)
558 return HazardType;
559
560 if (ST.hasNSAtoVMEMBug() && checkNSAtoVMEMHazard(MI) > 0)
561 return HazardType;
562
563 if (checkFPAtomicToDenormModeHazard(MI) > 0)
564 return HazardType;
565
566 // Hazards which cannot be mitigated with S_NOPs.
567 if (!isHazardRecognizerMode()) {
568 if (checkWMMACoexecutionHazards(MI) > 0) {
569 HasPendingWMMACoexecHazard = true;
570 return Hazard;
571 }
572 }
573
574 if (ST.hasNoDataDepHazard())
575 return NoHazard;
576
577 if (SIInstrInfo::isVMEM(*MI) && checkVMEMHazards(MI) > 0)
578 return HazardType;
579
580 if (SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/true) &&
581 checkVALUHazards(MI) > 0)
582 return HazardType;
583
584 if (SIInstrInfo::isDPP(*MI) && checkDPPHazards(MI) > 0)
585 return HazardType;
586
587 if (isDivFMas(MI->getOpcode()) && checkDivFMasHazards(MI) > 0)
588 return HazardType;
589
590 if (isRWLane(MI->getOpcode()) && checkRWLaneHazards(MI) > 0)
591 return HazardType;
592
593 if ((SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/false) ||
596 checkMAIVALUHazards(MI) > 0)
597 return HazardType;
598
599 if (isSGetReg(MI->getOpcode()) && checkGetRegHazards(MI) > 0)
600 return HazardType;
601
602 if (isSSetReg(MI->getOpcode()) && checkSetRegHazards(MI) > 0)
603 return HazardType;
604
605 if (isRFE(MI->getOpcode()) && checkRFEHazards(MI) > 0)
606 return HazardType;
607
608 if (((ST.hasReadM0MovRelInterpHazard() &&
609 (TII.isVINTRP(*MI) || isSMovRel(MI->getOpcode()) ||
610 MI->getOpcode() == AMDGPU::DS_WRITE_ADDTID_B32 ||
611 MI->getOpcode() == AMDGPU::DS_READ_ADDTID_B32)) ||
612 (ST.hasReadM0SendMsgHazard() && isSendMsgTraceDataOrGDS(TII, *MI)) ||
613 (ST.hasReadM0LdsDmaHazard() && isLdsDma(*MI)) ||
614 (ST.hasReadM0LdsDirectHazard() &&
615 MI->readsRegister(AMDGPU::LDS_DIRECT, /*TRI=*/nullptr))) &&
616 checkReadM0Hazards(MI) > 0)
617 return HazardType;
618
619 if (SIInstrInfo::isMAI(*MI) && checkMAIHazards(MI) > 0)
620 return HazardType;
621
623 checkMAILdStHazards(MI) > 0)
624 return HazardType;
625
626 if (ST.hasPermlaneForwardingHazard() && isPermlane(*MI) &&
627 checkPermlaneHazards(MI) > 0)
628 return HazardType;
629
630 if (MI->isInlineAsm() && checkInlineAsmHazards(MI) > 0)
631 return HazardType;
632
633 return NoHazard;
634}
635
637 unsigned Quantity) {
638 while (Quantity > 0) {
639 unsigned Arg = std::min(Quantity, 8u);
640 Quantity -= Arg;
641 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII.get(AMDGPU::S_NOP))
642 .addImm(Arg - 1);
643 }
644}
645
646unsigned
647GCNHazardRecognizer::getMFMAPipelineWaitStates(const MachineInstr &MI) const {
648 const MCSchedClassDesc *SC = TSchedModel.resolveSchedClass(&MI);
649 assert(TSchedModel.getWriteProcResBegin(SC) !=
650 TSchedModel.getWriteProcResEnd(SC));
651 return TSchedModel.getWriteProcResBegin(SC)->ReleaseAtCycle;
652}
653
654void GCNHazardRecognizer::processBundle() {
655 MachineBasicBlock::instr_iterator MI = std::next(CurrCycleInstr->getIterator());
656 MachineBasicBlock::instr_iterator E = CurrCycleInstr->getParent()->instr_end();
657 // Check bundled MachineInstr's for hazards.
658 for (; MI != E && MI->isInsideBundle(); ++MI) {
659 CurrCycleInstr = &*MI;
660 unsigned WaitStates = PreEmitNoopsCommon(CurrCycleInstr);
661
663 fixHazards(CurrCycleInstr);
664
665 insertNoopsInBundle(CurrCycleInstr, TII, WaitStates);
666 }
667
668 // It’s unnecessary to track more than MaxLookAhead instructions. Since we
669 // include the bundled MI directly after, only add a maximum of
670 // (MaxLookAhead - 1) noops to EmittedInstrs.
671 for (unsigned i = 0, e = std::min(WaitStates, MaxLookAhead - 1); i < e; ++i)
672 EmittedInstrs.push_front(nullptr);
673
674 EmittedInstrs.push_front(CurrCycleInstr);
675 EmittedInstrs.resize(MaxLookAhead);
676 }
677 CurrCycleInstr = nullptr;
678}
679
680void GCNHazardRecognizer::runOnInstruction(MachineInstr *MI) {
682
683 unsigned NumPreNoops = PreEmitNoops(MI);
684 EmitNoops(NumPreNoops);
685 if (MI->isInsideBundle())
686 insertNoopsInBundle(MI, TII, NumPreNoops);
687 else
688 TII.insertNoops(*MI->getParent(), MachineBasicBlock::iterator(MI),
689 NumPreNoops);
691 AdvanceCycle();
692}
693
696 CurrCycleInstr = MI;
697 unsigned W = PreEmitNoopsCommon(MI);
698 fixHazards(MI);
699 CurrCycleInstr = nullptr;
700 return std::max(W, ST.getCLOpts().snop_padding);
701}
702
704 unsigned W = 0;
705
706 // Check co-execution slot hazards and pipeline stalls in scheduler modes.
707 if (isSchedulerMode()) {
708 W = checkWMMACoexecSlot(*MI);
709 W = std::max(W, checkTRANSHazard(*MI));
710 W = std::max(W, checkMultiCycleVALUHazard(*MI));
711 W = std::max(W, checkMultiShadowHazard(*MI));
712 // The remaining checks are all defined by register dependences.
713 if (!hasPhysRegs())
714 return W;
715 }
716
717 return std::max(W, PreEmitNoopsCommon(MI));
718}
719
721 if (MI->isBundle())
722 return 0;
723
724 int WaitStates = 0;
725
727 return std::max(WaitStates, checkSMRDHazards(MI));
728
729 if (ST.hasNSAtoVMEMBug())
730 WaitStates = std::max(WaitStates, checkNSAtoVMEMHazard(MI));
731
732 WaitStates = std::max(WaitStates, checkFPAtomicToDenormModeHazard(MI));
733
734 if (ST.hasNoDataDepHazard())
735 return WaitStates;
736
738 WaitStates = std::max(WaitStates, checkVMEMHazards(MI));
739
740 if (SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/true))
741 WaitStates = std::max(WaitStates, checkVALUHazards(MI));
742
744 WaitStates = std::max(WaitStates, checkDPPHazards(MI));
745
746 if (isDivFMas(MI->getOpcode()))
747 WaitStates = std::max(WaitStates, checkDivFMasHazards(MI));
748
749 if (isRWLane(MI->getOpcode()))
750 WaitStates = std::max(WaitStates, checkRWLaneHazards(MI));
751
752 if (SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/false) ||
755 WaitStates = std::max(WaitStates, checkMAIVALUHazards(MI));
756
757 if (MI->isInlineAsm())
758 return std::max(WaitStates, checkInlineAsmHazards(MI));
759
760 if (isSGetReg(MI->getOpcode()))
761 return std::max(WaitStates, checkGetRegHazards(MI));
762
763 if (isSSetReg(MI->getOpcode()))
764 return std::max(WaitStates, checkSetRegHazards(MI));
765
766 if (isRFE(MI->getOpcode()))
767 return std::max(WaitStates, checkRFEHazards(MI));
768
769 if ((ST.hasReadM0MovRelInterpHazard() &&
770 (TII.isVINTRP(*MI) || isSMovRel(MI->getOpcode()) ||
771 MI->getOpcode() == AMDGPU::DS_WRITE_ADDTID_B32 ||
772 MI->getOpcode() == AMDGPU::DS_READ_ADDTID_B32)) ||
773 (ST.hasReadM0SendMsgHazard() && isSendMsgTraceDataOrGDS(TII, *MI)) ||
774 (ST.hasReadM0LdsDmaHazard() && isLdsDma(*MI)) ||
775 (ST.hasReadM0LdsDirectHazard() &&
776 MI->readsRegister(AMDGPU::LDS_DIRECT, /*TRI=*/nullptr)))
777 return std::max(WaitStates, checkReadM0Hazards(MI));
778
780 return std::max(WaitStates, checkMAIHazards(MI));
781
783 return std::max(WaitStates, checkMAILdStHazards(MI));
784
785 if (ST.hasPermlaneForwardingHazard() && isPermlane(*MI))
786 return std::max(WaitStates, checkPermlaneHazards(MI));
787
788 return WaitStates;
789}
790
792 EmittedInstrs.push_front(nullptr);
793}
794
796 if (isSchedulerMode())
797 schedulerAdvanceCycle();
798
799 // When the scheduler detects a stall, it will call AdvanceCycle() without
800 // emitting any instructions.
801 if (!CurrCycleInstr) {
802 EmittedInstrs.push_front(nullptr);
803
804 if (HasPendingWMMACoexecHazard)
805 EmittedVALUInstrs.push_front(nullptr);
806 return;
807 }
808
809 HasPendingWMMACoexecHazard = false;
810
811 if (CurrCycleInstr->isBundle()) {
812 processBundle();
813 return;
814 }
815
816 unsigned NumWaitStates = TII.getNumWaitStates(*CurrCycleInstr);
817 if (!NumWaitStates) {
818 CurrCycleInstr = nullptr;
819 return;
820 }
821
822 // Keep track of emitted instructions
823 EmittedInstrs.push_front(CurrCycleInstr);
824
825 bool IsVALUOrWMMA =
826 SIInstrInfo::isVALU(*CurrCycleInstr, /*AllowLDSDMA=*/true) ||
827 SIInstrInfo::isWMMA(*CurrCycleInstr) ||
828 SIInstrInfo::isSWMMAC(*CurrCycleInstr);
829 if (IsVALUOrWMMA) {
830 EmittedVALUInstrs.push_front(CurrCycleInstr);
831 } else {
832 // A pending WMMA co-execution hazard optimistically records stall cycles as
833 // future V_NOPs. If the scheduler instead stalls for a different
834 // (S_NOP-resolvable) hazard and schedules a non-VALU into those cycles,
835 // they will not resolve the VALU-pipe hazard, so drop them here.
836 while (!EmittedVALUInstrs.empty() && EmittedVALUInstrs.front() == nullptr)
837 EmittedVALUInstrs.pop_front();
838 }
839
840 // Add a nullptr for each additional wait state after the first. Make sure
841 // not to add more than getMaxLookAhead() items to the list, since we
842 // truncate the list to that size right after this loop.
843 for (unsigned i = 1, e = std::min(NumWaitStates, getMaxLookAhead());
844 i < e; ++i) {
845 EmittedInstrs.push_front(nullptr);
846 }
847
848 // getMaxLookahead() is the largest number of wait states we will ever need
849 // to insert, so there is no point in keeping track of more than that many
850 // wait states.
851 EmittedInstrs.resize(getMaxLookAhead());
852 if (EmittedVALUInstrs.size() > MaxVALULookAhead)
853 EmittedVALUInstrs.resize(MaxVALULookAhead);
854
855 CurrCycleInstr = nullptr;
856}
857
860 "Bottom-up scheduling shouldn't run in hazard recognizer mode");
861}
862
863//===----------------------------------------------------------------------===//
864// Helper Functions
865//===----------------------------------------------------------------------===//
866
868
869// Search for a hazard in a block and its predecessors.
870template <typename StateT>
871static bool
872hasHazard(StateT InitialState,
873 function_ref<HazardFnResult(StateT &, const MachineInstr &)> IsHazard,
874 function_ref<void(StateT &, const MachineInstr &)> UpdateState,
875 const MachineBasicBlock *InitialMBB,
877 struct StateMapKey {
879 size_t Idx;
880 static bool isEqual(const StateMapKey &LHS, const StateMapKey &RHS) {
881 return LHS.States == RHS.States && LHS.Idx == RHS.Idx;
882 }
883 };
884 struct StateMapKeyTraits : DenseMapInfo<StateMapKey> {
885 static unsigned getHashValue(const StateMapKey &Key) {
886 return StateT::getHashValue((*Key.States)[Key.Idx]);
887 }
888 static unsigned getHashValue(const StateT &State) {
889 return StateT::getHashValue(State);
890 }
891 static bool isEqual(const StateMapKey &LHS, const StateMapKey &RHS) {
892 return StateT::isEqual((*LHS.States)[LHS.Idx], (*RHS.States)[RHS.Idx]);
893 }
894 static bool isEqual(const StateT &LHS, const StateMapKey &RHS) {
895 return StateT::isEqual(LHS, (*RHS.States)[RHS.Idx]);
896 }
897 };
898
901
903 const MachineBasicBlock *MBB = InitialMBB;
904 StateT State = InitialState;
905
907 unsigned WorkIdx = 0;
908 for (;;) {
909 bool Expired = false;
910 for (auto E = MBB->instr_rend(); I != E; ++I) {
911 // No need to look at parent BUNDLE instructions.
912 if (I->isBundle())
913 continue;
914
915 auto Result = IsHazard(State, *I);
916 if (Result == HazardFound)
917 return true;
918 if (Result == HazardExpired) {
919 Expired = true;
920 break;
921 }
922
923 if (I->isInlineAsm() || I->isMetaInstruction())
924 continue;
925
926 UpdateState(State, *I);
927 }
928
929 if (!Expired) {
930 size_t StateIdx = States.size();
931 StateMapKey Key = {&States, StateIdx};
932 auto Insertion = StateMap.insert_as(std::pair(Key, StateIdx), State);
933 if (Insertion.second) {
934 States.emplace_back(State);
935 } else {
936 StateIdx = Insertion.first->second;
937 }
938 for (MachineBasicBlock *Pred : MBB->predecessors())
939 Worklist.insert(std::pair(Pred, StateIdx));
940 }
941
942 if (WorkIdx == Worklist.size())
943 break;
944
945 size_t StateIdx;
946 std::tie(MBB, StateIdx) = Worklist[WorkIdx++];
947 State = States[StateIdx];
948 I = MBB->instr_rbegin();
949 }
950
951 return false;
952}
953
954// Number of trailing terminators of \p Pred not executed on the edge to \p MBB:
955// control leaves at the first terminator branching to \p MBB, so the ones after
956// it are dead on that edge. A fallthrough executes them all.
958 const MachineBasicBlock *MBB) {
959 const SIInstrInfo &TII =
960 *Pred.getParent()->getSubtarget<GCNSubtarget>().getInstrInfo();
961 unsigned Unexecuted = 0, Passed = 0;
962 for (auto I = Pred.instr_rbegin(), E = Pred.instr_rend();
963 I != E && I->isTerminator(); ++I, ++Passed) {
964 // Only an explicit MBB destination identifies this edge; the last match is
965 // the earliest such branch in program order.
966 if (I->isBranch() && I->getNumOperands() > 0 && I->getOperand(0).isMBB() &&
967 TII.getBranchDestBlock(*I) == MBB)
968 Unexecuted = Passed;
969 }
970 return Unexecuted;
971}
972
973// Wait states \p MI adds to a distance. Inline asm may be empty, so it adds
974// none, which is the worst case.
975static unsigned
978 return MI.isInlineAsm() ? 0 : GetNumWaitStates(MI);
979}
980
981namespace {
982
983// Answers GCNHazardRecognizer::getMax*WindowDeficit, which documents the
984// result, by walking the CFG backwards from the instruction being checked,
985// counting distances with GetNumWaitStates. That needs the instruction in its
986// final place, so hazard recognizer mode only. Each object answers one query.
987class WindowDeficitSearch {
988public:
989 WindowDeficitSearch(
990 function_ref<std::optional<int>(const MachineInstr &)> WindowFor,
991 int MaxWindow,
994 : WindowFor(WindowFor), GetNumWaitStates(GetNumWaitStates),
995 MaxWindow(MaxWindow) {}
996
997 int run(const MachineInstr &MI);
998
999private:
1000 // A block to scan upwards from Start, which is Distance away from the
1001 // instruction being checked. In a predecessor, Start is the last instruction
1002 // above the terminators, and Distance includes the ones the edge executes.
1003 struct Arrival {
1004 const MachineBasicBlock *MBB;
1006 int Distance;
1007 };
1008
1009 void arrive(const MachineBasicBlock *MBB,
1011 int Distance);
1012 void scan(Arrival A);
1013
1014 const function_ref<std::optional<int>(const MachineInstr &)> WindowFor;
1015 const GCNHazardRecognizer::GetNumWaitStatesFn GetNumWaitStates;
1016 const int MaxWindow;
1017 int Deficit = 0;
1018 // Pending[D] holds the arrivals at distance D, and Best the smallest distance
1019 // each block has been queued at. Buckets are emptied in increasing distance,
1020 // so the first arrival scanned at a block is the shortest way into it, and
1021 // any later one is stale.
1023 DenseMap<const MachineBasicBlock *, int> Best;
1024};
1025
1026} // end anonymous namespace
1027
1028void WindowDeficitSearch::arrive(
1029 const MachineBasicBlock *MBB,
1031 // No window exceeds MaxWindow, so nothing this far back can beat the deficit
1032 // already found.
1033 if (MaxWindow - Distance <= Deficit)
1034 return;
1035
1036 if (Pending.empty())
1037 Pending.resize(MaxWindow);
1038
1039 auto [It, Inserted] = Best.try_emplace(MBB, Distance);
1040 if (!Inserted) {
1041 if (It->second <= Distance)
1042 return;
1043 It->second = Distance;
1044 }
1045
1046 assert(Distance < MaxWindow && "arrival outside the window");
1047 Pending[Distance].push_back({MBB, Start, Distance});
1048}
1049
1050// \p A is a copy because arrive() may append to the bucket it came from, which
1051// can move that bucket's elements.
1052void WindowDeficitSearch::scan(Arrival A) {
1053 // A shorter way into this block has been queued since.
1054 if (Best.lookup(A.MBB) < A.Distance)
1055 return;
1056
1057 int Distance = A.Distance;
1058 for (auto I = A.Start, E = A.MBB->instr_rend(); I != E; ++I) {
1059 if (I->isBundle())
1060 continue;
1061
1062 if (std::optional<int> Window = WindowFor(*I)) {
1063 assert(*Window >= 0 && *Window <= MaxWindow && "window out of bounds");
1064 Deficit = std::max(Deficit, *Window - Distance);
1065 }
1066
1067 Distance += getCountedWaitStates(*I, GetNumWaitStates);
1068
1069 if (Distance >= MaxWindow)
1070 return;
1071 }
1072
1073 for (const MachineBasicBlock *Pred : A.MBB->predecessors()) {
1074 auto Start = Pred->instr_rbegin(), End = Pred->instr_rend();
1075 for (unsigned N = countUnexecutedTerminators(*Pred, A.MBB); N; --N)
1076 ++Start;
1077
1078 int Executed = 0;
1079 for (; Start != End && Start->isTerminator(); ++Start) {
1080 assert(!WindowFor(*Start) && "terminators must not ask for a window");
1081 Executed += getCountedWaitStates(*Start, GetNumWaitStates);
1082 }
1083
1084 arrive(Pred, Start, Distance + Executed);
1085 }
1086}
1087
1088int WindowDeficitSearch::run(const MachineInstr &MI) {
1089 // Only the part above MI is scanned here, so the block stays out of Best: a
1090 // backedge into it must still scan it from its end.
1091 scan({MI.getParent(), std::next(MI.getReverseIterator()), 0});
1092
1093 // Distances never shrink along a path, so a scan only queues arrivals at the
1094 // distance being swept or further, and one pass over the buckets is enough.
1095 // The inner loop re-reads the size because an edge that adds nothing appends
1096 // to the bucket in hand; Best keeps a cycle that adds nothing from looping.
1097 for (int Distance = 0; Distance < static_cast<int>(Pending.size());
1098 ++Distance)
1099 for (unsigned I = 0; I != Pending[Distance].size(); ++I)
1100 scan(Pending[Distance][I]);
1101
1102 return Deficit;
1103}
1104
1105// Returns a minimum wait states since \p I walking all predecessors.
1106// Only scans until \p IsExpired does not return true.
1107// Can only be run in a hazard recognizer mode.
1108static int
1110 const MachineBasicBlock *MBB,
1112 int WaitStates, GCNHazardRecognizer::IsExpiredFn IsExpired,
1116 for (auto E = MBB->instr_rend(); I != E; ++I) {
1117 // Don't add WaitStates for parent BUNDLE instructions.
1118 if (I->isBundle())
1119 continue;
1120
1121 if (I->isMetaInstruction())
1122 continue;
1123
1124 if (IsHazard(*I))
1125 return WaitStates;
1126
1127 if (I->isInlineAsm())
1128 continue;
1129
1130 WaitStates += GetNumWaitStates(*I);
1131
1132 if (IsExpired(*I, WaitStates))
1133 return std::numeric_limits<int>::max();
1134 }
1135
1136 int MinWaitStates = std::numeric_limits<int>::max();
1137 for (MachineBasicBlock *Pred : MBB->predecessors()) {
1138 if (!Visited.insert(Pred).second)
1139 continue;
1140
1141 int W = getWaitStatesSince(IsHazard, Pred, Pred->instr_rbegin(), WaitStates,
1142 IsExpired, Visited, GetNumWaitStates);
1143
1144 MinWaitStates = std::min(MinWaitStates, W);
1145 }
1146
1147 return MinWaitStates;
1148}
1149
1150static int
1152 const MachineInstr *MI,
1157 return getWaitStatesSince(IsHazard, MI->getParent(),
1158 std::next(MI->getReverseIterator()), 0, IsExpired,
1159 Visited, GetNumWaitStates);
1160}
1161
1162int GCNHazardRecognizer::getMaxWindowDeficit(int MaxWindow,
1163 WindowForFn WindowFor) const {
1165 return WindowDeficitSearch(WindowFor, MaxWindow).run(*CurrCycleInstr);
1166
1167 // EmittedInstrs is capped and can be shorter than the widest window, which
1168 // costs scheduling quality only: the standalone pass still pads.
1169 int Deficit = 0, Distance = 0;
1170 for (MachineInstr *MI : EmittedInstrs) {
1171 if (MI) {
1172 if (std::optional<int> Window = WindowFor(*MI)) {
1173 assert(*Window >= 0 && *Window <= MaxWindow && "window out of bounds");
1174 Deficit = std::max(Deficit, *Window - Distance);
1175 }
1176 }
1177
1178 Distance +=
1180
1181 if (Distance >= MaxWindow)
1182 break;
1183 }
1184 return Deficit;
1185}
1186
1187int GCNHazardRecognizer::getWaitStatesSince(
1188 IsHazardFn IsHazard, int Limit, GetNumWaitStatesFn GetNumWaitStates) const {
1189 if (isHazardRecognizerMode()) {
1190 auto IsExpiredFn = [Limit](const MachineInstr &, int WaitStates) {
1191 return WaitStates >= Limit;
1192 };
1193 return ::getWaitStatesSince(IsHazard, CurrCycleInstr, IsExpiredFn,
1194 GetNumWaitStates);
1195 }
1196
1197 int WaitStates = 0;
1198 for (MachineInstr *MI : EmittedInstrs) {
1199 if (MI) {
1200 if (IsHazard(*MI))
1201 return WaitStates;
1202
1203 if (MI->isInlineAsm())
1204 continue;
1205 }
1206 WaitStates += MI ? GetNumWaitStates(*MI) : 1;
1207
1208 if (WaitStates >= Limit)
1209 break;
1210 }
1211 return std::numeric_limits<int>::max();
1212}
1213
1214int GCNHazardRecognizer::getWaitStatesSince(IsHazardFn IsHazard,
1215 int Limit) const {
1216 return getWaitStatesSince(IsHazard, Limit, SIInstrInfo::getNumWaitStates);
1217}
1218
1219int GCNHazardRecognizer::getMaxVALUWindowDeficit(int MaxWindow,
1220 WindowForFn WindowFor) const {
1221 if (isHazardRecognizerMode()) {
1222 auto GetVALUWaitStates = [](const MachineInstr &MI) -> unsigned {
1223 return SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/true) ? 1 : 0;
1224 };
1225 return WindowDeficitSearch(WindowFor, MaxWindow, GetVALUWaitStates)
1226 .run(*CurrCycleInstr);
1227 }
1228
1229 // EmittedVALUInstrs is capped at MaxVALULookAhead, so a MaxWindow beyond that
1230 // window could miss a hazard. Keep the cap in sync with the wait-state
1231 // tables.
1232 assert(MaxWindow <= static_cast<int>(MaxVALULookAhead) &&
1233 "MaxWindow exceeds the EmittedVALUInstrs lookahead window");
1234 int WaitStates = 0;
1235 for (MachineInstr *MI : EmittedVALUInstrs) {
1236 if (MI) {
1237 if (std::optional<int> Window = WindowFor(*MI)) {
1238 assert(*Window >= 0 && *Window <= MaxWindow && "window out of bounds");
1239 return *Window - WaitStates;
1240 }
1241 }
1242
1243 ++WaitStates;
1244
1245 if (WaitStates >= MaxWindow)
1246 break;
1247 }
1248 return 0;
1249}
1250
1251int GCNHazardRecognizer::getWaitStatesSinceDef(unsigned Reg,
1252 IsHazardFn IsHazardDef,
1253 int Limit) const {
1254 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1255
1256 auto IsHazardFn = [IsHazardDef, TRI, Reg](const MachineInstr &MI) {
1257 return IsHazardDef(MI) && MI.modifiesRegister(Reg, TRI);
1258 };
1259
1260 return getWaitStatesSince(IsHazardFn, Limit);
1261}
1262
1263int GCNHazardRecognizer::getWaitStatesSinceSetReg(IsHazardFn IsHazard,
1264 int Limit) const {
1265 auto IsHazardFn = [IsHazard](const MachineInstr &MI) {
1266 return isSSetReg(MI.getOpcode()) && IsHazard(MI);
1267 };
1268
1269 return getWaitStatesSince(IsHazardFn, Limit);
1270}
1271
1272//===----------------------------------------------------------------------===//
1273// No-op Hazard Detection
1274//===----------------------------------------------------------------------===//
1275
1276static void addRegUnits(const SIRegisterInfo &TRI, BitVector &BV,
1277 MCRegister Reg) {
1278 for (MCRegUnit Unit : TRI.regunits(Reg))
1279 BV.set(static_cast<unsigned>(Unit));
1280}
1281
1284 BitVector &DefSet, BitVector &UseSet) {
1285 for (const MachineOperand &Op : Ops) {
1286 if (Op.isReg())
1287 addRegUnits(TRI, Op.isDef() ? DefSet : UseSet, Op.getReg().asMCReg());
1288 }
1289}
1290
1291void GCNHazardRecognizer::addClauseInst(const MachineInstr &MI) const {
1292 addRegsToSet(TRI, MI.operands(), ClauseDefs, ClauseUses);
1293}
1294
1296 return !SIInstrInfo::isSMRD(*MI);
1297}
1298
1300 return !SIInstrInfo::isVMEM(*MI);
1301}
1302
1303int GCNHazardRecognizer::checkSoftClauseHazards(MachineInstr *MEM) const {
1304 // SMEM soft clause are only present on VI+, and only matter if xnack is
1305 // enabled.
1306 if (!ST.isXNACKEnabled())
1307 return 0;
1308
1309 bool IsSMRD = TII.isSMRD(*MEM);
1310
1311 resetClause();
1312
1313 // A soft-clause is any group of consecutive SMEM instructions. The
1314 // instructions in this group may return out of order and/or may be
1315 // replayed (i.e. the same instruction issued more than once).
1316 //
1317 // In order to handle these situations correctly we need to make sure that
1318 // when a clause has more than one instruction, no instruction in the clause
1319 // writes to a register that is read by another instruction in the clause
1320 // (including itself). If we encounter this situation, we need to break the
1321 // clause by inserting a non SMEM instruction.
1322
1323 for (MachineInstr *MI : EmittedInstrs) {
1324 // When we hit a non-SMEM instruction then we have passed the start of the
1325 // clause and we can stop.
1326 if (!MI)
1327 break;
1328
1330 break;
1331
1332 addClauseInst(*MI);
1333 }
1334
1335 if (ClauseDefs.none())
1336 return 0;
1337
1338 // We need to make sure not to put loads and stores in the same clause if they
1339 // use the same address. For now, just start a new clause whenever we see a
1340 // store.
1341 if (MEM->mayStore())
1342 return 1;
1343
1344 addClauseInst(*MEM);
1345
1346 // If the set of defs and uses intersect then we cannot add this instruction
1347 // to the clause, so we have a hazard.
1348 return ClauseDefs.anyCommon(ClauseUses) ? 1 : 0;
1349}
1350
1351int GCNHazardRecognizer::checkSMRDHazards(MachineInstr *SMRD) const {
1352 int WaitStatesNeeded = 0;
1353
1354 WaitStatesNeeded = checkSoftClauseHazards(SMRD);
1355
1356 // This SMRD hazard only affects SI.
1357 if (!ST.hasSMRDReadVALUDefHazard())
1358 return WaitStatesNeeded;
1359
1360 // A read of an SGPR by SMRD instruction requires 4 wait states when the
1361 // SGPR was written by a VALU instruction.
1362 int SmrdSgprWaitStates = 4;
1363 auto IsHazardDefFn = [this](const MachineInstr &MI) {
1364 return TII.isVALU(MI, /*AllowLDSDMA=*/false);
1365 };
1366 auto IsBufferHazardDefFn = [this](const MachineInstr &MI) {
1367 return TII.isSALU(MI);
1368 };
1369
1370 bool IsBufferSMRD = TII.isBufferSMRD(*SMRD);
1371
1372 for (const MachineOperand &Use : SMRD->uses()) {
1373 if (!Use.isReg())
1374 continue;
1375 int WaitStatesNeededForUse =
1376 SmrdSgprWaitStates - getWaitStatesSinceDef(Use.getReg(), IsHazardDefFn,
1377 SmrdSgprWaitStates);
1378 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
1379
1380 // This fixes what appears to be undocumented hardware behavior in SI where
1381 // s_mov writing a descriptor and s_buffer_load_dword reading the descriptor
1382 // needs some number of nops in between. We don't know how many we need, but
1383 // let's use 4. This wasn't discovered before probably because the only
1384 // case when this happens is when we expand a 64-bit pointer into a full
1385 // descriptor and use s_buffer_load_dword instead of s_load_dword, which was
1386 // probably never encountered in the closed-source land.
1387 if (IsBufferSMRD) {
1388 int WaitStatesNeededForUse =
1389 SmrdSgprWaitStates - getWaitStatesSinceDef(Use.getReg(),
1390 IsBufferHazardDefFn,
1391 SmrdSgprWaitStates);
1392 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
1393 }
1394 }
1395
1396 return WaitStatesNeeded;
1397}
1398
1399int GCNHazardRecognizer::checkVMEMHazards(MachineInstr *VMEM) const {
1400 if (!ST.hasVMEMReadSGPRVALUDefHazard())
1401 return 0;
1402
1403 int WaitStatesNeeded = checkSoftClauseHazards(VMEM);
1404
1405 // A read of an SGPR by a VMEM instruction requires 5 wait states when the
1406 // SGPR was written by a VALU Instruction.
1407 const int VmemSgprWaitStates = 5;
1408 auto IsHazardDefFn = [this](const MachineInstr &MI) {
1409 return TII.isVALU(MI, /*AllowLDSDMA=*/false);
1410 };
1411 for (const MachineOperand &Use : VMEM->uses()) {
1412 if (!Use.isReg() || TRI.isVectorRegister(MF.getRegInfo(), Use.getReg()))
1413 continue;
1414
1415 int WaitStatesNeededForUse =
1416 VmemSgprWaitStates - getWaitStatesSinceDef(Use.getReg(), IsHazardDefFn,
1417 VmemSgprWaitStates);
1418 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
1419 }
1420 return WaitStatesNeeded;
1421}
1422
1423int GCNHazardRecognizer::checkDPPHazards(MachineInstr *DPP) const {
1424 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1425 const SIInstrInfo *TII = ST.getInstrInfo();
1426
1427 // Check for DPP VGPR read after VALU VGPR write and EXEC write.
1428 int DppVgprWaitStates = 2;
1429 int DppExecWaitStates = 5;
1430 int WaitStatesNeeded = 0;
1431 auto IsHazardDefFn = [TII](const MachineInstr &MI) {
1432 return TII->isVALU(MI, /*AllowLDSDMA=*/false);
1433 };
1434
1435 for (const MachineOperand &Use : DPP->uses()) {
1436 if (!Use.isReg() || !TRI->isVGPR(MF.getRegInfo(), Use.getReg()))
1437 continue;
1438 int WaitStatesNeededForUse =
1439 DppVgprWaitStates - getWaitStatesSinceDef(
1440 Use.getReg(),
1441 [](const MachineInstr &) { return true; },
1442 DppVgprWaitStates);
1443 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
1444 }
1445
1446 WaitStatesNeeded = std::max(
1447 WaitStatesNeeded,
1448 DppExecWaitStates - getWaitStatesSinceDef(AMDGPU::EXEC, IsHazardDefFn,
1449 DppExecWaitStates));
1450
1451 return WaitStatesNeeded;
1452}
1453
1454int GCNHazardRecognizer::checkDivFMasHazards(MachineInstr *DivFMas) const {
1455 const SIInstrInfo *TII = ST.getInstrInfo();
1456
1457 // v_div_fmas requires 4 wait states after a write to vcc from a VALU
1458 // instruction.
1459 const int DivFMasWaitStates = 4;
1460 auto IsHazardDefFn = [TII](const MachineInstr &MI) {
1461 return TII->isVALU(MI, /*AllowLDSDMA=*/false);
1462 };
1463 int WaitStatesNeeded = getWaitStatesSinceDef(AMDGPU::VCC, IsHazardDefFn,
1464 DivFMasWaitStates);
1465
1466 return DivFMasWaitStates - WaitStatesNeeded;
1467}
1468
1469int GCNHazardRecognizer::checkGetRegHazards(MachineInstr *GetRegInstr) const {
1470 const SIInstrInfo *TII = ST.getInstrInfo();
1471 unsigned GetRegHWReg = getHWReg(TII, *GetRegInstr);
1472
1473 const int GetRegWaitStates = 2;
1474 auto IsHazardFn = [TII, GetRegHWReg](const MachineInstr &MI) {
1475 return GetRegHWReg == getHWReg(TII, MI);
1476 };
1477 int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, GetRegWaitStates);
1478
1479 return GetRegWaitStates - WaitStatesNeeded;
1480}
1481
1482int GCNHazardRecognizer::checkSetRegHazards(MachineInstr *SetRegInstr) const {
1483 const SIInstrInfo *TII = ST.getInstrInfo();
1484 unsigned HWReg = getHWReg(TII, *SetRegInstr);
1485
1486 const int SetRegWaitStates = ST.getSetRegWaitStates();
1487 auto IsHazardFn = [TII, HWReg](const MachineInstr &MI) {
1488 return HWReg == getHWReg(TII, MI);
1489 };
1490 int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, SetRegWaitStates);
1491 return SetRegWaitStates - WaitStatesNeeded;
1492}
1493
1494int GCNHazardRecognizer::createsVALUHazard(const MachineInstr &MI) const {
1495 if (!MI.mayStore())
1496 return -1;
1497
1498 const SIInstrInfo *TII = ST.getInstrInfo();
1499 unsigned Opcode = MI.getOpcode();
1500 const MCInstrDesc &Desc = MI.getDesc();
1501
1502 int VDataIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
1503 int VDataRCID = -1;
1504 if (VDataIdx != -1)
1505 VDataRCID = TII->getOpRegClassID(Desc.operands()[VDataIdx]);
1506
1507 if (TII->isMUBUF(MI) || TII->isMTBUF(MI)) {
1508 // There is no hazard if the instruction does not use vector regs
1509 // (like wbinvl1)
1510 if (VDataIdx == -1)
1511 return -1;
1512 if (AMDGPU::getRegBitWidth(VDataRCID) > 64) {
1513 // When SOFFSET-dependent wide-store windows apply, the BUFFER_STORE
1514 // source-vgpr WAR hazard exists for every SOFFSET shape; the wait-state
1515 // count differs by SOFFSET and is computed in checkVALUHazardsHelper.
1516 // Otherwise the hazard only exists if soffset is not an SGPR.
1517 if (ST.hasVDecCoExecHazard())
1518 return VDataIdx;
1519 const MachineOperand *SOffset =
1520 TII->getNamedOperand(MI, AMDGPU::OpName::soffset);
1521 if (!SOffset || !SOffset->isReg())
1522 return VDataIdx;
1523 }
1524 }
1525
1526 // MIMG instructions create a hazard if they don't use a 256-bit T# and
1527 // the store size is greater than 8 bytes and they have more than two bits
1528 // of their dmask set.
1529 // All our MIMG definitions use a 256-bit T#, so we can skip checking for them.
1530 if (TII->isMIMG(MI)) {
1531 int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
1532 assert(SRsrcIdx != -1 && AMDGPU::getRegBitWidth(TII->getOpRegClassID(
1533 Desc.operands()[SRsrcIdx])) == 256);
1534 (void)SRsrcIdx;
1535 }
1536
1537 if (TII->isFLAT(MI)) {
1538 // There is no hazard if the instruction does not use vector regs
1539 if (VDataIdx == -1)
1540 return -1;
1541
1542 if (AMDGPU::getRegBitWidth(VDataRCID) > 64)
1543 return VDataIdx;
1544 }
1545
1546 return -1;
1547}
1548
1549int GCNHazardRecognizer::checkUniformWindowVALUHazardsHelper(
1550 Register Reg) const {
1551 // Wide stores need a single wait-state bubble before a VALU that overwrites
1552 // store data. createsVALUHazard already excludes MUBUF/MTBUF stores with an
1553 // SGPR SOFFSET.
1554 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1555
1556 auto IsHazard = [&](const MachineInstr &MI) {
1557 int DataIdx = createsVALUHazard(MI);
1558 return DataIdx >= 0 &&
1559 TRI->regsOverlap(MI.getOperand(DataIdx).getReg(), Reg);
1560 };
1561
1562 return std::max(0, 1 - getWaitStatesSince(IsHazard, /*Limit=*/1));
1563}
1564
1565int GCNHazardRecognizer::checkSOFFSETWindowVALUHazardsHelper(
1566 Register Reg) const {
1567 // The required wait-state window depends on the producer's SOFFSET shape:
1568 // - MUBUF/MTBUF wide store with sgpr SOFFSET: 1 wait state.
1569 // - MUBUF/MTBUF wide store with literal/absent SOFFSET, and FLAT wide
1570 // store: 2 wait states.
1571 // The 1-cycle sgpr-SOFFSET window was measured on gfx950.
1572 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1573 const SIInstrInfo *TII = ST.getInstrInfo();
1574
1575 int WaitStatesNeeded = 0;
1576
1577 // Scan each wait-state window separately and take the max padding needed.
1578 // getWaitStatesSince supplies the minimum distance to a producer over paths.
1579 for (int Window = 1; Window <= 2; ++Window) {
1580 auto IsHazard = [&](const MachineInstr &MI) {
1581 int DataIdx = createsVALUHazard(MI);
1582 if (DataIdx < 0 ||
1583 !TRI->regsOverlap(MI.getOperand(DataIdx).getReg(), Reg))
1584 return false;
1585
1586 // Window 1 matches every hazard producer. Window 2 excludes BUF stores
1587 // with an SGPR SOFFSET, which only require a single wait state.
1588 if (Window == 1 || !TII->isBUF(MI))
1589 return true;
1590
1591 const MachineOperand *SOffset =
1592 TII->getNamedOperand(MI, AMDGPU::OpName::soffset);
1593 return !SOffset || !SOffset->isReg();
1594 };
1595 WaitStatesNeeded = std::max(WaitStatesNeeded,
1596 Window - getWaitStatesSince(IsHazard, Window));
1597 }
1598
1599 return WaitStatesNeeded;
1600}
1601
1602int GCNHazardRecognizer::checkVALUHazardsHelper(
1603 const MachineOperand &Def, const MachineRegisterInfo &MRI) const {
1604 // Helper to check for the hazard where VMEM instructions that store more
1605 // than 8 bytes can have their store data overwritten by the next
1606 // instruction.
1607 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1608
1609 if (!TRI->isVectorRegister(MRI, Def.getReg()))
1610 return 0;
1611
1612 if (ST.hasVDecCoExecHazard())
1613 return checkSOFFSETWindowVALUHazardsHelper(Def.getReg());
1614
1615 return checkUniformWindowVALUHazardsHelper(Def.getReg());
1616}
1617
1618/// Dest sel forwarding issue occurs if additional logic is needed to swizzle /
1619/// pack the computed value into correct bit position of the dest register. This
1620/// occurs if we have SDWA with dst_sel != DWORD or if we have op_sel with
1621/// dst_sel that is not aligned to the register. This function analayzes the \p
1622/// MI and \returns an operand with dst forwarding issue, or nullptr if
1623/// none exists.
1624static const MachineOperand *
1626 if (!SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false))
1627 return nullptr;
1628
1629 const SIInstrInfo *TII = ST.getInstrInfo();
1630
1631 unsigned Opcode = MI.getOpcode();
1632
1633 // There are three different types of instructions
1634 // which produce forwarded dest: 1. SDWA with dst_sel != DWORD, 2. VOP3
1635 // which write hi bits (e.g. op_sel[3] == 1), and 3. FP8DstSelInst
1636 // (instructions with dest byte sel, e.g. CVT_SR_BF8_F32) and
1637 // op_sel[3:2]
1638 // != 0
1639 if (SIInstrInfo::isSDWA(MI)) {
1640 // Type 1: SDWA with dst_sel != DWORD
1641 if (auto *DstSel = TII->getNamedOperand(MI, AMDGPU::OpName::dst_sel))
1642 if (DstSel->getImm() != AMDGPU::SDWA::DWORD)
1643 return TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
1644 }
1645
1646 AMDGPU::FPType IsFP4OrFP8ConvOpc = AMDGPU::getFPDstSelType(Opcode);
1647 if (AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::op_sel)) {
1648 // Type 2: VOP3 which write the hi bits. DST_OP_SEL is a destination
1649 // selector in the VOP3 layout; VOP3P uses this bit for source op_sel_hi.
1651 (TII->getNamedImmOperand(MI, AMDGPU::OpName::src0_modifiers) &
1653 return TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
1654
1655 // Type 2b: VOP3P mix instructions with a tied destination (MIXLO/MIXHI)
1656 // write only one half of vdst and preserve the other half, so treat them
1657 // like a VOP3 destination op_sel write regardless of their source
1658 // op_sel_hi bits.
1659 if (SIInstrInfo::isVOP3P(MI) &&
1660 AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::vdst_in))
1661 return TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
1662
1663 // Type 3: FP8DstSelInst with op_sel[3:2] != 0)
1664 if (IsFP4OrFP8ConvOpc == AMDGPU::FPType::FP8 &&
1665 (TII->getNamedImmOperand(MI, AMDGPU::OpName::src2_modifiers) &
1667 return TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
1668 }
1669
1670 // Special case: nop is required for all the opsel values for fp4 sr variant
1671 // cvt scale instructions
1672 if (IsFP4OrFP8ConvOpc == AMDGPU::FPType::FP4)
1673 return TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
1674
1675 return nullptr;
1676}
1677
1678/// Checks whether the provided \p MI "consumes" the operand with a Dest sel
1679/// fowarding issue \p Dst . We may "consume" the Dst via a standard explicit
1680/// RAW, or through irregular ways (e.g implicit RAW, certain types of WAW)
1682 const MachineOperand *Dst,
1683 const SIRegisterInfo *TRI) {
1684 // We must consider implicit reads of the VALU. SDWA with dst_sel and
1685 // UNUSED_PRESERVE will implicitly read the result from forwarded dest,
1686 // and we must account for that hazard.
1687 // We also must account for WAW hazards. In particular, WAW with dest
1688 // preserve semantics (e.g. VOP3 with op_sel, VOP2 &&
1689 // !zeroesHigh16BitsOfDest) will read the forwarded dest for parity
1690 // check for ECC. Without accounting for this hazard, the ECC will be
1691 // wrong.
1692 // TODO: limit to RAW (including implicit reads) + problematic WAW (i.e.
1693 // complete zeroesHigh16BitsOfDest)
1694 for (auto &Operand : VALU->operands()) {
1695 if (Operand.isReg() && TRI->regsOverlap(Dst->getReg(), Operand.getReg())) {
1696 return true;
1697 }
1698 }
1699 return false;
1700}
1701
1702int GCNHazardRecognizer::checkVALUHazards(MachineInstr *VALU) const {
1703 int WaitStatesNeeded = 0;
1704
1705 if (ST.hasTransForwardingHazard() && !SIInstrInfo::isTRANS(*VALU)) {
1706 const int TransDefWaitstates = 1;
1707
1708 auto IsTransDefFn = [this, VALU](const MachineInstr &MI) {
1710 return false;
1711 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1712 const SIInstrInfo *TII = ST.getInstrInfo();
1713 Register Def = TII->getNamedOperand(MI, AMDGPU::OpName::vdst)->getReg();
1714
1715 for (const MachineOperand &Use : VALU->explicit_uses()) {
1716 if (Use.isReg() && TRI->regsOverlap(Def, Use.getReg()))
1717 return true;
1718 }
1719
1720 return false;
1721 };
1722
1723 int WaitStatesNeededForDef =
1724 TransDefWaitstates -
1725 getWaitStatesSince(IsTransDefFn, TransDefWaitstates);
1726 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
1727 }
1728
1729 if (ST.hasDstSelForwardingHazard() || ST.hasCvtScaleForwardingHazard()) {
1730 const int Shift16DefWaitstates = 1;
1731
1732 auto IsShift16BitDefFn = [this, VALU](const MachineInstr &ProducerMI) {
1733 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1734 const MachineOperand *ForwardedDst =
1735 getDstSelForwardingOperand(ProducerMI, ST);
1736 if (ForwardedDst) {
1737 return consumesDstSelForwardingOperand(VALU, ForwardedDst, TRI);
1738 }
1739
1740 if (ProducerMI.isInlineAsm()) {
1741 // Assume inline asm has dst forwarding hazard
1742 for (auto &Def : ProducerMI.all_defs()) {
1743 if (consumesDstSelForwardingOperand(VALU, &Def, TRI))
1744 return true;
1745 }
1746 }
1747
1748 return false;
1749 };
1750
1751 int WaitStatesNeededForDef =
1752 Shift16DefWaitstates -
1753 getWaitStatesSince(IsShift16BitDefFn, Shift16DefWaitstates);
1754 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
1755 }
1756
1757 if (ST.hasVDecCoExecHazard()) {
1758 const int VALUWriteSGPRVALUReadWaitstates = 2;
1759 const int VALUWriteEXECRWLane = 4;
1760 const int VALUWriteVGPRReadlaneRead = 1;
1761
1762 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1763 const MachineRegisterInfo &MRI = MF.getRegInfo();
1765 auto IsVALUDefSGPRFn = [&UseReg, TRI](const MachineInstr &MI) {
1766 if (!SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false))
1767 return false;
1768 return MI.modifiesRegister(UseReg, TRI);
1769 };
1770
1771 for (const MachineOperand &Use : VALU->explicit_uses()) {
1772 if (!Use.isReg())
1773 continue;
1774
1775 UseReg = Use.getReg();
1776 if (TRI->isSGPRReg(MRI, UseReg)) {
1777 int WaitStatesNeededForDef =
1778 VALUWriteSGPRVALUReadWaitstates -
1779 getWaitStatesSince(IsVALUDefSGPRFn,
1780 VALUWriteSGPRVALUReadWaitstates);
1781 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
1782 }
1783 }
1784
1785 if (VALU->readsRegister(AMDGPU::VCC, TRI)) {
1786 UseReg = AMDGPU::VCC;
1787 int WaitStatesNeededForDef =
1788 VALUWriteSGPRVALUReadWaitstates -
1789 getWaitStatesSince(IsVALUDefSGPRFn, VALUWriteSGPRVALUReadWaitstates);
1790 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
1791 }
1792
1793 switch (VALU->getOpcode()) {
1794 case AMDGPU::V_READLANE_B32:
1795 case AMDGPU::V_READFIRSTLANE_B32: {
1796 MachineOperand *Src = TII.getNamedOperand(*VALU, AMDGPU::OpName::src0);
1797 UseReg = Src->getReg();
1798 int WaitStatesNeededForDef =
1799 VALUWriteVGPRReadlaneRead -
1800 getWaitStatesSince(IsVALUDefSGPRFn, VALUWriteVGPRReadlaneRead);
1801 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
1802 }
1803 [[fallthrough]];
1804 case AMDGPU::V_WRITELANE_B32: {
1805 UseReg = AMDGPU::EXEC;
1806 int WaitStatesNeededForDef =
1807 VALUWriteEXECRWLane -
1808 getWaitStatesSince(IsVALUDefSGPRFn, VALUWriteEXECRWLane);
1809 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
1810 break;
1811 }
1812 default:
1813 break;
1814 }
1815 }
1816
1817 // This checks for the hazard where VMEM instructions that store more than
1818 // 8 bytes can have there store data over written by the next instruction.
1819 if (!ST.has12DWordStoreHazard())
1820 return WaitStatesNeeded;
1821
1822 const MachineRegisterInfo &MRI = MF.getRegInfo();
1823
1824 for (const MachineOperand &Def : VALU->defs()) {
1825 WaitStatesNeeded = std::max(WaitStatesNeeded, checkVALUHazardsHelper(Def, MRI));
1826 }
1827
1828 return WaitStatesNeeded;
1829}
1830
1831int GCNHazardRecognizer::checkInlineAsmHazards(MachineInstr *IA) const {
1832 // This checks for hazards associated with inline asm statements.
1833 // Since inline asms can contain just about anything, we use this
1834 // to call/leverage other check*Hazard routines. Note that
1835 // this function doesn't attempt to address all possible inline asm
1836 // hazards (good luck), but is a collection of what has been
1837 // problematic thus far.
1838
1839 // see checkVALUHazards()
1840 if (!ST.has12DWordStoreHazard() && !ST.hasDstSelForwardingHazard() &&
1841 !ST.hasCvtScaleForwardingHazard())
1842 return 0;
1843
1844 const MachineRegisterInfo &MRI = MF.getRegInfo();
1845 int WaitStatesNeeded = 0;
1846
1847 for (const MachineOperand &Op :
1849 if (Op.isReg() && Op.isDef()) {
1850 if (!TRI.isVectorRegister(MRI, Op.getReg()))
1851 continue;
1852
1853 if (ST.has12DWordStoreHazard()) {
1854 WaitStatesNeeded =
1855 std::max(WaitStatesNeeded, checkVALUHazardsHelper(Op, MRI));
1856 }
1857 }
1858 }
1859
1860 if (ST.hasDstSelForwardingHazard()) {
1861 const int Shift16DefWaitstates = 1;
1862
1863 auto IsShift16BitDefFn = [this, &IA](const MachineInstr &ProducerMI) {
1864 const MachineOperand *Dst = getDstSelForwardingOperand(ProducerMI, ST);
1865 // Assume inline asm reads the dst
1866 if (Dst)
1867 return IA->modifiesRegister(Dst->getReg(), &TRI) ||
1868 IA->readsRegister(Dst->getReg(), &TRI);
1869
1870 if (ProducerMI.isInlineAsm()) {
1871 // If MI is inline asm, assume it has dst forwarding hazard
1872 for (auto &Def : ProducerMI.all_defs()) {
1873 if (IA->modifiesRegister(Def.getReg(), &TRI) ||
1874 IA->readsRegister(Def.getReg(), &TRI)) {
1875 return true;
1876 }
1877 }
1878 }
1879
1880 return false;
1881 };
1882
1883 int WaitStatesNeededForDef =
1884 Shift16DefWaitstates -
1885 getWaitStatesSince(IsShift16BitDefFn, Shift16DefWaitstates);
1886 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
1887 }
1888
1889 return WaitStatesNeeded;
1890}
1891
1892int GCNHazardRecognizer::checkRWLaneHazards(MachineInstr *RWLane) const {
1893 const SIInstrInfo *TII = ST.getInstrInfo();
1894 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1895 const MachineRegisterInfo &MRI = MF.getRegInfo();
1896
1897 const MachineOperand *LaneSelectOp =
1898 TII->getNamedOperand(*RWLane, AMDGPU::OpName::src1);
1899
1900 if (!LaneSelectOp->isReg() || !TRI->isSGPRReg(MRI, LaneSelectOp->getReg()))
1901 return 0;
1902
1903 Register LaneSelectReg = LaneSelectOp->getReg();
1904 auto IsHazardFn = [TII](const MachineInstr &MI) {
1905 return TII->isVALU(MI, /*AllowLDSDMA=*/false);
1906 };
1907
1908 const int RWLaneWaitStates = 4;
1909 int WaitStatesSince = getWaitStatesSinceDef(LaneSelectReg, IsHazardFn,
1910 RWLaneWaitStates);
1911 return RWLaneWaitStates - WaitStatesSince;
1912}
1913
1914int GCNHazardRecognizer::checkRFEHazards(MachineInstr *RFE) const {
1915 if (!ST.hasRFEHazards())
1916 return 0;
1917
1918 const SIInstrInfo *TII = ST.getInstrInfo();
1919
1920 const int RFEWaitStates = 1;
1921
1922 auto IsHazardFn = [TII](const MachineInstr &MI) {
1923 return getHWReg(TII, MI) == AMDGPU::Hwreg::ID_TRAPSTS;
1924 };
1925 int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, RFEWaitStates);
1926 return RFEWaitStates - WaitStatesNeeded;
1927}
1928
1929int GCNHazardRecognizer::checkReadM0Hazards(MachineInstr *MI) const {
1930 const SIInstrInfo *TII = ST.getInstrInfo();
1931 const int ReadM0WaitStates = 1;
1932 auto IsHazardFn = [TII](const MachineInstr &MI) { return TII->isSALU(MI); };
1933 return ReadM0WaitStates -
1934 getWaitStatesSinceDef(AMDGPU::M0, IsHazardFn, ReadM0WaitStates);
1935}
1936
1937void GCNHazardRecognizer::emitVNops(MachineBasicBlock &MBB,
1939 int WaitStatesNeeded, bool IsHoisting) {
1940 const DebugLoc &DL = IsHoisting ? DebugLoc() : InsertPt->getDebugLoc();
1941 for (int I = 0; I < WaitStatesNeeded; ++I)
1942 BuildMI(MBB, InsertPt, DL, TII.get(AMDGPU::V_NOP_e32));
1943}
1944
1945void GCNHazardRecognizer::fixHazards(MachineInstr *MI) {
1946 fixVMEMtoScalarWriteHazards(MI);
1947 fixVcmpxPermlaneHazards(MI);
1948 fixSMEMtoVectorWriteHazards(MI);
1949 fixVcmpxExecWARHazard(MI);
1950 fixLdsBranchVmemWARHazard(MI);
1951 if (ST.hasLdsDirect()) {
1952 fixLdsDirectVALUHazard(MI);
1953 fixLdsDirectVMEMHazard(MI);
1954 }
1955 fixVALUPartialForwardingHazard(MI);
1956 fixVALUTransUseHazard(MI);
1957 fixVALUTransCoexecutionHazards(MI);
1958 fixWMMAHazards(MI); // fall-through if co-execution is enabled.
1959 fixWMMACoexecutionHazards(MI);
1960 fixShift64HighRegBug(MI);
1961 fixVALUMaskWriteHazard(MI);
1962 fixRequiredExportPriority(MI);
1963 if (ST.hasVPermPk16Hazard())
1964 fixVPermPk16Hazard(MI);
1965 if (ST.requiresWaitIdleBeforeGetReg())
1966 fixGetRegWaitIdle(MI);
1967 if (ST.hasDsAtomicAsyncBarrierArriveB64PipeBug())
1968 fixDsAtomicAsyncBarrierArriveB64(MI);
1969 if (ST.hasBarrierJoinCompletionBug())
1970 fixBarrierJoinCompletion(MI);
1971 if (ST.hasScratchBaseForwardingHazard())
1972 fixScratchBaseForwardingHazard(MI);
1973 if (ST.setRegModeNeedsVNOPs())
1974 fixSetRegMode(MI);
1975 if (ST.hasNeedsTDMDrain())
1976 fixTDM(MI);
1977 if (ST.hasTransF16ToPartialVGPRWriteHazard())
1978 fixTransF16ToPartialVGPRWriteHazard(MI);
1979}
1980
1982 const MachineInstr &MI) {
1983 return (TII.isVOPC(MI) ||
1984 (MI.isCompare() && (TII.isVOP3(MI) || TII.isSDWA(MI)))) &&
1985 MI.modifiesRegister(AMDGPU::EXEC, &TRI);
1986}
1987
1988bool GCNHazardRecognizer::fixVcmpxPermlaneHazards(MachineInstr *MI) {
1989 if (!ST.hasVcmpxPermlaneHazard() || !isPermlane(*MI))
1990 return false;
1991
1992 const SIInstrInfo *TII = ST.getInstrInfo();
1993 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1994 auto IsHazardFn = [TII, TRI](const MachineInstr &MI) {
1995 return isVCmpXWritesExec(*TII, *TRI, MI);
1996 };
1997
1998 auto IsExpiredFn = [](const MachineInstr &MI, int) {
1999 unsigned Opc = MI.getOpcode();
2000 return SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/true) &&
2001 Opc != AMDGPU::V_NOP_e32 && Opc != AMDGPU::V_NOP_e64 &&
2002 Opc != AMDGPU::V_NOP_sdwa;
2003 };
2004
2005 if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
2006 std::numeric_limits<int>::max())
2007 return false;
2008
2009 // V_NOP will be discarded by SQ.
2010 // Use V_MOV_B32 v?, v?. Register must be alive so use src0 of V_PERMLANE*
2011 // which is always a VGPR and available.
2012 auto *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
2013 Register Reg = Src0->getReg();
2014 bool IsUndef = Src0->isUndef();
2015 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2016 TII->get(AMDGPU::V_MOV_B32_e32))
2019
2020 return true;
2021}
2022
2023bool GCNHazardRecognizer::fixVMEMtoScalarWriteHazards(MachineInstr *MI) {
2024 if (!ST.hasVMEMtoScalarWriteHazard())
2025 return false;
2026 assert(!ST.hasExtendedWaitCounts());
2027
2029 return false;
2030
2031 if (MI->getNumDefs() == 0)
2032 return false;
2033
2034 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2035
2036 auto IsHazardFn = [TRI, MI](const MachineInstr &I) {
2038 return false;
2039
2040 for (const MachineOperand &Def : MI->defs()) {
2041 const MachineOperand *Op =
2042 I.findRegisterUseOperand(Def.getReg(), TRI, false);
2043 if (!Op)
2044 continue;
2045 return true;
2046 }
2047 return false;
2048 };
2049
2050 auto IsExpiredFn = [](const MachineInstr &MI, int) {
2051 return SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/true) ||
2052 (MI.getOpcode() == AMDGPU::S_WAITCNT &&
2053 !MI.getOperand(0).getImm()) ||
2054 (MI.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
2056 static_cast<unsigned>(MI.getOperand(0).getImm())) == 0);
2057 };
2058
2059 if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
2060 std::numeric_limits<int>::max())
2061 return false;
2062
2063 const SIInstrInfo *TII = ST.getInstrInfo();
2064 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2065 TII->get(AMDGPU::S_WAITCNT_DEPCTR))
2067 return true;
2068}
2069
2070bool GCNHazardRecognizer::fixSMEMtoVectorWriteHazards(MachineInstr *MI) {
2071 if (!ST.hasSMEMtoVectorWriteHazard())
2072 return false;
2073 assert(!ST.hasExtendedWaitCounts());
2074
2075 if (!SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/false))
2076 return false;
2077
2078 AMDGPU::OpName SDSTName;
2079 switch (MI->getOpcode()) {
2080 case AMDGPU::V_READLANE_B32:
2081 case AMDGPU::V_READFIRSTLANE_B32:
2082 SDSTName = AMDGPU::OpName::vdst;
2083 break;
2084 default:
2085 SDSTName = AMDGPU::OpName::sdst;
2086 break;
2087 }
2088
2089 const SIInstrInfo *TII = ST.getInstrInfo();
2090 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2091 const AMDGPU::IsaVersion IV = AMDGPU::getIsaVersion(ST.getCPU());
2092 const MachineOperand *SDST = TII->getNamedOperand(*MI, SDSTName);
2093 if (!SDST) {
2094 for (const auto &MO : MI->implicit_operands()) {
2095 if (MO.isDef() && TRI->isSGPRClass(TRI->getPhysRegBaseClass(MO.getReg()))) {
2096 SDST = &MO;
2097 break;
2098 }
2099 }
2100 }
2101
2102 if (!SDST)
2103 return false;
2104
2105 const Register SDSTReg = SDST->getReg();
2106 auto IsHazardFn = [SDSTReg, TRI](const MachineInstr &I) {
2107 return SIInstrInfo::isSMRD(I) && I.readsRegister(SDSTReg, TRI);
2108 };
2109
2110 auto IsExpiredFn = [TII, IV](const MachineInstr &MI, int) {
2111 if (TII->isSALU(MI)) {
2112 switch (MI.getOpcode()) {
2113 case AMDGPU::S_SETVSKIP:
2114 case AMDGPU::S_VERSION:
2115 case AMDGPU::S_WAITCNT_VSCNT:
2116 case AMDGPU::S_WAITCNT_VMCNT:
2117 case AMDGPU::S_WAITCNT_EXPCNT:
2118 // These instructions cannot not mitigate the hazard.
2119 return false;
2120 case AMDGPU::S_WAITCNT_LGKMCNT:
2121 // Reducing lgkmcnt count to 0 always mitigates the hazard.
2122 return (MI.getOperand(1).getImm() == 0) &&
2123 (MI.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
2124 case AMDGPU::S_WAITCNT: {
2125 const int64_t Imm = MI.getOperand(0).getImm();
2126 AMDGPU::Waitcnt Decoded =
2127 AMDGPU::decodeWaitcnt(IV, static_cast<unsigned>(Imm));
2128 // DsCnt corresponds to LGKMCnt here.
2129 return Decoded.get(AMDGPU::DS_CNT) == 0;
2130 }
2131 default:
2132 assert((!SIInstrInfo::isWaitcnt(MI.getOpcode()) ||
2133 MI.getOpcode() == AMDGPU::S_WAIT_IDLE) &&
2134 "unexpected wait count instruction");
2135 // SOPP instructions cannot mitigate the hazard.
2136 if (TII->isSOPP(MI))
2137 return false;
2138 // At this point the SALU can be assumed to mitigate the hazard
2139 // because either:
2140 // (a) it is independent of the at risk SMEM (breaking chain),
2141 // or
2142 // (b) it is dependent on the SMEM, in which case an appropriate
2143 // s_waitcnt lgkmcnt _must_ exist between it and the at risk
2144 // SMEM instruction.
2145 return true;
2146 }
2147 }
2148 return false;
2149 };
2150
2151 if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
2152 std::numeric_limits<int>::max())
2153 return false;
2154
2155 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2156 TII->get(AMDGPU::S_MOV_B32), AMDGPU::SGPR_NULL)
2157 .addImm(0);
2158 return true;
2159}
2160
2161bool GCNHazardRecognizer::fixVcmpxExecWARHazard(MachineInstr *MI) {
2162 if (!ST.hasVcmpxExecWARHazard())
2163 return false;
2164 assert(!ST.hasExtendedWaitCounts());
2165
2166 if (!SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/false))
2167 return false;
2168
2169 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2170 if (!MI->modifiesRegister(AMDGPU::EXEC, TRI))
2171 return false;
2172
2173 auto IsHazardFn = [TRI](const MachineInstr &I) {
2174 if (SIInstrInfo::isVALU(I, /*AllowLDSDMA=*/true))
2175 return false;
2176 return I.readsRegister(AMDGPU::EXEC, TRI);
2177 };
2178
2179 const SIInstrInfo *TII = ST.getInstrInfo();
2180 auto IsExpiredFn = [TII, TRI](const MachineInstr &MI, int) {
2181 if (SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false)) {
2182 if (TII->getNamedOperand(MI, AMDGPU::OpName::sdst))
2183 return true;
2184 for (auto MO : MI.implicit_operands())
2185 if (MO.isDef() && TRI->isSGPRClass(TRI->getPhysRegBaseClass(MO.getReg())))
2186 return true;
2187 }
2188 if (MI.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
2190 static_cast<unsigned>(MI.getOperand(0).getImm())) == 0)
2191 return true;
2192 return false;
2193 };
2194
2195 if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
2196 std::numeric_limits<int>::max())
2197 return false;
2198
2199 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2200 TII->get(AMDGPU::S_WAITCNT_DEPCTR))
2202 return true;
2203}
2204
2206 const GCNSubtarget &ST) {
2207 if (!ST.hasLdsBranchVmemWARHazard())
2208 return false;
2209
2210 // Check if the necessary condition for the hazard is met: both LDS and VMEM
2211 // instructions need to appear in the same function.
2212 bool HasLds = false;
2213 bool HasVmem = false;
2214 for (auto &MBB : MF) {
2215 for (auto &MI : MBB) {
2217 HasVmem |= SIInstrInfo::isVMEM(MI);
2218 if (HasLds && HasVmem)
2219 return true;
2220 }
2221 }
2222 return false;
2223}
2224
2226 return I.getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
2227 I.getOperand(0).getReg() == AMDGPU::SGPR_NULL &&
2228 !I.getOperand(1).getImm();
2229}
2230
2231bool GCNHazardRecognizer::fixLdsBranchVmemWARHazard(MachineInstr *MI) {
2232 if (!RunLdsBranchVmemWARHazardFixup)
2233 return false;
2234
2235 assert(ST.hasLdsBranchVmemWARHazard());
2236 assert(!ST.hasExtendedWaitCounts());
2237
2238 auto IsHazardInst = [](const MachineInstr &MI) {
2240 return 1;
2242 return 2;
2243 return 0;
2244 };
2245
2246 auto InstType = IsHazardInst(*MI);
2247 if (!InstType)
2248 return false;
2249
2250 auto IsExpiredFn = [&IsHazardInst](const MachineInstr &I, int) {
2251 return IsHazardInst(I) || isStoreCountWaitZero(I);
2252 };
2253
2254 auto IsHazardFn = [InstType, &IsHazardInst](const MachineInstr &I) {
2255 if (!I.isBranch())
2256 return false;
2257
2258 auto IsHazardFn = [InstType, IsHazardInst](const MachineInstr &I) {
2259 auto InstType2 = IsHazardInst(I);
2260 return InstType2 && InstType != InstType2;
2261 };
2262
2263 auto IsExpiredFn = [InstType, &IsHazardInst](const MachineInstr &I, int) {
2264 auto InstType2 = IsHazardInst(I);
2265 if (InstType == InstType2)
2266 return true;
2267
2268 return isStoreCountWaitZero(I);
2269 };
2270
2271 return ::getWaitStatesSince(IsHazardFn, &I, IsExpiredFn) !=
2272 std::numeric_limits<int>::max();
2273 };
2274
2275 if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
2276 std::numeric_limits<int>::max())
2277 return false;
2278
2279 const SIInstrInfo *TII = ST.getInstrInfo();
2280 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2281 TII->get(AMDGPU::S_WAITCNT_VSCNT))
2282 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
2283 .addImm(0);
2284
2285 return true;
2286}
2287
2288bool GCNHazardRecognizer::fixLdsDirectVALUHazard(MachineInstr *MI) {
2290 return false;
2291
2292 const int NoHazardWaitStates = 15;
2293 const MachineOperand *VDST = TII.getNamedOperand(*MI, AMDGPU::OpName::vdst);
2294 const Register VDSTReg = VDST->getReg();
2295
2296 bool VisitedTrans = false;
2297 auto IsHazardFn = [this, VDSTReg, &VisitedTrans](const MachineInstr &I) {
2298 if (!SIInstrInfo::isVALU(I, /*AllowLDSDMA=*/true))
2299 return false;
2300 VisitedTrans = VisitedTrans || SIInstrInfo::isTRANS(I);
2301 // Cover both WAR and WAW
2302 return I.readsRegister(VDSTReg, &TRI) || I.modifiesRegister(VDSTReg, &TRI);
2303 };
2304 auto IsExpiredFn = [&](const MachineInstr &I, int WaitStates) {
2305 if (WaitStates >= NoHazardWaitStates)
2306 return true;
2307 // Instructions which cause va_vdst==0 expire hazard
2310 };
2311 auto GetWaitStatesFn = [](const MachineInstr &MI) {
2312 return SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/true) ? 1 : 0;
2313 };
2314
2315 DenseSet<const MachineBasicBlock *> Visited;
2316 auto Count = ::getWaitStatesSince(IsHazardFn, MI->getParent(),
2317 std::next(MI->getReverseIterator()), 0,
2318 IsExpiredFn, Visited, GetWaitStatesFn);
2319
2320 // Transcendentals can execute in parallel to other VALUs.
2321 // This makes va_vdst count unusable with a mixture of VALU and TRANS.
2322 if (VisitedTrans)
2323 Count = 0;
2324
2325 MachineOperand *WaitVdstOp =
2326 TII.getNamedOperand(*MI, AMDGPU::OpName::waitvdst);
2327 WaitVdstOp->setImm(std::min(Count, NoHazardWaitStates));
2328
2329 return true;
2330}
2331
2332bool GCNHazardRecognizer::fixLdsDirectVMEMHazard(MachineInstr *MI) {
2334 return false;
2335
2336 const MachineOperand *VDST = TII.getNamedOperand(*MI, AMDGPU::OpName::vdst);
2337 const Register VDSTReg = VDST->getReg();
2338
2339 auto IsHazardFn = [this, VDSTReg](const MachineInstr &I) {
2341 return false;
2342 return I.readsRegister(VDSTReg, &TRI) || I.modifiesRegister(VDSTReg, &TRI);
2343 };
2344 bool LdsdirCanWait = ST.hasLdsWaitVMSRC();
2345 // TODO: On GFX12 the hazard should expire on S_WAIT_LOADCNT/SAMPLECNT/BVHCNT
2346 // according to the type of VMEM instruction.
2347 auto IsExpiredFn = [this, LdsdirCanWait](const MachineInstr &I, int) {
2348 return SIInstrInfo::isVALU(I, /*AllowLDSDMA=*/true) ||
2350 (I.getOpcode() == AMDGPU::S_WAITCNT && !I.getOperand(0).getImm()) ||
2351 (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
2353 static_cast<unsigned>(I.getOperand(0).getImm())) == 0) ||
2354 (LdsdirCanWait && SIInstrInfo::isLDSDIR(I) &&
2355 !TII.getNamedOperand(I, AMDGPU::OpName::waitvsrc)->getImm());
2356 };
2357
2358 if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
2359 std::numeric_limits<int>::max())
2360 return false;
2361
2362 if (LdsdirCanWait) {
2363 TII.getNamedOperand(*MI, AMDGPU::OpName::waitvsrc)->setImm(0);
2364 } else {
2365 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2366 TII.get(AMDGPU::S_WAITCNT_DEPCTR))
2368 }
2369
2370 return true;
2371}
2372
2373bool GCNHazardRecognizer::fixVALUPartialForwardingHazard(MachineInstr *MI) {
2374 if (!ST.hasVALUPartialForwardingHazard())
2375 return false;
2376 assert(!ST.hasExtendedWaitCounts());
2377
2378 if (!ST.isWave64() || !SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/false))
2379 return false;
2380
2381 SmallSetVector<Register, 4> SrcVGPRs;
2382
2383 for (const MachineOperand &Use : MI->explicit_uses()) {
2384 if (Use.isReg() && TRI.isVGPR(MF.getRegInfo(), Use.getReg()))
2385 SrcVGPRs.insert(Use.getReg());
2386 }
2387
2388 // Only applies with >= 2 unique VGPR sources
2389 if (SrcVGPRs.size() <= 1)
2390 return false;
2391
2392 // Look for the following pattern:
2393 // Va <- VALU [PreExecPos]
2394 // intv1
2395 // Exec <- SALU [ExecPos]
2396 // intv2
2397 // Vb <- VALU [PostExecPos]
2398 // intv3
2399 // MI Va, Vb (WaitState = 0)
2400 //
2401 // Where:
2402 // intv1 + intv2 <= 2 VALUs
2403 // intv3 <= 4 VALUs
2404 //
2405 // If found, insert an appropriate S_WAITCNT_DEPCTR before MI.
2406
2407 const int Intv1plus2MaxVALUs = 2;
2408 const int Intv3MaxVALUs = 4;
2409 const int IntvMaxVALUs = 6;
2410 const int NoHazardVALUWaitStates = IntvMaxVALUs + 2;
2411
2412 struct StateType {
2413 SmallDenseMap<Register, int, 4> DefPos;
2414 int ExecPos = std::numeric_limits<int>::max();
2415 int VALUs = 0;
2416
2417 static unsigned getHashValue(const StateType &State) {
2418 hash_code H = hash_combine(State.ExecPos, State.VALUs);
2419 for (const auto &[Reg, Pos] : State.DefPos)
2420 H = hash_combine(H, Reg, Pos);
2421 return static_cast<unsigned>(H);
2422 }
2423 static bool isEqual(const StateType &LHS, const StateType &RHS) {
2424 return LHS.DefPos == RHS.DefPos && LHS.ExecPos == RHS.ExecPos &&
2425 LHS.VALUs == RHS.VALUs;
2426 }
2427 };
2428
2429 StateType State;
2430
2431 // This overloads expiry testing with all the hazard detection
2432 auto IsHazardFn = [&, this](StateType &State, const MachineInstr &I) {
2433 // Too many VALU states have passed
2434 if (State.VALUs > NoHazardVALUWaitStates)
2435 return HazardExpired;
2436
2437 // Instructions which cause va_vdst==0 expire hazard
2440 (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
2442 static_cast<unsigned>(I.getOperand(0).getImm())) == 0))
2443 return HazardExpired;
2444
2445 // Track registers writes
2446 bool Changed = false;
2447 if (SIInstrInfo::isVALU(I, /*AllowLDSDMA=*/false)) {
2448 for (Register Src : SrcVGPRs) {
2449 if (!State.DefPos.count(Src) && I.modifiesRegister(Src, &TRI)) {
2450 State.DefPos[Src] = State.VALUs;
2451 Changed = true;
2452 }
2453 }
2454 } else if (SIInstrInfo::isSALU(I)) {
2455 if (State.ExecPos == std::numeric_limits<int>::max()) {
2456 if (!State.DefPos.empty() && I.modifiesRegister(AMDGPU::EXEC, &TRI)) {
2457 State.ExecPos = State.VALUs;
2458 Changed = true;
2459 }
2460 }
2461 }
2462
2463 // Early expiration: too many VALUs in intv3
2464 if (State.VALUs > Intv3MaxVALUs && State.DefPos.empty())
2465 return HazardExpired;
2466
2467 // Only evaluate state if something changed
2468 if (!Changed)
2469 return NoHazardFound;
2470
2471 // Determine positions of VALUs pre/post exec change
2472 if (State.ExecPos == std::numeric_limits<int>::max())
2473 return NoHazardFound;
2474
2475 int PreExecPos = std::numeric_limits<int>::max();
2476 int PostExecPos = std::numeric_limits<int>::max();
2477
2478 for (auto Entry : State.DefPos) {
2479 int DefVALUs = Entry.second;
2480 if (DefVALUs != std::numeric_limits<int>::max()) {
2481 if (DefVALUs >= State.ExecPos)
2482 PreExecPos = std::min(PreExecPos, DefVALUs);
2483 else
2484 PostExecPos = std::min(PostExecPos, DefVALUs);
2485 }
2486 }
2487
2488 // Need a VALUs post exec change
2489 if (PostExecPos == std::numeric_limits<int>::max())
2490 return NoHazardFound;
2491
2492 // Too many VALUs in intv3?
2493 int Intv3VALUs = PostExecPos;
2494 if (Intv3VALUs > Intv3MaxVALUs)
2495 return HazardExpired;
2496
2497 // Too many VALUs in intv2?
2498 int Intv2VALUs = (State.ExecPos - PostExecPos) - 1;
2499 if (Intv2VALUs > Intv1plus2MaxVALUs)
2500 return HazardExpired;
2501
2502 // Need a VALUs pre exec change
2503 if (PreExecPos == std::numeric_limits<int>::max())
2504 return NoHazardFound;
2505
2506 // Too many VALUs in intv1?
2507 int Intv1VALUs = PreExecPos - State.ExecPos;
2508 if (Intv1VALUs > Intv1plus2MaxVALUs)
2509 return HazardExpired;
2510
2511 // Too many VALUs in intv1 + intv2
2512 if (Intv1VALUs + Intv2VALUs > Intv1plus2MaxVALUs)
2513 return HazardExpired;
2514
2515 return HazardFound;
2516 };
2517 auto UpdateStateFn = [](StateType &State, const MachineInstr &MI) {
2518 if (SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false))
2519 State.VALUs += 1;
2520 };
2521
2522 if (!hasHazard<StateType>(State, IsHazardFn, UpdateStateFn, MI->getParent(),
2523 std::next(MI->getReverseIterator())))
2524 return false;
2525
2526 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2527 TII.get(AMDGPU::S_WAITCNT_DEPCTR))
2529
2530 return true;
2531}
2532
2533bool GCNHazardRecognizer::fixVALUTransUseHazard(MachineInstr *MI) {
2534 if (!ST.hasVALUTransUseHazard())
2535 return false;
2536 assert(!ST.hasExtendedWaitCounts());
2537
2538 if (!SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/false))
2539 return false;
2540
2541 SmallSet<Register, 4> SrcVGPRs;
2542
2543 for (const MachineOperand &Use : MI->explicit_uses()) {
2544 if (Use.isReg() && TRI.isVGPR(MF.getRegInfo(), Use.getReg()))
2545 SrcVGPRs.insert(Use.getReg());
2546 }
2547
2548 // Look for the following pattern:
2549 // Va <- TRANS VALU
2550 // intv
2551 // MI Va (WaitState = 0)
2552 //
2553 // Where:
2554 // intv <= 5 VALUs / 1 TRANS
2555 //
2556 // If found, insert an appropriate S_WAITCNT_DEPCTR before MI.
2557
2558 const int IntvMaxVALUs = 5;
2559 const int IntvMaxTRANS = 1;
2560
2561 struct StateType {
2562 int VALUs = 0;
2563 int TRANS = 0;
2564
2565 static unsigned getHashValue(const StateType &State) {
2566 return static_cast<unsigned>(hash_combine(State.VALUs, State.TRANS));
2567 }
2568 static bool isEqual(const StateType &LHS, const StateType &RHS) {
2569 return LHS.VALUs == RHS.VALUs && LHS.TRANS == RHS.TRANS;
2570 }
2571 };
2572
2573 StateType State;
2574
2575 // This overloads expiry testing with all the hazard detection
2576 auto IsHazardFn = [&, this](StateType &State, const MachineInstr &I) {
2577 // Too many VALU states have passed
2578 if (State.VALUs > IntvMaxVALUs || State.TRANS > IntvMaxTRANS)
2579 return HazardExpired;
2580
2581 // Instructions which cause va_vdst==0 expire hazard
2584 (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
2586 static_cast<unsigned>(I.getOperand(0).getImm())) == 0))
2587 return HazardExpired;
2588
2589 // Track registers writes
2590 if (SIInstrInfo::isTRANS(I)) {
2591 for (Register Src : SrcVGPRs) {
2592 if (I.modifiesRegister(Src, &TRI)) {
2593 return HazardFound;
2594 }
2595 }
2596 }
2597
2598 return NoHazardFound;
2599 };
2600 auto UpdateStateFn = [](StateType &State, const MachineInstr &MI) {
2601 if (SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false))
2602 State.VALUs += 1;
2604 State.TRANS += 1;
2605 };
2606
2607 if (!hasHazard<StateType>(State, IsHazardFn, UpdateStateFn, MI->getParent(),
2608 std::next(MI->getReverseIterator())))
2609 return false;
2610
2611 // Hazard is observed - insert a wait on va_dst counter to ensure hazard is
2612 // avoided.
2613 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2614 TII.get(AMDGPU::S_WAITCNT_DEPCTR))
2616
2617 return true;
2618}
2619
2620bool GCNHazardRecognizer::fixVALUTransCoexecutionHazards(MachineInstr *MI) {
2621 if (!ST.hasTransCoexecutionHazard() || // Coexecution disabled.
2622 !SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/true) ||
2624 return false;
2625
2626 const SIInstrInfo *TII = ST.getInstrInfo();
2627 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2628
2629 auto IsTransHazardFn = [MI, TII, TRI](const MachineInstr &I) {
2630 if (!SIInstrInfo::isTRANS(I))
2631 return false;
2632
2633 // RAW: Trans(I) writes, VALU(MI) reads.
2634 Register TransDef = TII->getNamedOperand(I, AMDGPU::OpName::vdst)->getReg();
2635 for (const MachineOperand &ValuUse : MI->explicit_uses()) {
2636 if (ValuUse.isReg() && TRI->regsOverlap(TransDef, ValuUse.getReg()))
2637 return true;
2638 }
2639
2640 // WAR: Trans(I) reads, VALU(MI) writes. Use modifiesRegister for
2641 // multi-dest VALUs.
2642 for (const MachineOperand &TransUse : I.explicit_uses()) {
2643 if (TransUse.isReg() && MI->modifiesRegister(TransUse.getReg(), TRI))
2644 return true;
2645 }
2646
2647 return false;
2648 };
2649
2650 auto IsExpiredFn = [](const MachineInstr &I, int) {
2651 return SIInstrInfo::isVALU(I, /*AllowLDSDMA=*/true);
2652 };
2653
2654 const int HasVALU = std::numeric_limits<int>::max();
2655 if (::getWaitStatesSince(IsTransHazardFn, MI, IsExpiredFn) == HasVALU)
2656 return false;
2657
2658 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(AMDGPU::V_NOP_e32));
2659 return true;
2660}
2661
2662bool GCNHazardRecognizer::fixWMMAHazards(MachineInstr *MI) {
2664 return false;
2665
2666 const SIInstrInfo *TII = ST.getInstrInfo();
2667 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2668
2669 auto IsHazardFn = [MI, TII, TRI, this](const MachineInstr &I) {
2671 return false;
2672
2673 // Src0(matrix A) or Src1(matrix B) of the current wmma instruction overlaps
2674 // with the dest(matrix D) of the previous wmma.
2675 const Register CurSrc0Reg =
2676 TII->getNamedOperand(*MI, AMDGPU::OpName::src0)->getReg();
2677 const Register CurSrc1Reg =
2678 TII->getNamedOperand(*MI, AMDGPU::OpName::src1)->getReg();
2679
2680 const Register PrevDstReg =
2681 TII->getNamedOperand(I, AMDGPU::OpName::vdst)->getReg();
2682
2683 if (TRI->regsOverlap(PrevDstReg, CurSrc0Reg) ||
2684 TRI->regsOverlap(PrevDstReg, CurSrc1Reg)) {
2685 return true;
2686 }
2687
2688 // GFX12+ allows overlap of matrix C with PrevDstReg (hardware will stall)
2689 // but Index can't overlap with PrevDstReg.
2690 if (AMDGPU::isGFX12Plus(ST)) {
2691 if (SIInstrInfo::isSWMMAC(*MI)) {
2692 const Register CurIndex =
2693 TII->getNamedOperand(*MI, AMDGPU::OpName::src2)->getReg();
2694 if (TRI->regsOverlap(PrevDstReg, CurIndex))
2695 return true;
2696 }
2697 return false;
2698 }
2699
2700 return false;
2701 };
2702
2703 auto IsExpiredFn = [](const MachineInstr &I, int) {
2704 return SIInstrInfo::isVALU(I, /*AllowLDSDMA=*/true);
2705 };
2706
2707 if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
2708 std::numeric_limits<int>::max())
2709 return false;
2710
2711 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(AMDGPU::V_NOP_e32));
2712
2713 return true;
2714}
2715
2717 return SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false) &&
2719}
2720
2721// Classify XDL WMMA instructions into co-execution hazard categories
2722// (Refer to SPG 4.6.12.1), mainly based on instruction latency.
2723//
2724// Category 0: WMMA with Latency 8
2725// WMMA_*F16, WMMA_*BF16
2726// WMMA_*_16X16X128_{FP8,BF8}
2727// WMMA_*F8F6F4 if SRCA & SRCB are not both F4
2728//
2729// Category 1: WMMA Latency 16
2730// WMMA_IU8
2731//
2732// Category 2: SWMMAC with Latency 8
2733// SWMMAC_*F16, SWMMAC_*BF16,
2734// SWMMAC_*FP8FP8
2735// SWMMAC_*BF8FP8
2736// SWMMAC_*FP8BF8
2737// SWMMAC_*BF8BF8
2738//
2739// Category 3: SWMMAC with Latency 16
2740// SWMMAC_IU8
2741//
2742// Category 4: 16 Pass GFX1251 WMMA with latency 16
2743// V_WMMA_*_16X16X32_{F16,BF16}
2744// V_WMMA_{F32,F16}_16X16X64_{FP8,BF8}*
2745// V_WMMA_F32_16x16x128_F8F6F4 (F4 only)
2746// V_SWMMAC_*_16X16X64_{F16,BF16}
2747// V_SWMMAC_{F32,F16}_16X16X128_{FP8,BF8}*
2748//
2749// Category 5: 32 Pass GFX1251 WMMA with latency 32
2750// V_WMMA_F32_16x16x128_F8F6F4 (not all F4)
2751// V_WMMA_{F32,F16}_16X16X128_{FP8,BF8}*
2752// V_WMMA_F32_32X16X128_F4
2753// V_WMMA_I32_16X16X64_IU8
2754// V_WMMA_I32_16X16X64_IU8
2755//
2756// Category 6: gfx1250 WMMA with Latency 4 (one co-execution slot)
2757// WMMA_*_16X16X64_{FP8,BF8}
2758// WMMA_*F8F6F4 if SRCA & SRCB are both F4
2760 const SIInstrInfo *TII,
2761 const TargetSchedModel &SchedModel,
2762 const GCNSubtarget &ST) {
2763 assert(TII->isXDLWMMA(MI) && "must be xdl wmma");
2764 bool IsSWMMAC = SIInstrInfo::isSWMMAC(MI);
2765 bool IsLowestRateWMMA = ST.hasGFX125xLowestRateWMMA();
2766 unsigned Category = 0;
2767
2768 unsigned Latency = SchedModel.computeInstrLatency(&MI);
2769 switch (Latency) {
2770 case 4:
2771 // Dense 4-cycle WMMA (gfx1250 16x16x64 FP8/BF8 and f8f6f4 with both
2772 // inputs F4). One co-execution slot; there is no 4-cycle SWMMAC.
2773 assert(!IsSWMMAC && "no 4-cycle SWMMAC expected");
2774 Category = 6;
2775 break;
2776 case 8:
2777 Category = IsSWMMAC ? 2 : 0;
2778 break;
2779 case 16:
2780 Category = IsLowestRateWMMA ? 4 : (IsSWMMAC ? 3 : 1);
2781 break;
2782 case 32:
2783 assert(IsLowestRateWMMA && "latency 32 is not expected");
2784 Category = 5;
2785 break;
2786 default:
2787 llvm_unreachable("unexpected xdl wmma latency");
2788 } // end switch.
2789
2790 return Category;
2791}
2792
2793unsigned
2795 return ST.hasGFX125xLowestRateWMMA() ? 17 : 9;
2796}
2797
2798int GCNHazardRecognizer::checkWMMACoexecutionHazards(MachineInstr *MI) const {
2799 if (!ST.hasWMMACoexecutionHazards())
2800 return 0;
2801
2802 const SIInstrInfo *TII = ST.getInstrInfo();
2803 if (!TII->isXDLWMMA(*MI) && !isCoexecutableVALUInst(*MI))
2804 return 0;
2805
2806 // WaitStates here is the number of V_NOPs or unrelated VALU instructions must
2807 // be in between the first WMMA and the second instruction to cover the hazard
2808 // (WMMAWaitStates if the second is also a WMMA, VALUWaitStates if the second
2809 // is a VALU). Refer to SPG 4.6.12.1. "Requirements for WMMA data hazards" for
2810 // numbers, which depends on the category of the first WMMA.
2811 const int WMMAWaitStates[] = {5, 9, 3, 5, 9, 17, 2};
2812 const int VALUWaitStates[] = {4, 8, 2, 4, 8, 16, 1};
2813 const bool IsWMMA = TII->isXDLWMMA(*MI);
2814 const bool IsLowestRateWMMA = ST.hasGFX125xLowestRateWMMA();
2815 ArrayRef<int> RequiredWaitStates =
2816 IsWMMA ? ArrayRef<int>(WMMAWaitStates) : ArrayRef<int>(VALUWaitStates);
2817 const int MaxWaitStates = IsWMMA ? getMaxWMMACoexecutionWaitStates(ST)
2818 : (IsLowestRateWMMA ? 16 : 8);
2819
2820 auto WindowFor = [=](const MachineInstr &I) -> std::optional<int> {
2821 if (!TII->isXDLWMMA(I))
2822 return std::nullopt;
2823 if (IsWMMA ? !hasWMMAToWMMARegOverlap(I, *MI)
2824 : !hasWMMAToVALURegOverlap(I, *MI))
2825 return std::nullopt;
2826 return RequiredWaitStates[getWMMAHazardInstInCategory(I, TII, TSchedModel,
2827 ST)];
2828 };
2829
2830 return getMaxVALUWindowDeficit(MaxWaitStates, WindowFor);
2831}
2832
2833bool GCNHazardRecognizer::hasWMMAToWMMARegOverlap(
2834 const MachineInstr &WMMA, const MachineInstr &MI) const {
2835 Register D0 = TII.getNamedOperand(WMMA, AMDGPU::OpName::vdst)->getReg();
2836 Register A1 = TII.getNamedOperand(MI, AMDGPU::OpName::src0)->getReg();
2837 Register B1 = TII.getNamedOperand(MI, AMDGPU::OpName::src1)->getReg();
2838
2839 // WMMA0 writes (D0), WMMA1 reads (A1/B1/Idx1).
2840 if (TRI.regsOverlap(D0, A1) || TRI.regsOverlap(D0, B1))
2841 return true;
2842
2844 Register Idx1 = TII.getNamedOperand(MI, AMDGPU::OpName::src2)->getReg();
2845 if (TRI.regsOverlap(D0, Idx1))
2846 return true;
2847 }
2848 return false;
2849}
2850
2851bool GCNHazardRecognizer::hasWMMAToVALURegOverlap(
2852 const MachineInstr &WMMA, const MachineInstr &MI) const {
2853 // WMMA writes, VALU reads.
2854 Register D0 = TII.getNamedOperand(WMMA, AMDGPU::OpName::vdst)->getReg();
2855 for (const MachineOperand &ValuUse : MI.explicit_uses()) {
2856 if (ValuUse.isReg() && TRI.regsOverlap(D0, ValuUse.getReg()))
2857 return true;
2858 }
2859
2860 // WMMA reads or writes, VALU writes.
2861 Register A0 = TII.getNamedOperand(WMMA, AMDGPU::OpName::src0)->getReg();
2862 Register B0 = TII.getNamedOperand(WMMA, AMDGPU::OpName::src1)->getReg();
2863 SmallVector<Register, 4> WMMARegs({D0, A0, B0});
2864
2865 const MachineOperand *Src2 = TII.getNamedOperand(WMMA, AMDGPU::OpName::src2);
2866 if (Src2->isReg())
2867 WMMARegs.push_back(Src2->getReg());
2868
2869 for (const MachineOperand &ValuDef : MI.defs()) {
2870 Register VDstReg = ValuDef.getReg();
2871 for (Register WMMAReg : WMMARegs) {
2872 if (TRI.regsOverlap(VDstReg, WMMAReg))
2873 return true;
2874 }
2875 }
2876 return false;
2877}
2878
2879bool GCNHazardRecognizer::isCoexecutionHazardFor(const MachineInstr &I,
2880 const MachineInstr &MI) const {
2881 // I is the potential WMMA hazard source, MI is the instruction being checked
2882 // for hazard.
2883 if (!TII.isXDLWMMA(I))
2884 return false;
2885
2886 // Dispatch based on MI type
2887 if (TII.isXDLWMMA(MI))
2888 return hasWMMAToWMMARegOverlap(I, MI);
2890 return hasWMMAToVALURegOverlap(I, MI);
2891
2892 return false;
2893}
2894
2895bool GCNHazardRecognizer::hasWMMAHazardInLoop(MachineLoop *L, MachineInstr *MI,
2896 bool IncludeSubloops) {
2897 // Scan loop for any WMMA that hazards MI.
2898 // TODO: Avoid full loop scan when WMMA is beyond VALU distance.
2899 for (MachineBasicBlock *MBB : L->getBlocks()) {
2900 if (!IncludeSubloops && MLI->getLoopFor(MBB) != L)
2901 continue;
2902 for (MachineInstr &I : *MBB) {
2903 if (&I == MI)
2904 continue;
2905 if (isCoexecutionHazardFor(I, *MI))
2906 return true;
2907 }
2908 }
2909 return false;
2910}
2911
2912bool GCNHazardRecognizer::tryHoistWMMAVnopsFromLoop(MachineInstr *MI,
2913 int WaitStatesNeeded) {
2914 if (!MLI)
2915 return false;
2916
2917 MachineLoop *L = MLI->getLoopFor(MI->getParent());
2918 if (!L) {
2919 ++NumWMMAHoistingBailed;
2920 return false;
2921 }
2922
2923 // If innermost loop has WMMA hazard, we can't hoist at all
2924 if (hasWMMAHazardInLoop(L, MI)) {
2925 ++NumWMMAHoistingBailed;
2926 return false;
2927 }
2928
2929 // Find outermost loop with no internal hazard
2930 MachineLoop *TargetLoop = L;
2931 while (MachineLoop *Parent = TargetLoop->getParentLoop()) {
2932 if (hasWMMAHazardInLoop(Parent, MI, false))
2933 break; // Parent has hazard in its own blocks, stop here
2934 TargetLoop = Parent; // Safe to hoist further out
2935 }
2936
2937 // Need valid preheader to insert V_NOPs
2938 MachineBasicBlock *Preheader = TargetLoop->getLoopPreheader();
2939 if (!Preheader) {
2940 ++NumWMMAHoistingBailed;
2941 return false;
2942 }
2943
2944 LLVM_DEBUG(dbgs() << "WMMA V_NOP Hoisting: Moving " << WaitStatesNeeded
2945 << " V_NOPs from loop to " << printMBBReference(*Preheader)
2946 << "\n");
2947
2948 emitVNops(*Preheader, Preheader->getFirstTerminator(), WaitStatesNeeded,
2949 /*IsHoisting=*/true);
2950 NumWMMANopsHoisted += WaitStatesNeeded;
2951 return true;
2952}
2953
2954bool GCNHazardRecognizer::fixWMMACoexecutionHazards(MachineInstr *MI) {
2955 int WaitStatesNeeded = checkWMMACoexecutionHazards(MI);
2956 if (WaitStatesNeeded <= 0)
2957 return false;
2958
2959 if (ST.getCLOpts().wmma_vnop_hoisting &&
2960 tryHoistWMMAVnopsFromLoop(MI, WaitStatesNeeded))
2961 return true;
2962
2963 emitVNops(*MI->getParent(), MI->getIterator(), WaitStatesNeeded);
2964 return true;
2965}
2966
2967bool GCNHazardRecognizer::fixShift64HighRegBug(MachineInstr *MI) {
2968 if (!ST.hasShift64HighRegBug())
2969 return false;
2970 assert(!ST.hasExtendedWaitCounts());
2971
2972 switch (MI->getOpcode()) {
2973 default:
2974 return false;
2975 case AMDGPU::V_LSHLREV_B64_e64:
2976 case AMDGPU::V_LSHRREV_B64_e64:
2977 case AMDGPU::V_ASHRREV_I64_e64:
2978 break;
2979 }
2980
2981 MachineOperand *Amt = TII.getNamedOperand(*MI, AMDGPU::OpName::src0);
2982 if (!Amt->isReg())
2983 return false;
2984
2985 Register AmtReg = Amt->getReg();
2986 const MachineRegisterInfo &MRI = MF.getRegInfo();
2987 // Check if this is a last VGPR in the allocation block.
2988 if (!TRI.isVGPR(MRI, AmtReg) || ((AmtReg - AMDGPU::VGPR0) & 7) != 7)
2989 return false;
2990
2991 if (AmtReg != AMDGPU::VGPR255 && MRI.isPhysRegUsed(AmtReg + 1))
2992 return false;
2993
2994 assert(ST.needsAlignedVGPRs());
2995 static_assert(AMDGPU::VGPR0 + 1 == AMDGPU::VGPR1);
2996
2997 const DebugLoc &DL = MI->getDebugLoc();
2998 MachineBasicBlock *MBB = MI->getParent();
2999 MachineOperand *Src1 = TII.getNamedOperand(*MI, AMDGPU::OpName::src1);
3000
3001 // In:
3002 //
3003 // Dst = shiftrev64 Amt, Src1
3004 //
3005 // if Dst!=Src1 then avoid the bug with:
3006 //
3007 // Dst.sub0 = Amt
3008 // Dst = shift64 Dst.sub0, Src1
3009
3010 Register DstReg = MI->getOperand(0).getReg();
3011 if (!Src1->isReg() || Src1->getReg() != DstReg) {
3012 Register DstLo = TRI.getSubReg(DstReg, AMDGPU::sub0);
3013 runOnInstruction(
3014 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_MOV_B32_e32), DstLo).add(*Amt));
3015 Amt->setReg(DstLo);
3016 Amt->setIsKill(true);
3017 return true;
3018 }
3019
3020 bool Overlapped = MI->modifiesRegister(AmtReg, &TRI);
3021 Register NewReg;
3022 for (MCRegister Reg : Overlapped ? AMDGPU::VReg_64_Align2RegClass
3023 : AMDGPU::VGPR_32RegClass) {
3024 if (!MI->modifiesRegister(Reg, &TRI) && !MI->readsRegister(Reg, &TRI)) {
3025 NewReg = Reg;
3026 break;
3027 }
3028 }
3029
3030 Register NewAmt = Overlapped ? (Register)TRI.getSubReg(NewReg, AMDGPU::sub1)
3031 : NewReg;
3032 Register NewAmtLo;
3033
3034 if (Overlapped)
3035 NewAmtLo = TRI.getSubReg(NewReg, AMDGPU::sub0);
3036
3037 // Insert a full wait count because found register might be pending a wait.
3038 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_WAITCNT))
3039 .addImm(0);
3040
3041 // Insert V_SWAP_B32 instruction(s) and run hazard recognizer on them.
3042 if (Overlapped)
3043 runOnInstruction(
3044 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_SWAP_B32), NewAmtLo)
3045 .addDef(AmtReg - 1)
3046 .addReg(AmtReg - 1, RegState::Undef)
3047 .addReg(NewAmtLo, RegState::Undef));
3048 runOnInstruction(BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_SWAP_B32), NewAmt)
3049 .addDef(AmtReg)
3050 .addReg(AmtReg, RegState::Undef)
3051 .addReg(NewAmt, RegState::Undef));
3052
3053 // Instructions emitted after the current instruction will be processed by the
3054 // parent loop of the hazard recognizer in a natural way.
3055 BuildMI(*MBB, std::next(MI->getIterator()), DL, TII.get(AMDGPU::V_SWAP_B32),
3056 AmtReg)
3057 .addDef(NewAmt)
3058 .addReg(NewAmt)
3059 .addReg(AmtReg);
3060 if (Overlapped)
3061 BuildMI(*MBB, std::next(MI->getIterator()), DL, TII.get(AMDGPU::V_SWAP_B32),
3062 AmtReg - 1)
3063 .addDef(NewAmtLo)
3064 .addReg(NewAmtLo)
3065 .addReg(AmtReg - 1);
3066
3067 // Re-running hazard recognizer on the modified instruction is not necessary,
3068 // inserted V_SWAP_B32 has already both read and write new registers so
3069 // hazards related to these register has already been handled.
3070 Amt->setReg(NewAmt);
3071 Amt->setIsKill(false);
3072 // We do not update liveness, so verifier may see it as undef.
3073 Amt->setIsUndef();
3074 if (Overlapped) {
3075 MI->getOperand(0).setReg(NewReg);
3076 Src1->setReg(NewReg);
3077 Src1->setIsKill(false);
3078 Src1->setIsUndef();
3079 }
3080
3081 return true;
3082}
3083
3084int GCNHazardRecognizer::checkNSAtoVMEMHazard(MachineInstr *MI) const {
3085 int NSAtoVMEMWaitStates = 1;
3086
3087 if (!ST.hasNSAtoVMEMBug())
3088 return 0;
3089
3091 return 0;
3092
3093 const SIInstrInfo *TII = ST.getInstrInfo();
3094 const auto *Offset = TII->getNamedOperand(*MI, AMDGPU::OpName::offset);
3095 if (!Offset || (Offset->getImm() & 6) == 0)
3096 return 0;
3097
3098 auto IsHazardFn = [TII](const MachineInstr &I) {
3099 if (!SIInstrInfo::isMIMG(I))
3100 return false;
3101 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(I.getOpcode());
3102 return Info->MIMGEncoding == AMDGPU::MIMGEncGfx10NSA &&
3103 TII->getInstSizeInBytes(I) >= 16;
3104 };
3105
3106 return NSAtoVMEMWaitStates - getWaitStatesSince(IsHazardFn, 1);
3107}
3108
3109int GCNHazardRecognizer::checkFPAtomicToDenormModeHazard(
3110 MachineInstr *MI) const {
3111 int FPAtomicToDenormModeWaitStates = 3;
3112
3113 if (!ST.hasFPAtomicToDenormModeHazard())
3114 return 0;
3115 assert(!ST.hasExtendedWaitCounts());
3116
3117 if (MI->getOpcode() != AMDGPU::S_DENORM_MODE)
3118 return 0;
3119
3120 auto IsHazardFn = [](const MachineInstr &I) {
3121 if (!SIInstrInfo::isVMEM(I))
3122 return false;
3123 return SIInstrInfo::isFPAtomic(I);
3124 };
3125
3126 auto IsExpiredFn = [](const MachineInstr &MI, int WaitStates) {
3127 if (WaitStates >= 3 || SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/true))
3128 return true;
3129
3130 return SIInstrInfo::isWaitcnt(MI.getOpcode());
3131 };
3132
3133 return FPAtomicToDenormModeWaitStates -
3134 ::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn);
3135}
3136
3137int GCNHazardRecognizer::checkMAIHazards(MachineInstr *MI) const {
3139
3140 return ST.hasGFX90AInsts() ? checkMAIHazards90A(MI) : checkMAIHazards908(MI);
3141}
3142
3143int GCNHazardRecognizer::checkMFMAPadding(MachineInstr *MI) const {
3144 // Early exit if no padding is requested.
3145 if (MFMAPaddingRatio == 0)
3146 return 0;
3147
3148 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3149 if (!SIInstrInfo::isMFMA(*MI) || MFI->getOccupancy() < 2)
3150 return 0;
3151
3152 int NeighborMFMALatency = 0;
3153 auto IsNeighboringMFMA = [&NeighborMFMALatency,
3154 this](const MachineInstr &MI) {
3155 if (!SIInstrInfo::isMFMA(MI))
3156 return false;
3157
3158 NeighborMFMALatency = this->getMFMAPipelineWaitStates(MI);
3159 return true;
3160 };
3161
3162 const int MaxMFMAPipelineWaitStates = 16;
3163 int WaitStatesSinceNeighborMFMA =
3164 getWaitStatesSince(IsNeighboringMFMA, MaxMFMAPipelineWaitStates);
3165
3166 int NeighborMFMAPaddingNeeded =
3167 (NeighborMFMALatency * MFMAPaddingRatio / 100) -
3168 WaitStatesSinceNeighborMFMA;
3169
3170 return std::max(0, NeighborMFMAPaddingNeeded);
3171}
3172
3173int GCNHazardRecognizer::checkMAIHazards908(MachineInstr *MI) const {
3174 int WaitStatesNeeded = 0;
3175 unsigned Opc = MI->getOpcode();
3176
3177 auto IsVALUFn = [](const MachineInstr &MI) {
3178 return SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false) || MI.isInlineAsm();
3179 };
3180
3181 if (Opc != AMDGPU::V_ACCVGPR_READ_B32_e64) { // MFMA or v_accvgpr_write
3182 const int LegacyVALUWritesVGPRWaitStates = 2;
3183 const int VALUWritesExecWaitStates = 4;
3184 const int MaxWaitStates = 4;
3185
3186 int WaitStatesNeededForUse = VALUWritesExecWaitStates -
3187 getWaitStatesSinceDef(AMDGPU::EXEC, IsVALUFn, MaxWaitStates);
3188 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3189
3190 if (WaitStatesNeeded < MaxWaitStates) {
3191 for (const MachineOperand &Use : MI->explicit_uses()) {
3192 const int MaxWaitStates = 2;
3193
3194 if (!Use.isReg() || !TRI.isVGPR(MF.getRegInfo(), Use.getReg()))
3195 continue;
3196
3197 int WaitStatesNeededForUse = LegacyVALUWritesVGPRWaitStates -
3198 getWaitStatesSinceDef(Use.getReg(), IsVALUFn, MaxWaitStates);
3199 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3200
3201 if (WaitStatesNeeded == MaxWaitStates)
3202 break;
3203 }
3204 }
3205 }
3206
3207 for (const MachineOperand &Op : MI->explicit_operands()) {
3208 if (!Op.isReg() || !TRI.isAGPR(MF.getRegInfo(), Op.getReg()))
3209 continue;
3210
3211 if (Op.isDef() && Opc != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
3212 continue;
3213
3214 const int MFMAWritesAGPROverlappedSrcABWaitStates = 4;
3215 const int MFMAWritesAGPROverlappedSrcCWaitStates = 2;
3216 const int MFMA4x4WritesAGPRAccVgprReadWaitStates = 4;
3217 const int MFMA16x16WritesAGPRAccVgprReadWaitStates = 10;
3218 const int MFMA32x32WritesAGPRAccVgprReadWaitStates = 18;
3219 const int MFMA4x4WritesAGPRAccVgprWriteWaitStates = 1;
3220 const int MFMA16x16WritesAGPRAccVgprWriteWaitStates = 7;
3221 const int MFMA32x32WritesAGPRAccVgprWriteWaitStates = 15;
3222 const int MaxWaitStates = 18;
3223 Register Reg = Op.getReg();
3224 unsigned HazardDefLatency = 0;
3225
3226 auto IsOverlappedMFMAFn = [Reg, &HazardDefLatency,
3227 this](const MachineInstr &MI) {
3228 if (!SIInstrInfo::isMFMA(MI))
3229 return false;
3230 Register DstReg = MI.getOperand(0).getReg();
3231 if (DstReg == Reg)
3232 return false;
3233 HazardDefLatency =
3234 std::max(HazardDefLatency, TSchedModel.computeInstrLatency(&MI));
3235 return TRI.regsOverlap(DstReg, Reg);
3236 };
3237
3238 int WaitStatesSinceDef = getWaitStatesSinceDef(Reg, IsOverlappedMFMAFn,
3239 MaxWaitStates);
3240 int NeedWaitStates = MFMAWritesAGPROverlappedSrcABWaitStates;
3241 int SrcCIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
3242 int OpNo = Op.getOperandNo();
3243 if (OpNo == SrcCIdx) {
3244 NeedWaitStates = MFMAWritesAGPROverlappedSrcCWaitStates;
3245 } else if (Opc == AMDGPU::V_ACCVGPR_READ_B32_e64) {
3246 switch (HazardDefLatency) {
3247 case 2: NeedWaitStates = MFMA4x4WritesAGPRAccVgprReadWaitStates;
3248 break;
3249 case 8: NeedWaitStates = MFMA16x16WritesAGPRAccVgprReadWaitStates;
3250 break;
3251 case 16: [[fallthrough]];
3252 default: NeedWaitStates = MFMA32x32WritesAGPRAccVgprReadWaitStates;
3253 break;
3254 }
3255 } else if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64) {
3256 switch (HazardDefLatency) {
3257 case 2: NeedWaitStates = MFMA4x4WritesAGPRAccVgprWriteWaitStates;
3258 break;
3259 case 8: NeedWaitStates = MFMA16x16WritesAGPRAccVgprWriteWaitStates;
3260 break;
3261 case 16: [[fallthrough]];
3262 default: NeedWaitStates = MFMA32x32WritesAGPRAccVgprWriteWaitStates;
3263 break;
3264 }
3265 }
3266
3267 int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceDef;
3268 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3269
3270 if (WaitStatesNeeded == MaxWaitStates)
3271 return WaitStatesNeeded; // Early exit.
3272
3273 auto IsAccVgprWriteFn = [Reg, this](const MachineInstr &MI) {
3274 if (MI.getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
3275 return false;
3276 Register DstReg = MI.getOperand(0).getReg();
3277 return TRI.regsOverlap(Reg, DstReg);
3278 };
3279
3280 const int AccVGPRWriteMFMAReadSrcCWaitStates = 1;
3281 const int AccVGPRWriteMFMAReadSrcABWaitStates = 3;
3282 const int AccVGPRWriteAccVgprReadWaitStates = 3;
3283 NeedWaitStates = AccVGPRWriteMFMAReadSrcABWaitStates;
3284 if (OpNo == SrcCIdx)
3285 NeedWaitStates = AccVGPRWriteMFMAReadSrcCWaitStates;
3286 else if (Opc == AMDGPU::V_ACCVGPR_READ_B32_e64)
3287 NeedWaitStates = AccVGPRWriteAccVgprReadWaitStates;
3288
3289 WaitStatesNeededForUse = NeedWaitStates -
3290 getWaitStatesSinceDef(Reg, IsAccVgprWriteFn, MaxWaitStates);
3291 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3292
3293 if (WaitStatesNeeded == MaxWaitStates)
3294 return WaitStatesNeeded; // Early exit.
3295 }
3296
3297 if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64) {
3298 const int MFMA4x4ReadSrcCAccVgprWriteWaitStates = 0;
3299 const int MFMA16x16ReadSrcCAccVgprWriteWaitStates = 5;
3300 const int MFMA32x32ReadSrcCAccVgprWriteWaitStates = 13;
3301 const int MaxWaitStates = 13;
3302 Register DstReg = MI->getOperand(0).getReg();
3303 unsigned HazardDefLatency = 0;
3304
3305 auto IsSrcCMFMAFn = [DstReg, &HazardDefLatency,
3306 this](const MachineInstr &MI) {
3307 if (!SIInstrInfo::isMFMA(MI))
3308 return false;
3309 Register Reg = TII.getNamedOperand(MI, AMDGPU::OpName::src2)->getReg();
3310 HazardDefLatency =
3311 std::max(HazardDefLatency, TSchedModel.computeInstrLatency(&MI));
3312 return TRI.regsOverlap(Reg, DstReg);
3313 };
3314
3315 int WaitStatesSince = getWaitStatesSince(IsSrcCMFMAFn, MaxWaitStates);
3316 int NeedWaitStates;
3317 switch (HazardDefLatency) {
3318 case 2: NeedWaitStates = MFMA4x4ReadSrcCAccVgprWriteWaitStates;
3319 break;
3320 case 8: NeedWaitStates = MFMA16x16ReadSrcCAccVgprWriteWaitStates;
3321 break;
3322 case 16: [[fallthrough]];
3323 default: NeedWaitStates = MFMA32x32ReadSrcCAccVgprWriteWaitStates;
3324 break;
3325 }
3326
3327 int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSince;
3328 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3329 }
3330
3331 // Pad neighboring MFMA with noops for better inter-wave performance.
3332 WaitStatesNeeded = std::max(WaitStatesNeeded, checkMFMAPadding(MI));
3333
3334 return WaitStatesNeeded;
3335}
3336
3337/// One MFMA can be written with up to four opcodes that differ only in how vdst
3338/// and src2 are encoded: both are either AGPRs or VGPRs, and the mac form ties
3339/// vdst to src2 instead of taking them as separate operands. \returns the AGPR,
3340/// non-mac opcode, so that every form of the same MFMA maps to one value.
3341static unsigned getMFMANonMacAGPRFormOp(unsigned Opc) {
3342 if (int NonMacOp = AMDGPU::getMFMAEarlyClobberOp(Opc); NonMacOp != -1)
3343 Opc = NonMacOp;
3344 if (int AGPROp = AMDGPU::getAGPRFormOp(Opc); AGPROp != -1)
3345 Opc = AGPROp;
3346 return Opc;
3347}
3348
3349/// \returns true if \p Opc0 and \p Opc1 are the same MFMA, ignoring the mac
3350/// form and whether vdst/src2 are AGPRs or VGPRs.
3351static bool isSameMFMA(unsigned Opc0, unsigned Opc1) {
3353}
3354
3355static int
3357 bool IsGFX950) {
3358 // xdl def cycles | gfx940 | gfx950
3359 // 2 pass | 3 4
3360 // 4 pass | 5 6
3361 // 8 pass | 9 10
3362 // 16 pass | 17 18
3363 return NumPasses + 1 + IsGFX950;
3364}
3365
3366static int
3368 bool IsGFX950) {
3369 // xdl def cycles | gfx940 | gfx950
3370 // 2 pass | 3 3
3371 // 4 pass | 5 6
3372 // 8 pass | 9 10
3373 // 16 pass | 17 18
3374 return NumPasses + 1 + (NumPasses != 2 && IsGFX950);
3375}
3376
3377static int
3379 // 2 pass -> 2
3380 // 4 pass -> 4
3381 // 8 pass -> 8
3382 // 16 pass -> 16
3383 return NumPasses;
3384}
3385
3386static int
3388 // 2 pass -> 4
3389 // 4 pass -> 6
3390 // 8 pass -> 10
3391 // 16 pass -> 18
3392 return NumPasses + 2;
3393}
3394
3396 bool IsGFX950) {
3397 // xdl def cycles | gfx942 | gfx950
3398 // 2 pass | 5 5
3399 // 4 pass | 7 8
3400 // 8 pass | 11 12
3401 // 16 pass | 19 20
3402 return NumPasses + 3 + (NumPasses != 2 && IsGFX950);
3403}
3404
3405int GCNHazardRecognizer::getMFMAOverlappedSrcCWaitStates(
3406 const MachineInstr *Reader, const MachineInstr *Writer) const {
3407 constexpr int SMFMA4x4WritesVGPROverlappedSMFMASrcCWaitStates = 2;
3408 constexpr int SMFMA16x16WritesVGPROverlappedSMFMASrcCWaitStates = 8;
3409 constexpr int SMFMA32x32WritesVGPROverlappedSMFMASrcCWaitStates = 16;
3410 constexpr int SMFMA4x4WritesVGPROverlappedDMFMASrcCWaitStates = 3;
3411 constexpr int SMFMA16x16WritesVGPROverlappedDMFMASrcCWaitStates = 9;
3412 constexpr int SMFMA32x32WritesVGPROverlappedDMFMASrcCWaitStates = 17;
3413 constexpr int DMFMA16x16WritesVGPROverlappedSrcCWaitStates = 9;
3414 constexpr int GFX950_DMFMA16x16WritesVGPROverlappedSrcCWaitStates = 17;
3415 constexpr int DMFMA4x4WritesVGPROverlappedSrcCWaitStates = 4;
3416
3417 // An XDL read of a non-XDL result needs no wait states. DGEMM is never XDL,
3418 // so this also covers the f64 writers handled below.
3419 if (TII.isXDL(*Reader) && !TII.isXDL(*Writer))
3420 return 0;
3421
3422 switch (Writer->getOpcode()) {
3423 case AMDGPU::V_MFMA_F64_16X16X4F64_e64:
3424 case AMDGPU::V_MFMA_F64_16X16X4F64_vgprcd_e64:
3425 case AMDGPU::V_MFMA_F64_16X16X4F64_mac_e64:
3426 case AMDGPU::V_MFMA_F64_16X16X4F64_mac_vgprcd_e64:
3427 return ST.hasGFX950Insts()
3428 ? GFX950_DMFMA16x16WritesVGPROverlappedSrcCWaitStates
3429 : DMFMA16x16WritesVGPROverlappedSrcCWaitStates;
3430 case AMDGPU::V_MFMA_F64_4X4X4F64_e64:
3431 case AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64:
3432 return DMFMA4x4WritesVGPROverlappedSrcCWaitStates;
3433 default:
3434 break;
3435 }
3436
3437 int NumPasses = TSchedModel.computeInstrLatency(Writer);
3438 if (ST.hasGFX940Insts()) {
3439 if (!TII.isXDL(*Writer))
3441 NumPasses);
3442 return TII.isXDL(*Reader)
3444 NumPasses, ST.hasGFX950Insts())
3446 NumPasses, ST.hasGFX950Insts());
3447 }
3448
3449 bool IsDGEMM = SIInstrInfo::isDGEMM(Reader->getOpcode());
3450 switch (NumPasses) {
3451 case 2:
3452 return IsDGEMM ? SMFMA4x4WritesVGPROverlappedDMFMASrcCWaitStates
3453 : SMFMA4x4WritesVGPROverlappedSMFMASrcCWaitStates;
3454 case 8:
3455 return IsDGEMM ? SMFMA16x16WritesVGPROverlappedDMFMASrcCWaitStates
3456 : SMFMA16x16WritesVGPROverlappedSMFMASrcCWaitStates;
3457 case 16:
3458 return IsDGEMM ? SMFMA32x32WritesVGPROverlappedDMFMASrcCWaitStates
3459 : SMFMA32x32WritesVGPROverlappedSMFMASrcCWaitStates;
3460 default:
3461 llvm_unreachable("unexpected number of passes");
3462 }
3463}
3464
3465int GCNHazardRecognizer::getMFMAReadWaitStates(const MachineInstr &Consumer,
3466 const MachineInstr &Producer,
3467 Register Reg,
3468 bool IsSrcC) const {
3469 unsigned Opc = Consumer.getOpcode();
3470 const int SMFMA4x4WritesVGPROverlappedSrcABWaitStates = 5;
3471 const int SMFMA16x16WritesVGPROverlappedSrcABWaitStates = 11;
3472 const int SMFMA32x32WritesVGPROverlappedSrcABWaitStates = 19;
3473 const int DMFMA4x4WritesVGPROverlappedMFMASrcABWaitStates = 6;
3474 const int DMFMA16x16WritesVGPROverlappedMFMASrcABWaitStates = 11;
3475 const int GFX950_DMFMA16x16WritesVGPROverlappedMFMASrcABWaitStates = 19;
3476 const int DMFMA4x4WritesVGPRFullSrcCWaitStates = 4;
3477 const int GFX940_SMFMA4x4WritesVGPRFullSrcCWaitStates = 2;
3478
3479 bool FullReg = Producer.getOperand(0).getReg() == Reg;
3480 unsigned Opc1 = Producer.getOpcode();
3481 int NeedWaitStates = 0;
3482 if (IsSrcC) {
3483 if (!SIInstrInfo::isDGEMM(Opc) &&
3484 (!ST.hasGFX940Insts() && SIInstrInfo::isDGEMM(Opc1))) {
3485 NeedWaitStates = 0;
3486 } else if (FullReg) {
3487 if ((Opc == AMDGPU::V_MFMA_F64_4X4X4F64_e64 ||
3488 Opc == AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64) &&
3489 (Opc1 == AMDGPU::V_MFMA_F64_4X4X4F64_e64 ||
3490 Opc1 == AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64))
3491 NeedWaitStates = DMFMA4x4WritesVGPRFullSrcCWaitStates;
3492 else if (ST.hasGFX940Insts() &&
3493 TSchedModel.computeInstrLatency(&Producer) == 2)
3494 NeedWaitStates = GFX940_SMFMA4x4WritesVGPRFullSrcCWaitStates;
3495
3496 // The accumulator forwarding path that allows zero wait states is only
3497 // available while the chain stays on a single MFMA. Two different MFMAs
3498 // sharing an accumulator need the wait states of a partial overlap.
3499 if (ST.hasGFX940Insts() && !isSameMFMA(Opc, Opc1)) {
3500 NeedWaitStates =
3501 std::max(NeedWaitStates,
3502 getMFMAOverlappedSrcCWaitStates(&Consumer, &Producer));
3503 }
3504 } else {
3505 NeedWaitStates = getMFMAOverlappedSrcCWaitStates(&Consumer, &Producer);
3506 }
3507 } else {
3508 switch (Opc1) {
3509 case AMDGPU::V_MFMA_F64_16X16X4F64_e64:
3510 case AMDGPU::V_MFMA_F64_16X16X4F64_vgprcd_e64:
3511 case AMDGPU::V_MFMA_F64_16X16X4F64_mac_e64:
3512 case AMDGPU::V_MFMA_F64_16X16X4F64_mac_vgprcd_e64:
3513 NeedWaitStates =
3514 ST.hasGFX950Insts()
3515 ? GFX950_DMFMA16x16WritesVGPROverlappedMFMASrcABWaitStates
3516 : DMFMA16x16WritesVGPROverlappedMFMASrcABWaitStates;
3517 break;
3518 case AMDGPU::V_MFMA_F64_4X4X4F64_e64:
3519 case AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64:
3520 NeedWaitStates = DMFMA4x4WritesVGPROverlappedMFMASrcABWaitStates;
3521 break;
3522 default:
3523 int NumPasses = TSchedModel.computeInstrLatency(&Producer);
3524
3525 if (ST.hasGFX940Insts()) {
3526 NeedWaitStates =
3527 TII.isXDL(Producer)
3529 NumPasses, ST.hasGFX950Insts())
3531 NumPasses);
3532 break;
3533 }
3534
3535 switch (NumPasses) {
3536 case 2:
3537 NeedWaitStates = SMFMA4x4WritesVGPROverlappedSrcABWaitStates;
3538 break;
3539 case 4:
3540 llvm_unreachable("unexpected number of passes for mfma");
3541 case 8:
3542 NeedWaitStates = SMFMA16x16WritesVGPROverlappedSrcABWaitStates;
3543 break;
3544 case 16:
3545 default:
3546 NeedWaitStates = SMFMA32x32WritesVGPROverlappedSrcABWaitStates;
3547 }
3548 }
3549 }
3550 return NeedWaitStates;
3551}
3552
3553int GCNHazardRecognizer::checkMAIHazards90A(MachineInstr *MI) const {
3554 int WaitStatesNeeded = 0;
3555 unsigned Opc = MI->getOpcode();
3556
3557 auto IsLegacyVALUFn = [](const MachineInstr &MI) {
3558 return SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false) &&
3560 };
3561
3562 auto IsLegacyVALUNotDotFn = [](const MachineInstr &MI) {
3563 return SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false) &&
3565 };
3566
3567 if (!SIInstrInfo::isMFMA(*MI))
3568 return WaitStatesNeeded;
3569
3570 const int VALUWritesExecWaitStates = 4;
3571 int WaitStatesNeededForUse = VALUWritesExecWaitStates -
3572 getWaitStatesSinceDef(AMDGPU::EXEC, IsLegacyVALUFn,
3573 VALUWritesExecWaitStates);
3574 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3575
3576 int SrcCIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
3577
3578 // Loop for both DGEMM and S/HGEMM 2nd instruction.
3579 for (const MachineOperand &Use : MI->explicit_uses()) {
3580 const int LegacyVALUNotDotWritesVGPRWaitStates = 2;
3581 const int MaxWaitStates =
3583 16, ST.hasGFX950Insts());
3584
3585 if (!Use.isReg())
3586 continue;
3587 Register Reg = Use.getReg();
3588
3589 WaitStatesNeededForUse = LegacyVALUNotDotWritesVGPRWaitStates -
3590 getWaitStatesSinceDef(Reg, IsLegacyVALUNotDotFn, MaxWaitStates);
3591 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3592
3593 int OpNo = Use.getOperandNo();
3594 WaitStatesNeeded = std::max(
3595 WaitStatesNeeded,
3596 getMaxWindowDeficit(
3597 MaxWaitStates, [&](const MachineInstr &P) -> std::optional<int> {
3598 if (!SIInstrInfo::isMFMA(P) ||
3599 !TRI.regsOverlap(P.getOperand(0).getReg(), Reg))
3600 return std::nullopt;
3601 return getMFMAReadWaitStates(*MI, P, Reg, OpNo == SrcCIdx);
3602 }));
3603
3604 if (WaitStatesNeeded == MaxWaitStates)
3605 break;
3606 }
3607
3608 // Pad neighboring MFMA with noops for better inter-wave performance.
3609 WaitStatesNeeded = std::max(WaitStatesNeeded, checkMFMAPadding(MI));
3610
3611 return WaitStatesNeeded;
3612}
3613
3614int GCNHazardRecognizer::checkMAILdStHazards(MachineInstr *MI) const {
3615 // On gfx90a+ relevant hazards are checked in checkMAIVALUHazards()
3616 if (!ST.hasMAIInsts() || ST.hasGFX90AInsts())
3617 return 0;
3618
3619 int WaitStatesNeeded = 0;
3620
3621 auto IsAccVgprReadFn = [](const MachineInstr &MI) {
3622 return MI.getOpcode() == AMDGPU::V_ACCVGPR_READ_B32_e64;
3623 };
3624
3625 for (const MachineOperand &Op : MI->explicit_uses()) {
3626 if (!Op.isReg() || !TRI.isVGPR(MF.getRegInfo(), Op.getReg()))
3627 continue;
3628
3629 Register Reg = Op.getReg();
3630
3631 const int AccVgprReadLdStWaitStates = 2;
3632 const int VALUWriteAccVgprRdWrLdStDepVALUWaitStates = 1;
3633 const int MaxWaitStates = 2;
3634
3635 int WaitStatesNeededForUse = AccVgprReadLdStWaitStates -
3636 getWaitStatesSinceDef(Reg, IsAccVgprReadFn, MaxWaitStates);
3637 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3638
3639 if (WaitStatesNeeded == MaxWaitStates)
3640 return WaitStatesNeeded; // Early exit.
3641
3642 auto IsVALUAccVgprRdWrCheckFn = [Reg, this](const MachineInstr &MI) {
3643 if (MI.getOpcode() != AMDGPU::V_ACCVGPR_READ_B32_e64 &&
3644 MI.getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
3645 return false;
3646 auto IsVALUFn = [](const MachineInstr &MI) {
3647 return SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false) &&
3649 };
3650 return getWaitStatesSinceDef(Reg, IsVALUFn, 2 /*MaxWaitStates*/) <
3651 std::numeric_limits<int>::max();
3652 };
3653
3654 WaitStatesNeededForUse = VALUWriteAccVgprRdWrLdStDepVALUWaitStates -
3655 getWaitStatesSince(IsVALUAccVgprRdWrCheckFn, MaxWaitStates);
3656 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3657 }
3658
3659 return WaitStatesNeeded;
3660}
3661
3662int GCNHazardRecognizer::checkPermlaneHazards(MachineInstr *MI) const {
3663 assert(!ST.hasVcmpxPermlaneHazard() &&
3664 "this is a different vcmpx+permlane hazard");
3665 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3666 const SIInstrInfo *TII = ST.getInstrInfo();
3667
3668 auto IsVCmpXWritesExecFn = [TII, TRI](const MachineInstr &MI) {
3669 return isVCmpXWritesExec(*TII, *TRI, MI);
3670 };
3671
3672 auto IsVALUFn = [](const MachineInstr &MI) {
3673 return SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false);
3674 };
3675
3676 const int VCmpXWritesExecWaitStates = 4;
3677 const int VALUWritesVDstWaitStates = 2;
3678 int WaitStatesNeeded = 0;
3679
3680 for (const MachineOperand &Op : MI->explicit_uses()) {
3681 if (!Op.isReg() || !TRI->isVGPR(MF.getRegInfo(), Op.getReg()))
3682 continue;
3683 Register Reg = Op.getReg();
3684
3685 int WaitStatesSinceDef =
3686 VALUWritesVDstWaitStates -
3687 getWaitStatesSinceDef(Reg, IsVALUFn,
3688 /*MaxWaitStates=*/VALUWritesVDstWaitStates);
3689 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesSinceDef);
3690 if (WaitStatesNeeded >= VALUWritesVDstWaitStates)
3691 break;
3692 }
3693
3694 int VCmpXHazardWaits =
3695 VCmpXWritesExecWaitStates -
3696 getWaitStatesSince(IsVCmpXWritesExecFn, VCmpXWritesExecWaitStates);
3697
3698 WaitStatesNeeded = std::max(WaitStatesNeeded, VCmpXHazardWaits);
3699 return WaitStatesNeeded;
3700}
3701
3703 // 2 pass -> 4
3704 // 4 pass -> 6
3705 // 8 pass -> 10
3706 // 16 pass -> 18
3707 return NumPasses + 2;
3708}
3709
3711 bool IsGFX950) {
3712 // xdl def cycles | gfx942 | gfx950
3713 // 2 pass | 5 5
3714 // 4 pass | 7 8
3715 // 8 pass | 11 12
3716 // 16 pass | 19 20
3717 return NumPasses + 3 + (NumPasses != 2 && IsGFX950);
3718}
3719
3721 bool IsGFX950) {
3722 // xdl def cycles | gfx942 | gfx950
3723 // 2 pass | 5 5
3724 // 4 pass | 7 8
3725 // 8 pass | 11 12
3726 // 16 pass | 19 20
3727 return NumPasses + 3 + (NumPasses != 2 && IsGFX950);
3728}
3729
3731 // 2 pass -> 4
3732 // 4 pass -> 6
3733 // 8 pass -> 10
3734 // 16 pass -> 18
3735 return NumPasses + 2;
3736}
3737
3738int GCNHazardRecognizer::checkMAIVALUHazards(MachineInstr *MI) const {
3739 if (!ST.hasGFX90AInsts())
3740 return 0;
3741
3742 auto IsDGEMMFn = [](const MachineInstr &MI) -> bool {
3743 return SIInstrInfo::isDGEMM(MI.getOpcode());
3744 };
3745
3746 // This is checked in checkMAIHazards90A()
3747 if (SIInstrInfo::isMFMA(*MI))
3748 return 0;
3749
3750 const MachineRegisterInfo &MRI = MF.getRegInfo();
3751
3752 int WaitStatesNeeded = 0;
3753
3754 bool IsMem = SIInstrInfo::isVMEM(*MI) || SIInstrInfo::isDS(*MI);
3755 bool IsMemOrExport = IsMem || SIInstrInfo::isEXP(*MI);
3756 bool IsVALU = SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/false);
3757
3758 unsigned Reg;
3759 auto IsMFMAWriteFn = [&Reg, this](const MachineInstr &MI) {
3760 if (!SIInstrInfo::isMFMA(MI) ||
3761 !TRI.regsOverlap(MI.getOperand(0).getReg(), Reg))
3762 return false;
3763 return true;
3764 };
3765
3766 const MachineInstr *DOT = nullptr;
3767 auto IsDotWriteFn = [&Reg, &DOT, this](const MachineInstr &MI) {
3768 if (!SIInstrInfo::isDOT(MI) ||
3769 !TRI.regsOverlap(MI.getOperand(0).getReg(), Reg))
3770 return false;
3771 DOT = &MI;
3772 return true;
3773 };
3774
3775 bool DGEMMAfterVALUWrite = false;
3776 auto IsDGEMMHazard = [&DGEMMAfterVALUWrite, this](const MachineInstr &MI) {
3777 // Found DGEMM on reverse traversal to def.
3778 if (SIInstrInfo::isDGEMM(MI.getOpcode()))
3779 DGEMMAfterVALUWrite = true;
3780
3781 // Only hazard if register is defined by a VALU and a DGEMM is found after
3782 // after the def.
3783 if (!TII.isVALU(MI, /*AllowLDSDMA=*/false) || !DGEMMAfterVALUWrite)
3784 return false;
3785
3786 return true;
3787 };
3788
3789 int SrcCIdx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
3790 AMDGPU::OpName::src2);
3791
3792 if (IsMemOrExport || IsVALU) {
3793 const int SMFMA4x4WriteVgprVALUMemExpReadWaitStates = 5;
3794 const int SMFMA16x16WriteVgprVALUMemExpReadWaitStates = 11;
3795 const int SMFMA32x32WriteVgprVALUMemExpReadWaitStates = 19;
3796 const int DMFMA4x4WriteVgprMemExpReadWaitStates = 9;
3797 const int DMFMA16x16WriteVgprMemExpReadWaitStates = 18;
3798 const int DMFMA4x4WriteVgprVALUReadWaitStates = 6;
3799 const int DMFMA16x16WriteVgprVALUReadWaitStates = 11;
3800 const int GFX950_DMFMA16x16WriteVgprVALUReadWaitStates = 19;
3801 const int DotWriteSameDotReadSrcAB = 3;
3802 const int DotWriteDifferentVALURead = 3;
3803 const int DMFMABetweenVALUWriteVMEMRead = 2;
3804 const int MaxWaitStates =
3806 ST.hasGFX950Insts());
3807
3808 for (const MachineOperand &Use : MI->explicit_uses()) {
3809 if (!Use.isReg())
3810 continue;
3811 Reg = Use.getReg();
3812
3813 DOT = nullptr;
3814 int WaitStatesSinceDef = getWaitStatesSinceDef(Reg, IsDotWriteFn,
3815 MaxWaitStates);
3816 if (DOT) {
3817 int NeedWaitStates = 0;
3818 if (DOT->getOpcode() == MI->getOpcode()) {
3819 if (&Use - &MI->getOperand(0) != SrcCIdx)
3820 NeedWaitStates = DotWriteSameDotReadSrcAB;
3821 } else {
3822 NeedWaitStates = DotWriteDifferentVALURead;
3823 }
3824
3825 int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceDef;
3826 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3827 }
3828
3829 // Workaround for HW data hazard bug observed only in GFX90A. When there
3830 // is a DGEMM instruction in-between a VALU and a VMEM instruction it
3831 // causes the SQ to incorrectly not insert two wait states between the two
3832 // instructions needed to avoid data hazard.
3833 if (IsMem && ST.hasGFX90AInsts() && !ST.hasGFX940Insts()) {
3834 DGEMMAfterVALUWrite = false;
3835 if (TRI.isVectorRegister(MRI, Reg)) {
3836 int WaitStatesNeededForUse =
3837 DMFMABetweenVALUWriteVMEMRead -
3838 getWaitStatesSinceDef(Reg, IsDGEMMHazard,
3839 DMFMABetweenVALUWriteVMEMRead);
3840
3841 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3842 }
3843 }
3844
3845 auto MFMAWindow = [&](const MachineInstr &Producer) {
3846 int NumPasses = TSchedModel.computeInstrLatency(&Producer);
3847 int NeedWaitStates = MaxWaitStates;
3848
3849 if (SIInstrInfo::isDGEMM(Producer.getOpcode())) {
3850 switch (NumPasses) {
3851 case 4:
3852 NeedWaitStates = IsMemOrExport
3853 ? DMFMA4x4WriteVgprMemExpReadWaitStates
3854 : DMFMA4x4WriteVgprVALUReadWaitStates;
3855 break;
3856 case 8:
3857 case 16:
3858 NeedWaitStates =
3859 IsMemOrExport
3860 ? DMFMA16x16WriteVgprMemExpReadWaitStates
3861 : (ST.hasGFX950Insts()
3862 ? GFX950_DMFMA16x16WriteVgprVALUReadWaitStates
3863 : DMFMA16x16WriteVgprVALUReadWaitStates);
3864 break;
3865 default:
3866 llvm_unreachable("unexpected dgemm");
3867 }
3868 } else if (ST.hasGFX940Insts()) {
3869 NeedWaitStates =
3870 TII.isXDL(Producer)
3872 NumPasses, ST.hasGFX950Insts())
3874 NumPasses);
3875 } else {
3876 switch (NumPasses) {
3877 case 2:
3878 NeedWaitStates = SMFMA4x4WriteVgprVALUMemExpReadWaitStates;
3879 break;
3880 case 8:
3881 NeedWaitStates = SMFMA16x16WriteVgprVALUMemExpReadWaitStates;
3882 break;
3883 case 16:
3884 NeedWaitStates = SMFMA32x32WriteVgprVALUMemExpReadWaitStates;
3885 break;
3886 default:
3887 llvm_unreachable("unexpected number of passes for mfma");
3888 }
3889 }
3890
3891 assert(NeedWaitStates <= MaxWaitStates &&
3892 "hazard requirement exceeds the scan window");
3893 return NeedWaitStates;
3894 };
3895
3896 WaitStatesNeeded = std::max(
3897 WaitStatesNeeded,
3898 getMaxWindowDeficit(MaxWaitStates,
3899 [&](const MachineInstr &P) -> std::optional<int> {
3900 if (!IsMFMAWriteFn(P))
3901 return std::nullopt;
3902 return MFMAWindow(P);
3903 }));
3904
3905 if (WaitStatesNeeded >= MaxWaitStates)
3906 break;
3907 }
3908 }
3909
3910 unsigned Opc = MI->getOpcode();
3911 const int DMFMAToFMA64WaitStates = 2;
3912 if ((Opc == AMDGPU::V_FMA_F64_e64 ||
3913 Opc == AMDGPU::V_FMAC_F64_e32 || Opc == AMDGPU::V_FMAC_F64_e64 ||
3914 Opc == AMDGPU::V_FMAC_F64_dpp) &&
3915 WaitStatesNeeded < DMFMAToFMA64WaitStates) {
3916 int WaitStatesNeededForUse = DMFMAToFMA64WaitStates -
3917 getWaitStatesSince(IsDGEMMFn, DMFMAToFMA64WaitStates);
3918 WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
3919 }
3920
3921 if (!IsVALU && !IsMemOrExport)
3922 return WaitStatesNeeded;
3923
3924 for (const MachineOperand &Def : MI->defs()) {
3925 const int SMFMA4x4WriteVgprVALUWawWaitStates = 5;
3926 const int SMFMA16x16WriteVgprVALUWawWaitStates = 11;
3927 const int SMFMA32x32WriteVgprVALUWawWaitStates = 19;
3928 const int SMFMA4x4ReadVgprVALUWarWaitStates = 1;
3929 const int GFX940_XDL4PassReadVgprVALUWarWaitStates = 3;
3930 const int SMFMA16x16ReadVgprVALUWarWaitStates = 7;
3931 const int SMFMA32x32ReadVgprVALUWarWaitStates = 15;
3932 const int DMFMA4x4WriteVgprVALUWriteWaitStates = 6;
3933 const int DMFMA16x16WriteVgprVALUWriteWaitStates = 11;
3934 const int DotWriteDifferentVALUWrite = 3;
3935 const int MaxWaitStates =
3936 GFX940_XDL_N_PassWriteVgprVALUWawWaitStates(16, ST.hasGFX950Insts());
3937 const int MaxWarWaitStates = 15;
3938
3939 Reg = Def.getReg();
3940
3941 DOT = nullptr;
3942 int WaitStatesSinceDef = getWaitStatesSinceDef(Reg, IsDotWriteFn,
3943 MaxWaitStates);
3944 if (DOT && DOT->getOpcode() != MI->getOpcode())
3945 WaitStatesNeeded = std::max(WaitStatesNeeded, DotWriteDifferentVALUWrite -
3946 WaitStatesSinceDef);
3947
3948 auto MFMAWawWindow = [&](const MachineInstr &Producer) {
3949 int NeedWaitStates = MaxWaitStates;
3950 int NumPasses = TSchedModel.computeInstrLatency(&Producer);
3951
3952 if (SIInstrInfo::isDGEMM(Producer.getOpcode())) {
3953 switch (NumPasses) {
3954 case 4:
3955 NeedWaitStates = DMFMA4x4WriteVgprVALUWriteWaitStates;
3956 break;
3957 case 8:
3958 case 16:
3959 NeedWaitStates = DMFMA16x16WriteVgprVALUWriteWaitStates;
3960 break;
3961 default:
3962 llvm_unreachable("unexpected number of cycles for dgemm");
3963 }
3964 } else if (ST.hasGFX940Insts()) {
3965 NeedWaitStates =
3966 TII.isXDL(Producer)
3968 NumPasses, ST.hasGFX950Insts())
3970 } else {
3971 switch (NumPasses) {
3972 case 2:
3973 NeedWaitStates = SMFMA4x4WriteVgprVALUWawWaitStates;
3974 break;
3975 case 8:
3976 NeedWaitStates = SMFMA16x16WriteVgprVALUWawWaitStates;
3977 break;
3978 case 16:
3979 NeedWaitStates = SMFMA32x32WriteVgprVALUWawWaitStates;
3980 break;
3981 default:
3982 llvm_unreachable("Unexpected number of passes for mfma");
3983 }
3984 }
3985
3986 assert(NeedWaitStates <= MaxWaitStates &&
3987 "hazard requirement exceeds the scan window");
3988 return NeedWaitStates;
3989 };
3990
3991 WaitStatesNeeded = std::max(
3992 WaitStatesNeeded,
3993 getMaxWindowDeficit(MaxWaitStates,
3994 [&](const MachineInstr &P) -> std::optional<int> {
3995 if (!IsMFMAWriteFn(P))
3996 return std::nullopt;
3997 return MFMAWawWindow(P);
3998 }));
3999
4000 if (WaitStatesNeeded >= MaxWaitStates)
4001 break;
4002
4003 // Wait states this write needs after an MFMA that read Reg as srcC.
4004 auto SMFMAReadAsCWindow =
4005 [&](const MachineInstr &Reader) -> std::optional<int> {
4006 if (!SIInstrInfo::isMFMA(Reader) ||
4007 SIInstrInfo::isDGEMM(Reader.getOpcode()) ||
4008 !Reader.readsRegister(Reg, &TRI))
4009 return std::nullopt;
4010
4011 if (ST.hasGFX940Insts() && !TII.isXDL(Reader))
4012 return std::nullopt;
4013
4014 const MachineOperand *SrcC =
4015 TII.getNamedOperand(Reader, AMDGPU::OpName::src2);
4016 assert(SrcC && "an MFMA must have a src2 operand");
4017 if (!SrcC->isReg() || !TRI.regsOverlap(SrcC->getReg(), Reg))
4018 return std::nullopt;
4019
4020 switch (TSchedModel.computeInstrLatency(&Reader)) {
4021 case 2:
4022 return SMFMA4x4ReadVgprVALUWarWaitStates;
4023 case 4:
4024 assert(ST.hasGFX940Insts() && "4-pass XDL is gfx940 or later");
4025 return GFX940_XDL4PassReadVgprVALUWarWaitStates;
4026 case 8:
4027 return SMFMA16x16ReadVgprVALUWarWaitStates;
4028 case 16:
4029 [[fallthrough]];
4030 default:
4031 return SMFMA32x32ReadVgprVALUWarWaitStates;
4032 }
4033 };
4034
4035 WaitStatesNeeded =
4036 std::max(WaitStatesNeeded,
4037 getMaxWindowDeficit(MaxWarWaitStates, SMFMAReadAsCWindow));
4038 }
4039
4040 return WaitStatesNeeded;
4041}
4042
4044 if (!SU->isInstr())
4045 return false;
4046
4047 const MachineInstr *MAI = nullptr;
4048
4049 auto IsMFMAFn = [&MAI](const MachineInstr &MI) {
4050 MAI = nullptr;
4052 MAI = &MI;
4053 return MAI != nullptr;
4054 };
4055
4056 MachineInstr *MI = SU->getInstr();
4057 if (IsMFMAFn(*MI)) {
4058 int W = getWaitStatesSince(IsMFMAFn, 16);
4059 if (MAI)
4060 return W < (int)TSchedModel.computeInstrLatency(MAI);
4061 }
4062
4063 return false;
4064}
4065
4066// Adjust global offsets for instructions bundled with S_GETPC_B64 after
4067// insertion of a new instruction.
4068static void updateGetPCBundle(MachineInstr *NewMI) {
4069 if (!NewMI->isBundled())
4070 return;
4071
4072 // Find start of bundle.
4073 auto I = NewMI->getIterator();
4074 while (I->isBundledWithPred())
4075 I--;
4076 if (I->isBundle())
4077 I++;
4078
4079 // Bail if this is not an S_GETPC bundle.
4080 if (I->getOpcode() != AMDGPU::S_GETPC_B64)
4081 return;
4082
4083 // Update offsets of any references in the bundle.
4084 const unsigned NewBytes = 4;
4085 assert(NewMI->getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
4086 "Unexpected instruction insertion in bundle");
4087 auto NextMI = std::next(NewMI->getIterator());
4088 auto End = NewMI->getParent()->end();
4089 while (NextMI != End && NextMI->isBundledWithPred()) {
4090 for (auto &Operand : NextMI->operands()) {
4091 if (Operand.isGlobal())
4092 Operand.setOffset(Operand.getOffset() + NewBytes);
4093 }
4094 NextMI++;
4095 }
4096}
4097
4098bool GCNHazardRecognizer::fixVALUMaskWriteHazard(MachineInstr *MI) {
4099 if (!ST.hasVALUMaskWriteHazard())
4100 return false;
4101 assert(!ST.hasExtendedWaitCounts());
4102
4103 if (!ST.isWave64())
4104 return false;
4105
4106 const bool IsSALU = SIInstrInfo::isSALU(*MI);
4107 const bool IsVALU = SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/false);
4108 if (!IsSALU && !IsVALU)
4109 return false;
4110
4111 // The hazard sequence is three instructions:
4112 // 1. VALU reads SGPR as mask
4113 // 2. VALU/SALU writes SGPR
4114 // 3. VALU/SALU reads SGPR
4115 // The hazard can expire if the distance between 2 and 3 is sufficient,
4116 // or (2) is VALU and (3) is SALU.
4117 // In practice this happens <10% of the time, hence always assume the hazard
4118 // exists if (1) and (2) are present to avoid searching all SGPR reads.
4119
4120 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4121 const MachineRegisterInfo &MRI = MF.getRegInfo();
4122
4123 auto IgnoreableSGPR = [](const Register Reg) {
4124 switch (Reg) {
4125 case AMDGPU::EXEC:
4126 case AMDGPU::EXEC_LO:
4127 case AMDGPU::EXEC_HI:
4128 case AMDGPU::M0:
4129 case AMDGPU::SGPR_NULL:
4130 case AMDGPU::SGPR_NULL64:
4131 case AMDGPU::SCC:
4132 return true;
4133 default:
4134 return false;
4135 }
4136 };
4137 auto IsVCC = [](const Register Reg) {
4138 return Reg == AMDGPU::VCC || Reg == AMDGPU::VCC_LO || Reg == AMDGPU::VCC_HI;
4139 };
4140
4141 struct StateType {
4142 SmallSet<Register, 2> HazardSGPRs;
4143
4144 static unsigned getHashValue(const StateType &State) {
4145 return static_cast<unsigned>(hash_combine_range(State.HazardSGPRs));
4146 }
4147 static bool isEqual(const StateType &LHS, const StateType &RHS) {
4148 return LHS.HazardSGPRs == RHS.HazardSGPRs;
4149 }
4150 };
4151
4152 StateType InitialState;
4153
4154 // Look for SGPR write.
4155 MachineOperand *HazardDef = nullptr;
4156 for (MachineOperand &Op : MI->all_defs()) {
4157 Register Reg = Op.getReg();
4158 if (IgnoreableSGPR(Reg))
4159 continue;
4160 if (!IsVCC(Reg)) {
4161 if (Op.isImplicit())
4162 continue;
4163 if (!TRI->isSGPRReg(MRI, Reg))
4164 continue;
4165 }
4166
4167 HazardDef = &Op;
4168 break;
4169 }
4170
4171 if (!HazardDef)
4172 return false;
4173
4174 // Setup to track writes to individual SGPRs
4175 const Register HazardReg = HazardDef->getReg();
4176 if (AMDGPU::SReg_32RegClass.contains(HazardReg)) {
4177 InitialState.HazardSGPRs.insert(HazardReg);
4178 } else {
4179 assert(AMDGPU::SReg_64RegClass.contains(HazardReg));
4180 InitialState.HazardSGPRs.insert(TRI->getSubReg(HazardReg, AMDGPU::sub0));
4181 InitialState.HazardSGPRs.insert(TRI->getSubReg(HazardReg, AMDGPU::sub1));
4182 }
4183
4184 auto IsHazardFn = [&](StateType &State, const MachineInstr &I) {
4185 if (State.HazardSGPRs.empty())
4186 return HazardExpired;
4187
4188 switch (I.getOpcode()) {
4189 case AMDGPU::V_ADDC_U32_e32:
4190 case AMDGPU::V_ADDC_U32_dpp:
4191 case AMDGPU::V_CNDMASK_B16_t16_e32:
4192 case AMDGPU::V_CNDMASK_B16_fake16_e32:
4193 case AMDGPU::V_CNDMASK_B16_t16_dpp:
4194 case AMDGPU::V_CNDMASK_B16_fake16_dpp:
4195 case AMDGPU::V_CNDMASK_B32_e32:
4196 case AMDGPU::V_CNDMASK_B32_dpp:
4197 case AMDGPU::V_DIV_FMAS_F32_e64:
4198 case AMDGPU::V_DIV_FMAS_F64_e64:
4199 case AMDGPU::V_SUBB_U32_e32:
4200 case AMDGPU::V_SUBB_U32_dpp:
4201 case AMDGPU::V_SUBBREV_U32_e32:
4202 case AMDGPU::V_SUBBREV_U32_dpp: {
4203 // These implicitly read VCC as mask source.
4204 return IsVCC(HazardReg) ? HazardFound : NoHazardFound;
4205 }
4206 case AMDGPU::V_ADDC_U32_e64:
4207 case AMDGPU::V_ADDC_U32_e64_dpp:
4208 case AMDGPU::V_CNDMASK_B16_t16_e64:
4209 case AMDGPU::V_CNDMASK_B16_fake16_e64:
4210 case AMDGPU::V_CNDMASK_B16_t16_e64_dpp:
4211 case AMDGPU::V_CNDMASK_B16_fake16_e64_dpp:
4212 case AMDGPU::V_CNDMASK_B32_e64:
4213 case AMDGPU::V_CNDMASK_B32_e64_dpp:
4214 case AMDGPU::V_SUBB_U32_e64:
4215 case AMDGPU::V_SUBB_U32_e64_dpp:
4216 case AMDGPU::V_SUBBREV_U32_e64:
4217 case AMDGPU::V_SUBBREV_U32_e64_dpp: {
4218 // Only check mask register overlaps.
4219 const MachineOperand *SSRCOp = TII.getNamedOperand(I, AMDGPU::OpName::src2);
4220 assert(SSRCOp);
4221 bool Result = TRI->regsOverlap(SSRCOp->getReg(), HazardReg);
4222 return Result ? HazardFound : NoHazardFound;
4223 }
4224 default:
4225 return NoHazardFound;
4226 }
4227 };
4228
4229 auto UpdateStateFn = [&](StateType &State, const MachineInstr &I) {
4230 // Update tracking of SGPR writes.
4231 for (auto &Op : I.all_defs()) {
4232 Register Reg = Op.getReg();
4233 if (IgnoreableSGPR(Reg))
4234 continue;
4235 if (!IsVCC(Reg)) {
4236 if (Op.isImplicit())
4237 continue;
4238 if (!TRI->isSGPRReg(MRI, Reg))
4239 continue;
4240 }
4241
4242 // Stop tracking any SGPRs with writes on the basis that they will
4243 // already have an appropriate wait inserted afterwards.
4245 for (Register SGPR : State.HazardSGPRs) {
4246 if (Reg == SGPR || TRI->regsOverlap(Reg, SGPR))
4247 Found.push_back(SGPR);
4248 }
4249 for (Register SGPR : Found)
4250 State.HazardSGPRs.erase(SGPR);
4251 }
4252 };
4253
4254 // Check for hazard
4255 if (!hasHazard<StateType>(InitialState, IsHazardFn, UpdateStateFn,
4256 MI->getParent(),
4257 std::next(MI->getReverseIterator())))
4258 return false;
4259
4260 // Compute counter mask
4261 unsigned DepCtr =
4262 IsVALU ? (IsVCC(HazardReg) ? AMDGPU::DepCtr::encodeFieldVaVcc(0, ST)
4263 : AMDGPU::DepCtr::encodeFieldVaSdst(0, ST))
4264 : AMDGPU::DepCtr::encodeFieldSaSdst(0, ST);
4265
4266 // Add s_waitcnt_depctr after SGPR write.
4267 auto NextMI = std::next(MI->getIterator());
4268 auto NewMI = BuildMI(*MI->getParent(), NextMI, MI->getDebugLoc(),
4269 TII.get(AMDGPU::S_WAITCNT_DEPCTR))
4270 .addImm(DepCtr);
4271
4272 // SALU write may be s_getpc in a bundle.
4273 updateGetPCBundle(NewMI);
4274
4275 return true;
4276}
4277
4278static bool ensureEntrySetPrio(MachineFunction *MF, int Priority,
4279 const SIInstrInfo &TII) {
4280 MachineBasicBlock &EntryMBB = MF->front();
4281 auto EntryI = skipMetaInstructionsForward(EntryMBB.begin(), EntryMBB.end());
4282 if (EntryI != EntryMBB.end() && EntryI->getOpcode() == AMDGPU::S_SETPRIO &&
4283 EntryI->getOperand(0).getImm() >= Priority)
4284 return false;
4285
4286 // Insert at the start of the block, before any meta instructions.
4287 BuildMI(EntryMBB, EntryMBB.begin(), DebugLoc(), TII.get(AMDGPU::S_SETPRIO))
4288 .addImm(Priority);
4289 return true;
4290}
4291
4292bool GCNHazardRecognizer::fixRequiredExportPriority(MachineInstr *MI) {
4293 if (!ST.hasRequiredExportPriority())
4294 return false;
4295
4296 // Assume the following shader types will never have exports,
4297 // and avoid adding or adjusting S_SETPRIO.
4298 MachineBasicBlock *MBB = MI->getParent();
4299 MachineFunction *MF = MBB->getParent();
4300 auto CC = MF->getFunction().getCallingConv();
4301 switch (CC) {
4306 return false;
4307 default:
4308 break;
4309 }
4310
4311 const int MaxPriority = 3;
4312 const int NormalPriority = 2;
4313 const int PostExportPriority = 0;
4314
4315 auto It = MI->getIterator();
4316 switch (MI->getOpcode()) {
4317 case AMDGPU::S_ENDPGM:
4318 case AMDGPU::S_ENDPGM_SAVED:
4319 case AMDGPU::S_ENDPGM_ORDERED_PS_DONE:
4320 case AMDGPU::SI_RETURN_TO_EPILOG:
4321 // Ensure shader with calls raises priority at entry.
4322 // This ensures correct priority if exports exist in callee.
4323 if (MF->getFrameInfo().hasCalls())
4324 return ensureEntrySetPrio(MF, NormalPriority, TII);
4325 return false;
4326 case AMDGPU::S_SETPRIO: {
4327 // Raise minimum priority unless in workaround.
4328 auto &PrioOp = MI->getOperand(0);
4329 int Prio = static_cast<int>(PrioOp.getImm());
4330 bool InWA =
4331 (Prio == PostExportPriority) &&
4332 (It != MBB->instr_begin() && TII.isEXP(*skipMetaInstructionsBackward(
4333 std::prev(It), MBB->instr_begin())));
4334 if (InWA || Prio >= NormalPriority)
4335 return false;
4336 PrioOp.setImm(std::min(Prio + NormalPriority, MaxPriority));
4337 return true;
4338 }
4339 default:
4340 if (!TII.isEXP(*MI))
4341 return false;
4342 break;
4343 }
4344
4345 // Check entry priority at each export (as there will only be a few).
4346 // Note: amdgpu_gfx can only be a callee, so defer to caller setprio.
4347 bool Changed = false;
4349 Changed = ensureEntrySetPrio(MF, NormalPriority, TII);
4350
4351 auto InsertPt = std::next(It);
4353 bool EndOfShader = false;
4354 if (NextMI != MBB->instr_end()) {
4355 // Only need WA at end of sequence of exports.
4356 if (TII.isEXP(*NextMI))
4357 return Changed;
4358 // Assume appropriate S_SETPRIO after export means WA already applied.
4359 if (NextMI->getOpcode() == AMDGPU::S_SETPRIO &&
4360 NextMI->getOperand(0).getImm() == PostExportPriority)
4361 return Changed;
4362 EndOfShader = NextMI->getOpcode() == AMDGPU::S_ENDPGM;
4363 }
4364
4365 const DebugLoc &DL = MI->getDebugLoc();
4366
4367 // Lower priority.
4368 BuildMI(*MBB, InsertPt, DL, TII.get(AMDGPU::S_SETPRIO))
4369 .addImm(PostExportPriority);
4370
4371 if (!EndOfShader) {
4372 // Wait for exports to complete.
4373 BuildMI(*MBB, InsertPt, DL, TII.get(AMDGPU::S_WAITCNT_EXPCNT))
4374 .addReg(AMDGPU::SGPR_NULL)
4375 .addImm(0);
4376 }
4377
4378 BuildMI(*MBB, InsertPt, DL, TII.get(AMDGPU::S_NOP)).addImm(0);
4379 BuildMI(*MBB, InsertPt, DL, TII.get(AMDGPU::S_NOP)).addImm(0);
4380
4381 if (!EndOfShader) {
4382 // Return to normal (higher) priority.
4383 BuildMI(*MBB, InsertPt, DL, TII.get(AMDGPU::S_SETPRIO))
4384 .addImm(NormalPriority);
4385 }
4386
4387 return true;
4388}
4389
4390bool GCNHazardRecognizer::fixVPermPk16Hazard(MachineInstr *MI) {
4391 // Requirement #1 of 2:
4392 // The cross-wave entry-block mitigation is delegated to the mandatory
4393 // unclaused-VMEM entry prologue (GLOBAL_PREFETCH_B8 + V_NOP).
4394 assert(ST.hasRequiresInitialUnclausedVmem() &&
4395 "V_PERM_PK16-hazard subtarget must provide the unclaused-VMEM entry "
4396 "prologue to satisfy the cross-wave entry mitigation");
4397
4398 if (!SIInstrInfo::isVPermPk16(MI->getOpcode()))
4399 return false;
4400
4401 MachineBasicBlock *MBB = MI->getParent();
4402
4403 // Requirement #2 of 2:
4404 // V_PERM_PK16 must be immediately followed by a safe instruction.
4405 auto NextI = skipMetaInstructionsForward(
4406 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
4407 if (NextI != MBB->end() && TII.isVPermPk16SafeInstr(*NextI))
4408 return false;
4409
4410 // EXEC is guaranteed non-zero here: V_PERM_PK16 reports unwanted effects
4411 // when EXEC is empty, so s_cbranch_execz over this region is retained.
4412 // A plain V_NOP is therefore a real VALU nop and clears the hazard.
4413 BuildMI(*MBB, NextI, MI->getDebugLoc(), TII.get(AMDGPU::V_NOP_e32));
4414 return true;
4415}
4416
4417bool GCNHazardRecognizer::fixGetRegWaitIdle(MachineInstr *MI) {
4418 if (!isSGetReg(MI->getOpcode()))
4419 return false;
4420
4421 const SIInstrInfo *TII = ST.getInstrInfo();
4422 switch (getHWReg(TII, *MI)) {
4423 default:
4424 return false;
4429 break;
4430 }
4431
4432 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4433 TII->get(AMDGPU::S_WAITCNT_DEPCTR))
4434 .addImm(0);
4435 return true;
4436}
4437
4438bool GCNHazardRecognizer::fixDsAtomicAsyncBarrierArriveB64(MachineInstr *MI) {
4439 if (MI->getOpcode() != AMDGPU::DS_ATOMIC_ASYNC_BARRIER_ARRIVE_B64)
4440 return false;
4441
4442 const SIInstrInfo *TII = ST.getInstrInfo();
4443 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4444 TII->get(AMDGPU::S_WAITCNT_DEPCTR))
4446 BuildMI(*MI->getParent(), std::next(MI->getIterator()), MI->getDebugLoc(),
4447 TII->get(AMDGPU::S_WAITCNT_DEPCTR))
4449
4450 return true;
4451}
4452
4453bool GCNHazardRecognizer::fixBarrierJoinCompletion(MachineInstr *MI) {
4454 if (MI->getOpcode() != AMDGPU::S_BARRIER_JOIN_IMM &&
4455 MI->getOpcode() != AMDGPU::S_BARRIER_JOIN_M0)
4456 return false;
4457
4458 // A singular S_BARRIER_JOIN may observe spurious barrier completions, so
4459 // issue it twice in a row. Insert it before the MI; the block is walked
4460 // forwards so if we inserted it after, we'd duplicate the copy again and
4461 // never terminate.
4462 MachineBasicBlock &MBB = *MI->getParent();
4463 MBB.insert(MI->getIterator(), MBB.getParent()->CloneMachineInstr(MI));
4464 return true;
4465}
4466
4467bool GCNHazardRecognizer::fixScratchBaseForwardingHazard(MachineInstr *MI) {
4468 // No reason to check this in pre-RA scheduling, SGPRs have to be allocated
4469 // for hazard to trigger.
4471 return false;
4472
4473 const SIRegisterInfo *TRI = ST.getRegisterInfo();
4474 const SIInstrInfo *TII = ST.getInstrInfo();
4475 // Hazard expires after 10 SGPR writes by SALU or 8 SGPR writes by VALU.
4476 const int FlatScrBaseWaitStates = 10;
4477
4478 bool ReadsFlatScrLo =
4479 MI->readsRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE_LO, TRI);
4480 bool ReadsFlatScrHi =
4481 MI->readsRegister(AMDGPU::SRC_FLAT_SCRATCH_BASE_HI, TRI);
4482 if (isSGetReg(MI->getOpcode())) {
4483 switch (getHWReg(TII, *MI)) {
4484 default:
4485 break;
4487 ReadsFlatScrLo = true;
4488 break;
4490 ReadsFlatScrHi = true;
4491 break;
4492 }
4493 }
4494
4495 const MachineRegisterInfo &MRI = MF.getRegInfo();
4496
4497 auto IsRegDefHazard = [&](Register Reg) -> bool {
4498 DenseSet<const MachineBasicBlock *> Visited;
4499 auto IsHazardFn = [TRI, Reg](const MachineInstr &MI) {
4500 return MI.modifiesRegister(Reg, TRI);
4501 };
4502
4503 // This literally abuses the idea of waitstates. Instead of waitstates it
4504 // returns 1 for SGPR written and 0 otherwise.
4505 auto IsSGPRDef = [TII, TRI, &MRI](const MachineInstr &MI) -> unsigned {
4506 if (!TII->isSALU(MI) && !TII->isVALU(MI, /*AllowLDSDMA=*/false))
4507 return 0;
4508 for (const MachineOperand &MO : MI.all_defs()) {
4509 if (TRI->isSGPRReg(MRI, MO.getReg()))
4510 return 1;
4511 }
4512 return 0;
4513 };
4514
4515 auto IsExpiredFn = [=](const MachineInstr &MI, int SgprWrites) {
4516 if (MI.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR) {
4517 unsigned Wait = static_cast<unsigned>(MI.getOperand(0).getImm());
4520 return true;
4521 }
4522 return SgprWrites >= FlatScrBaseWaitStates;
4523 };
4524
4525 return ::getWaitStatesSince(
4526 IsHazardFn, MI->getParent(), std::next(MI->getReverseIterator()),
4527 0, IsExpiredFn, Visited, IsSGPRDef) < FlatScrBaseWaitStates;
4528 };
4529
4530 if ((!ReadsFlatScrLo || MRI.isConstantPhysReg(AMDGPU::SGPR102) ||
4531 !IsRegDefHazard(AMDGPU::SGPR102)) &&
4532 (!ReadsFlatScrHi || MRI.isConstantPhysReg(AMDGPU::SGPR103) ||
4533 !IsRegDefHazard(AMDGPU::SGPR103)))
4534 return false;
4535
4536 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4537 TII->get(AMDGPU::S_WAITCNT_DEPCTR))
4540 return true;
4541}
4542
4543bool GCNHazardRecognizer::fixSetRegMode(MachineInstr *MI) {
4544 if (!isSSetReg(MI->getOpcode()) ||
4545 MI->getOperand(1).getImm() != AMDGPU::Hwreg::ID_MODE)
4546 return false;
4547
4548 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII.get(AMDGPU::V_NOP_e32));
4549 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII.get(AMDGPU::V_NOP_e32));
4550 return true;
4551}
4552
4553bool GCNHazardRecognizer::fixTDM(MachineInstr *MI) {
4554 auto IsTDM = [&](const MachineInstr &MI) -> bool {
4556 MI.getOpcode() != AMDGPU::S_WAIT_TENSORCNT;
4557 };
4558
4559 if (!IsTDM(*MI))
4560 return false;
4561
4562 auto IsExpiredFn = [](const MachineInstr &MI, int) {
4563 if (MI.getOpcode() != AMDGPU::S_WAIT_TENSORCNT)
4564 return false;
4565 return MI.getOperand(0).getImm() <= 10;
4566 };
4567
4568 if (::getWaitStatesSince(IsTDM, MI, IsExpiredFn) ==
4569 std::numeric_limits<int>::max())
4570 return false;
4571
4572 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4573 TII.get(AMDGPU::S_WAIT_TENSORCNT))
4574 .addImm(10);
4575 return true;
4576}
4577
4578bool GCNHazardRecognizer::fixTransF16ToPartialVGPRWriteHazard(
4579 MachineInstr *MI) {
4580 if (!SIInstrInfo::isVALU(*MI, /*AllowLDSDMA=*/false))
4581 return false;
4582
4583 const int NumVALUNeeded = 4;
4584 const MachineRegisterInfo &MRI = MF.getRegInfo();
4585
4586 struct StateType {
4587 int VALUs = 0;
4588
4589 static unsigned getHashValue(const StateType &State) { return State.VALUs; }
4590 static bool isEqual(const StateType &LHS, const StateType &RHS) {
4591 return LHS.VALUs == RHS.VALUs;
4592 }
4593 };
4594
4595 StateType State;
4596
4597 auto IsHazardFn = [&](StateType &State, const MachineInstr &I) {
4598 // Too many VALU states have passed
4599 if (State.VALUs >= NumVALUNeeded)
4600 return HazardExpired;
4601
4602 // Instructions which cause va_vdst==0 expire hazard
4603 if (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
4605 static_cast<unsigned>(I.getOperand(0).getImm())) == 0)
4606 return HazardExpired;
4607
4608 // Track registers writes
4609 if (!SIInstrInfo::isTRANS(I))
4610 return NoHazardFound;
4611
4612 MCRegister Def = I.getOperand(0).getReg();
4613 if (!TRI.isVGPR(MRI, Def))
4614 return NoHazardFound;
4615
4616 unsigned Opc = I.getOpcode();
4617 const MCInstrDesc &Desc = TII.get(Opc);
4618 // Note: checking vdst does not work because it is a generic
4619 // OPERAND_REGISTER.
4620 switch (
4621 Desc.operands()[AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0)]
4622 .OperandType) {
4628 break;
4629 default:
4630 // DPP instructions have VGPR-only src0 with generic OPERAND_REGISTER
4631 // type. The isDPP() check will catch any TRANS opcodes including f32.
4632 // This is suboptimal but shall only affect fake16 compilation because
4633 // of the Def size check below.
4634 if (SIInstrInfo::isDPP(I))
4635 break;
4636 return NoHazardFound;
4637 }
4638
4639 if (TRI.getRegSizeInBits(Def, MRI) == 16) {
4640 // Real True16 case.
4641 const auto Sub = AMDGPU::isHi16Reg(Def, TRI)
4642 ? std::make_pair(AMDGPU::hi16, AMDGPU::lo16)
4643 : std::make_pair(AMDGPU::lo16, AMDGPU::hi16);
4644 MCRegister Def32 =
4645 TRI.getMatchingSuperReg(Def, Sub.first, &AMDGPU::VGPR_32RegClass);
4646 MCRegister OffendingDef = TRI.getSubReg(Def32, Sub.second);
4647 // Only interested in partial 16-bit write, not any wider register.
4648 return MI->modifiesRegister(OffendingDef, nullptr) ? HazardFound
4649 : NoHazardFound;
4650 }
4651
4652 // Bail for any non-16 bit DPP instructions catched in true16 mode.
4653 if (ST.useRealTrue16Insts())
4654 return NoHazardFound;
4655
4656 // Fake16 case is suboptimal as it checks the whole 32-bit def overlap w/o
4657 // analyzing OPSEL bits.
4658 return MI->modifiesRegister(Def, nullptr) ? HazardFound : NoHazardFound;
4659 };
4660
4661 auto UpdateStateFn = [](StateType &State, const MachineInstr &MI) {
4662 if (SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/true))
4663 ++State.VALUs;
4664 };
4665
4666 if (!hasHazard<StateType>(State, IsHazardFn, UpdateStateFn, MI->getParent(),
4667 std::next(MI->getReverseIterator())))
4668 return false;
4669
4670 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4671 TII.get(AMDGPU::S_WAITCNT_DEPCTR))
4673
4674 return true;
4675}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
uint64_t Imm
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(AttributeSet CallerAttrs, AttributeSet CalleeAttrs)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static cl::opt< unsigned, false, MFMAPaddingRatioParser > MFMAPaddingRatio("amdgpu-mfma-padding-ratio", cl::init(0), cl::Hidden, cl::desc("Fill a percentage of the latency between " "neighboring MFMA with s_nops."))
static bool shouldRunLdsBranchVmemWARHazardFixup(const MachineFunction &MF, const GCNSubtarget &ST)
static bool consumesDstSelForwardingOperand(const MachineInstr *VALU, const MachineOperand *Dst, const SIRegisterInfo *TRI)
Checks whether the provided MI "consumes" the operand with a Dest sel fowarding issue Dst .
static bool isSGetReg(unsigned Opcode)
static bool breaksSMEMSoftClause(MachineInstr *MI)
static bool isLdsDma(const MachineInstr &MI)
static int GFX940_XDL_N_PassWritesVGPROverlappedSrcABWaitStates(int NumPasses, bool IsGFX950)
static unsigned getWMMAHazardInstInCategory(const MachineInstr &MI, const SIInstrInfo *TII, const TargetSchedModel &SchedModel, const GCNSubtarget &ST)
static bool isRFE(unsigned Opcode)
static bool isRWLane(unsigned Opcode)
static bool isSMovRel(unsigned Opcode)
static unsigned getMFMANonMacAGPRFormOp(unsigned Opc)
One MFMA can be written with up to four opcodes that differ only in how vdst and src2 are encoded: bo...
#define DEBUG_TYPE_VERBOSE
static const MachineOperand * getDstSelForwardingOperand(const MachineInstr &MI, const GCNSubtarget &ST)
Dest sel forwarding issue occurs if additional logic is needed to swizzle / pack the computed value i...
static int GFX940_XDL_N_PassWritesVGPROverlappedSGEMMDGEMMSrcCWaitStates(int NumPasses, bool IsGFX950)
static void updateGetPCBundle(MachineInstr *NewMI)
static int GFX940_XDL_N_PassWriteVgprVALUMemExpReadWaitStates(int NumPasses, bool IsGFX950)
static bool isStoreCountWaitZero(const MachineInstr &I)
static bool breaksVMEMSoftClause(MachineInstr *MI)
static bool isVCmpXWritesExec(const SIInstrInfo &TII, const SIRegisterInfo &TRI, const MachineInstr &MI)
static bool isSSetReg(unsigned Opcode)
static void addRegUnits(const SIRegisterInfo &TRI, BitVector &BV, MCRegister Reg)
static unsigned getHWReg(const SIInstrInfo *TII, const MachineInstr &RegInstr)
static bool isSameMFMA(unsigned Opc0, unsigned Opc1)
static bool isDivFMas(unsigned Opcode)
static unsigned getCountedWaitStates(const MachineInstr &MI, GCNHazardRecognizer::GetNumWaitStatesFn GetNumWaitStates)
static bool hasHazard(StateT InitialState, function_ref< HazardFnResult(StateT &, const MachineInstr &)> IsHazard, function_ref< void(StateT &, const MachineInstr &)> UpdateState, const MachineBasicBlock *InitialMBB, MachineBasicBlock::const_reverse_instr_iterator InitialI)
static int getWaitStatesSince(GCNHazardRecognizer::IsHazardFn IsHazard, const MachineBasicBlock *MBB, MachineBasicBlock::const_reverse_instr_iterator I, int WaitStates, GCNHazardRecognizer::IsExpiredFn IsExpired, DenseSet< const MachineBasicBlock * > &Visited, GCNHazardRecognizer::GetNumWaitStatesFn GetNumWaitStates=SIInstrInfo::getNumWaitStates)
static int GFX940_SMFMA_N_PassWritesVGPROverlappedSrcABWaitStates(int NumPasses)
static int GFX940_XDL_N_PassWriteVgprVALUWawWaitStates(int NumPasses, bool IsGFX950)
static int GFX940_SMFMA_N_PassWriteVgprVALUMemExpReadWaitStates(int NumPasses)
static int GFX940_SMFMA_N_PassWritesVGPROverlappedSMFMASrcCWaitStates(int NumPasses)
static bool isCoexecutableVALUInst(const MachineInstr &MI)
static bool ensureEntrySetPrio(MachineFunction *MF, int Priority, const SIInstrInfo &TII)
static void addRegsToSet(const SIRegisterInfo &TRI, iterator_range< MachineInstr::const_mop_iterator > Ops, BitVector &DefSet, BitVector &UseSet)
static void insertNoopsInBundle(MachineInstr *MI, const SIInstrInfo &TII, unsigned Quantity)
static bool isSendMsgTraceDataOrGDS(const SIInstrInfo &TII, const MachineInstr &MI)
static unsigned countUnexecutedTerminators(const MachineBasicBlock &Pred, const MachineBasicBlock *MBB)
static bool isPermlane(const MachineInstr &MI)
static int GFX940_SMFMA_N_PassWriteVgprVALUWawWaitStates(int NumPasses)
static int GFX940_XDL_N_PassWritesVGPROverlappedXDLOrSMFMASrcCWaitStates(int NumPasses, bool IsGFX950)
AMD GCN specific subclass of TargetSubtarget.
static Register UseReg(const MachineOperand &MO)
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static llvm::Error parse(GsymDataExtractor &Data, uint64_t BaseAddr, LineEntryCallback const &Callback)
Definition LineTable.cpp:54
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
#define P(N)
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
Func MI getDebugLoc()))
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
unsigned get(InstCounterType T) const
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
A debug info location.
Definition DebugLoc.h:126
std::pair< iterator, bool > insert_as(std::pair< KeyT, ValueT > &&KV, const LookupKeyT &Val)
Alternate version of insert() which allows a different, and possibly less expensive,...
Definition DenseMap.h:874
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
static unsigned getMaxWMMACoexecutionWaitStates(const GCNSubtarget &ST)
Largest number of intervening VALUs checkWMMACoexecutionHazards() can require between an XDL WMMA and...
unsigned getHazardWaitStates(MachineInstr *MI) const
Returns the number of wait states until all hazards for MI are resolved.
unsigned PreEmitNoopsCommon(MachineInstr *) const
OperatingMode
Operating mode for the hazard recognizer.
void EmitNoop() override
EmitNoop - This callback is invoked when a noop was added to the instruction stream.
void Reset() override
Reset - This callback is invoked when a new block of instructions is about to be schedule.
unsigned PreEmitNoops(MachineInstr *) override
This overload will be used when the hazard recognizer is being used by a non-scheduling pass,...
void EmitInstruction(SUnit *SU) override
EmitInstruction - This callback is invoked when an instruction is emitted, to advance the hazard stat...
function_ref< bool(const MachineInstr &)> IsHazardFn
void AdvanceCycle() override
AdvanceCycle - This callback is invoked whenever the next top-down instruction to be scheduled cannot...
function_ref< unsigned int(const MachineInstr &)> GetNumWaitStatesFn
bool ShouldPreferAnother(SUnit *SU) const override
ShouldPreferAnother - This callback may be invoked if getHazardType returns NoHazard.
bool hasPhysRegs() const
Returns true if instruction operands are physical registers, so that hazards defined by register depe...
function_ref< bool(const MachineInstr &, int WaitStates)> IsExpiredFn
bool isSchedulerMode() const
Returns true if running as a scheduler (pre-RA or post-RA).
GCNHazardRecognizer(const MachineFunction &MF, OperatingMode Mode, MachineLoopInfo *MLI=nullptr)
Construct with explicit operating mode.
static AMDGPU::CoExecMaskT getCoExecMaskForMI(const MachineInstr &MI, const SIInstrInfo &TII)
Get the CoExecMask for a given instruction.
HazardType getHazardType(SUnit *SU, int Stalls) override
getHazardType - Return the hazard type of emitting this node.
void RecedeCycle() override
RecedeCycle - This callback is invoked whenever the next bottom-up instruction to be scheduled cannot...
bool isHazardRecognizerMode() const
Returns true if running as the standalone hazard recognizer pass.
bool isPreRA() const
Returns true if running in pre-RA scheduling mode.
const SIInstrInfo * getInstrInfo() const override
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
Instructions::const_reverse_iterator const_reverse_instr_iterator
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Instructions::iterator instr_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
bool isBundled() const
Return true if this instruction part of a bundle.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool isConstantPhysReg(MCRegister PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
LLVM_ABI bool isPhysRegUsed(MCRegister PhysReg, bool SkipRegMaskTest=false) const
Return true if the specified register is modified or read in this function.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static bool isDS(const MachineInstr &MI)
static bool isVMEM(const MachineInstr &MI)
static bool isSMRD(const MachineInstr &MI)
static bool isMTBUF(const MachineInstr &MI)
static bool isDGEMM(unsigned Opcode)
static bool isEXP(const MachineInstr &MI)
static bool isSALU(const MachineInstr &MI)
static bool isSDWA(const MachineInstr &MI)
static bool isDOT(const MachineInstr &MI)
static bool usesTENSOR_CNT(const MachineInstr &MI)
static bool isSWMMAC(const MachineInstr &MI)
static bool isLDSDIR(const MachineInstr &MI)
static bool isVPermPk16(unsigned Opcode)
static bool isVALU(const MachineInstr &MI, bool AllowLDSDMA)
static bool isTRANS(const MachineInstr &MI)
static bool isMUBUF(const MachineInstr &MI)
static bool isWaitcnt(unsigned Opcode)
static bool isVOP3(const MCInstrDesc &Desc)
static bool isDPP(const MachineInstr &MI)
static bool isMFMA(const MachineInstr &MI)
static bool isMAI(const MCInstrDesc &Desc)
static bool isFPAtomic(const MachineInstr &MI)
static bool isMIMG(const MachineInstr &MI)
static unsigned getNumWaitStates(const MachineInstr &MI)
Return the number of wait states that result from executing this instruction.
static bool isVOP3P(const MachineInstr &MI)
static bool isWMMA(const MachineInstr &MI)
static bool isLDSDMA(const MachineInstr &MI)
Scheduling unit. This is a node in the scheduling DAG.
bool isInstr() const
Returns true if this SUnit refers to a machine instruction as opposed to an SDNode.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
unsigned MaxLookAhead
MaxLookAhead - Indicate the number of cycles in the scoreboard state.
virtual void EmitNoops(unsigned Quantity)
EmitNoops - This callback is invoked when noops were added to the instruction stream.
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:482
Provide an instruction scheduling machine model to CodeGen passes.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned encodeFieldVaVcc(unsigned Encoded, unsigned VaVcc)
unsigned encodeFieldVaVdst(unsigned Encoded, unsigned VaVdst)
unsigned decodeFieldSaSdst(unsigned Encoded)
unsigned decodeFieldVaSdst(unsigned Encoded)
unsigned encodeFieldVmVsrc(unsigned Encoded, unsigned VmVsrc)
unsigned encodeFieldSaSdst(unsigned Encoded, unsigned SaSdst)
unsigned decodeFieldVaVdst(unsigned Encoded)
unsigned decodeFieldVmVsrc(unsigned Encoded)
unsigned encodeFieldVaSdst(unsigned Encoded, unsigned VaSdst)
const char * getCoExecMaskName(CoExecMaskT Mask)
Return a human-readable name for a mask holding a single instruction class, as produced by getCoExecM...
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
constexpr unsigned MaxCoExecStages
Max stages: INT8 16x16x64 = 17 cycles, round up for safety.
bool isHi16Reg(MCRegister Reg, const MCRegisterInfo &MRI)
FPType getFPDstSelType(unsigned Opc)
bool isGFX12Plus(const MCSubtargetInfo &STI)
StringRef getSchedStrategy(const AMDGPUOptions &CLOpts, const Function &F)
const char * getStageTypeName(CoExecStageType T)
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
unsigned getRegBitWidth(unsigned RCID)
Get the size in bits of a register from the register class RC.
LLVM_READONLY int32_t getMFMAEarlyClobberOp(uint32_t Opcode)
CoExecMask CoExecMaskT
Waitcnt decodeWaitcnt(const IsaVersion &Version, unsigned Encoded)
CoExecInfo getCoExecInfo(const MachineInstr &MI, const SIInstrInfo &TII)
Get co-execution info for a WMMA instruction, selecting the per-cycle slot pattern from the opcode (a...
LLVM_READONLY bool hasNamedOperand(uint32_t Opcode, OpName NamedIdx)
LLVM_READONLY int32_t getAGPRFormOp(uint32_t Opcode)
InstructionFlavor classifyFlavor(const MachineInstr &MI, const SIInstrInfo &SII)
Classify MI into the execution flavor that drives both the scheduler's slot preferences and the hazar...
@ OPERAND_REG_IMM_NOINLINE_FP16
Definition SIDefines.h:438
@ OPERAND_REG_INLINE_C_BF16
Definition SIDefines.h:453
@ OPERAND_REG_IMM_BF16
Definition SIDefines.h:436
@ OPERAND_REG_IMM_FP16
Definition SIDefines.h:437
@ OPERAND_REG_INLINE_C_FP16
Definition SIDefines.h:454
CoExecMaskT getCoExecMask(InstructionFlavor F)
Map a flavor to the co-execution class it occupies in a window slot.
bool isGFX1250(const MCSubtargetInfo &STI)
@ Entry
Definition COFF.h:862
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
This namespace contains all of the command line option processing machinery.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
@ Define
Register definition.
@ Wait
Definition Threading.h:60
constexpr RegState getDeadRegState(bool B)
Op::Description Desc
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
IterT skipMetaInstructionsForward(IterT It, IterT End)
Increment It until it points to a non-meta instruction or to End and return the resulting iterator.
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IterT skipMetaInstructionsBackward(IterT It, IterT Begin)
Decrement It until it points to a non-meta instruction or to Begin and return the resulting iterator.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
#define N
Co-execution characteristics for a multi-cycle instruction.
static std::tuple< typename Fields::ValueType... > decode(uint64_t Encoded)
An information struct used to provide DenseMap with the various necessary components for a given valu...