xref: /llvm-project/llvm/lib/Target/AMDGPU/GCNHazardRecognizer.cpp (revision ba52f06f9d92c7ca04b440f618f8d352ea121fcc)
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 "GCNSubtarget.h"
15 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
16 #include "SIMachineFunctionInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/TargetParser/TargetParser.h"
20 
21 using namespace llvm;
22 
23 namespace {
24 
25 struct MFMAPaddingRatioParser : public cl::parser<unsigned> {
26   MFMAPaddingRatioParser(cl::Option &O) : cl::parser<unsigned>(O) {}
27 
28   bool parse(cl::Option &O, StringRef ArgName, StringRef Arg, unsigned &Value) {
29     if (Arg.getAsInteger(0, Value))
30       return O.error("'" + Arg + "' value invalid for uint argument!");
31 
32     if (Value > 100)
33       return O.error("'" + Arg + "' value must be in the range [0, 100]!");
34 
35     return false;
36   }
37 };
38 
39 } // end anonymous namespace
40 
41 static cl::opt<unsigned, false, MFMAPaddingRatioParser>
42     MFMAPaddingRatio("amdgpu-mfma-padding-ratio", cl::init(0), cl::Hidden,
43                      cl::desc("Fill a percentage of the latency between "
44                               "neighboring MFMA with s_nops."));
45 
46 //===----------------------------------------------------------------------===//
47 // Hazard Recognizer Implementation
48 //===----------------------------------------------------------------------===//
49 
50 static bool shouldRunLdsBranchVmemWARHazardFixup(const MachineFunction &MF,
51                                                  const GCNSubtarget &ST);
52 
53 GCNHazardRecognizer::GCNHazardRecognizer(const MachineFunction &MF) :
54   IsHazardRecognizerMode(false),
55   CurrCycleInstr(nullptr),
56   MF(MF),
57   ST(MF.getSubtarget<GCNSubtarget>()),
58   TII(*ST.getInstrInfo()),
59   TRI(TII.getRegisterInfo()),
60   ClauseUses(TRI.getNumRegUnits()),
61   ClauseDefs(TRI.getNumRegUnits()) {
62   MaxLookAhead = MF.getRegInfo().isPhysRegUsed(AMDGPU::AGPR0) ? 19 : 5;
63   TSchedModel.init(&ST);
64   RunLdsBranchVmemWARHazardFixup = shouldRunLdsBranchVmemWARHazardFixup(MF, ST);
65 }
66 
67 void GCNHazardRecognizer::Reset() {
68   EmittedInstrs.clear();
69 }
70 
71 void GCNHazardRecognizer::EmitInstruction(SUnit *SU) {
72   EmitInstruction(SU->getInstr());
73 }
74 
75 void GCNHazardRecognizer::EmitInstruction(MachineInstr *MI) {
76   CurrCycleInstr = MI;
77 }
78 
79 static bool isDivFMas(unsigned Opcode) {
80   return Opcode == AMDGPU::V_DIV_FMAS_F32_e64 || Opcode == AMDGPU::V_DIV_FMAS_F64_e64;
81 }
82 
83 static bool isSGetReg(unsigned Opcode) {
84   return Opcode == AMDGPU::S_GETREG_B32;
85 }
86 
87 static bool isSSetReg(unsigned Opcode) {
88   switch (Opcode) {
89   case AMDGPU::S_SETREG_B32:
90   case AMDGPU::S_SETREG_B32_mode:
91   case AMDGPU::S_SETREG_IMM32_B32:
92   case AMDGPU::S_SETREG_IMM32_B32_mode:
93     return true;
94   }
95   return false;
96 }
97 
98 static bool isRWLane(unsigned Opcode) {
99   return Opcode == AMDGPU::V_READLANE_B32 || Opcode == AMDGPU::V_WRITELANE_B32;
100 }
101 
102 static bool isRFE(unsigned Opcode) {
103   return Opcode == AMDGPU::S_RFE_B64;
104 }
105 
106 static bool isSMovRel(unsigned Opcode) {
107   switch (Opcode) {
108   case AMDGPU::S_MOVRELS_B32:
109   case AMDGPU::S_MOVRELS_B64:
110   case AMDGPU::S_MOVRELD_B32:
111   case AMDGPU::S_MOVRELD_B64:
112     return true;
113   default:
114     return false;
115   }
116 }
117 
118 static bool isDGEMM(unsigned Opcode) {
119   return AMDGPU::getMAIIsDGEMM(Opcode);
120 }
121 
122 static bool isXDL(const GCNSubtarget &ST, const MachineInstr &MI) {
123   unsigned Opcode = MI.getOpcode();
124 
125   if (!SIInstrInfo::isMAI(MI) ||
126       isDGEMM(Opcode) ||
127       Opcode == AMDGPU::V_ACCVGPR_WRITE_B32_e64 ||
128       Opcode == AMDGPU::V_ACCVGPR_READ_B32_e64)
129     return false;
130 
131   if (!ST.hasGFX940Insts())
132     return true;
133 
134   return AMDGPU::getMAIIsGFX940XDL(Opcode);
135 }
136 
137 static bool isSendMsgTraceDataOrGDS(const SIInstrInfo &TII,
138                                     const MachineInstr &MI) {
139   if (TII.isAlwaysGDS(MI.getOpcode()))
140     return true;
141 
142   switch (MI.getOpcode()) {
143   case AMDGPU::S_SENDMSG:
144   case AMDGPU::S_SENDMSGHALT:
145   case AMDGPU::S_TTRACEDATA:
146     return true;
147   // These DS opcodes don't support GDS.
148   case AMDGPU::DS_NOP:
149   case AMDGPU::DS_PERMUTE_B32:
150   case AMDGPU::DS_BPERMUTE_B32:
151     return false;
152   default:
153     if (TII.isDS(MI.getOpcode())) {
154       int GDS = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
155                                            AMDGPU::OpName::gds);
156       if (MI.getOperand(GDS).getImm())
157         return true;
158     }
159     return false;
160   }
161 }
162 
163 static bool isPermlane(const MachineInstr &MI) {
164   unsigned Opcode = MI.getOpcode();
165   return Opcode == AMDGPU::V_PERMLANE16_B32_e64 ||
166          Opcode == AMDGPU::V_PERMLANEX16_B32_e64 ||
167          Opcode == AMDGPU::V_PERMLANE16_VAR_B32_e64 ||
168          Opcode == AMDGPU::V_PERMLANEX16_VAR_B32_e64;
169 }
170 
171 static bool isLdsDma(const MachineInstr &MI) {
172   return SIInstrInfo::isVALU(MI) &&
173          (SIInstrInfo::isMUBUF(MI) || SIInstrInfo::isFLAT(MI));
174 }
175 
176 static unsigned getHWReg(const SIInstrInfo *TII, const MachineInstr &RegInstr) {
177   const MachineOperand *RegOp = TII->getNamedOperand(RegInstr,
178                                                      AMDGPU::OpName::simm16);
179   return RegOp->getImm() & AMDGPU::Hwreg::ID_MASK_;
180 }
181 
182 ScheduleHazardRecognizer::HazardType
183 GCNHazardRecognizer::getHazardType(SUnit *SU, int Stalls) {
184   MachineInstr *MI = SU->getInstr();
185   // If we are not in "HazardRecognizerMode" and therefore not being run from
186   // the scheduler, track possible stalls from hazards but don't insert noops.
187   auto HazardType = IsHazardRecognizerMode ? NoopHazard : Hazard;
188 
189   if (MI->isBundle())
190    return NoHazard;
191 
192   if (SIInstrInfo::isSMRD(*MI) && checkSMRDHazards(MI) > 0)
193     return HazardType;
194 
195   if (ST.hasNSAtoVMEMBug() && checkNSAtoVMEMHazard(MI) > 0)
196     return HazardType;
197 
198   if (checkFPAtomicToDenormModeHazard(MI) > 0)
199     return HazardType;
200 
201   if (ST.hasNoDataDepHazard())
202     return NoHazard;
203 
204   // FIXME: Should flat be considered vmem?
205   if ((SIInstrInfo::isVMEM(*MI) ||
206        SIInstrInfo::isFLAT(*MI))
207       && checkVMEMHazards(MI) > 0)
208     return HazardType;
209 
210   if (SIInstrInfo::isVALU(*MI) && checkVALUHazards(MI) > 0)
211     return HazardType;
212 
213   if (SIInstrInfo::isDPP(*MI) && checkDPPHazards(MI) > 0)
214     return HazardType;
215 
216   if (isDivFMas(MI->getOpcode()) && checkDivFMasHazards(MI) > 0)
217     return HazardType;
218 
219   if (isRWLane(MI->getOpcode()) && checkRWLaneHazards(MI) > 0)
220     return HazardType;
221 
222   if ((SIInstrInfo::isVALU(*MI) || SIInstrInfo::isVMEM(*MI) ||
223        SIInstrInfo::isFLAT(*MI) || SIInstrInfo::isDS(*MI) ||
224        SIInstrInfo::isEXP(*MI)) && checkMAIVALUHazards(MI) > 0)
225     return HazardType;
226 
227   if (isSGetReg(MI->getOpcode()) && checkGetRegHazards(MI) > 0)
228     return HazardType;
229 
230   if (isSSetReg(MI->getOpcode()) && checkSetRegHazards(MI) > 0)
231     return HazardType;
232 
233   if (isRFE(MI->getOpcode()) && checkRFEHazards(MI) > 0)
234     return HazardType;
235 
236   if (((ST.hasReadM0MovRelInterpHazard() &&
237         (TII.isVINTRP(*MI) || isSMovRel(MI->getOpcode()) ||
238          MI->getOpcode() == AMDGPU::DS_WRITE_ADDTID_B32 ||
239          MI->getOpcode() == AMDGPU::DS_READ_ADDTID_B32)) ||
240        (ST.hasReadM0SendMsgHazard() && isSendMsgTraceDataOrGDS(TII, *MI)) ||
241        (ST.hasReadM0LdsDmaHazard() && isLdsDma(*MI)) ||
242        (ST.hasReadM0LdsDirectHazard() &&
243         MI->readsRegister(AMDGPU::LDS_DIRECT))) &&
244       checkReadM0Hazards(MI) > 0)
245     return HazardType;
246 
247   if (SIInstrInfo::isMAI(*MI) && checkMAIHazards(MI) > 0)
248     return HazardType;
249 
250   if ((SIInstrInfo::isVMEM(*MI) ||
251        SIInstrInfo::isFLAT(*MI) ||
252        SIInstrInfo::isDS(*MI)) && checkMAILdStHazards(MI) > 0)
253     return HazardType;
254 
255   if (MI->isInlineAsm() && checkInlineAsmHazards(MI) > 0)
256     return HazardType;
257 
258   return NoHazard;
259 }
260 
261 static void insertNoopsInBundle(MachineInstr *MI, const SIInstrInfo &TII,
262                                 unsigned Quantity) {
263   while (Quantity > 0) {
264     unsigned Arg = std::min(Quantity, 8u);
265     Quantity -= Arg;
266     BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII.get(AMDGPU::S_NOP))
267         .addImm(Arg - 1);
268   }
269 }
270 
271 unsigned
272 GCNHazardRecognizer::getMFMAPipelineWaitStates(const MachineInstr &MI) const {
273   const MCSchedClassDesc *SC = TSchedModel.resolveSchedClass(&MI);
274   assert(TSchedModel.getWriteProcResBegin(SC) !=
275          TSchedModel.getWriteProcResEnd(SC));
276   return TSchedModel.getWriteProcResBegin(SC)->ReleaseAtCycle;
277 }
278 
279 void GCNHazardRecognizer::processBundle() {
280   MachineBasicBlock::instr_iterator MI = std::next(CurrCycleInstr->getIterator());
281   MachineBasicBlock::instr_iterator E = CurrCycleInstr->getParent()->instr_end();
282   // Check bundled MachineInstr's for hazards.
283   for (; MI != E && MI->isInsideBundle(); ++MI) {
284     CurrCycleInstr = &*MI;
285     unsigned WaitStates = PreEmitNoopsCommon(CurrCycleInstr);
286 
287     if (IsHazardRecognizerMode) {
288       fixHazards(CurrCycleInstr);
289 
290       insertNoopsInBundle(CurrCycleInstr, TII, WaitStates);
291     }
292 
293     // It’s unnecessary to track more than MaxLookAhead instructions. Since we
294     // include the bundled MI directly after, only add a maximum of
295     // (MaxLookAhead - 1) noops to EmittedInstrs.
296     for (unsigned i = 0, e = std::min(WaitStates, MaxLookAhead - 1); i < e; ++i)
297       EmittedInstrs.push_front(nullptr);
298 
299     EmittedInstrs.push_front(CurrCycleInstr);
300     EmittedInstrs.resize(MaxLookAhead);
301   }
302   CurrCycleInstr = nullptr;
303 }
304 
305 void GCNHazardRecognizer::runOnInstruction(MachineInstr *MI) {
306   assert(IsHazardRecognizerMode);
307 
308   unsigned NumPreNoops = PreEmitNoops(MI);
309   EmitNoops(NumPreNoops);
310   if (MI->isInsideBundle())
311     insertNoopsInBundle(MI, TII, NumPreNoops);
312   else
313     TII.insertNoops(*MI->getParent(), MachineBasicBlock::iterator(MI),
314                     NumPreNoops);
315   EmitInstruction(MI);
316   AdvanceCycle();
317 }
318 
319 unsigned GCNHazardRecognizer::PreEmitNoops(MachineInstr *MI) {
320   IsHazardRecognizerMode = true;
321   CurrCycleInstr = MI;
322   unsigned W = PreEmitNoopsCommon(MI);
323   fixHazards(MI);
324   CurrCycleInstr = nullptr;
325   return W;
326 }
327 
328 unsigned GCNHazardRecognizer::PreEmitNoopsCommon(MachineInstr *MI) {
329   if (MI->isBundle())
330     return 0;
331 
332   int WaitStates = 0;
333 
334   if (SIInstrInfo::isSMRD(*MI))
335     return std::max(WaitStates, checkSMRDHazards(MI));
336 
337   if (ST.hasNSAtoVMEMBug())
338     WaitStates = std::max(WaitStates, checkNSAtoVMEMHazard(MI));
339 
340   WaitStates = std::max(WaitStates, checkFPAtomicToDenormModeHazard(MI));
341 
342   if (ST.hasNoDataDepHazard())
343     return WaitStates;
344 
345   if (SIInstrInfo::isVMEM(*MI) || SIInstrInfo::isFLAT(*MI))
346     WaitStates = std::max(WaitStates, checkVMEMHazards(MI));
347 
348   if (SIInstrInfo::isVALU(*MI))
349     WaitStates = std::max(WaitStates, checkVALUHazards(MI));
350 
351   if (SIInstrInfo::isDPP(*MI))
352     WaitStates = std::max(WaitStates, checkDPPHazards(MI));
353 
354   if (isDivFMas(MI->getOpcode()))
355     WaitStates = std::max(WaitStates, checkDivFMasHazards(MI));
356 
357   if (isRWLane(MI->getOpcode()))
358     WaitStates = std::max(WaitStates, checkRWLaneHazards(MI));
359 
360   if ((SIInstrInfo::isVALU(*MI) || SIInstrInfo::isVMEM(*MI) ||
361        SIInstrInfo::isFLAT(*MI) || SIInstrInfo::isDS(*MI) ||
362        SIInstrInfo::isEXP(*MI)) && checkMAIVALUHazards(MI) > 0)
363     WaitStates = std::max(WaitStates, checkMAIVALUHazards(MI));
364 
365   if (MI->isInlineAsm())
366     return std::max(WaitStates, checkInlineAsmHazards(MI));
367 
368   if (isSGetReg(MI->getOpcode()))
369     return std::max(WaitStates, checkGetRegHazards(MI));
370 
371   if (isSSetReg(MI->getOpcode()))
372     return std::max(WaitStates, checkSetRegHazards(MI));
373 
374   if (isRFE(MI->getOpcode()))
375     return std::max(WaitStates, checkRFEHazards(MI));
376 
377   if ((ST.hasReadM0MovRelInterpHazard() &&
378        (TII.isVINTRP(*MI) || isSMovRel(MI->getOpcode()) ||
379         MI->getOpcode() == AMDGPU::DS_WRITE_ADDTID_B32 ||
380         MI->getOpcode() == AMDGPU::DS_READ_ADDTID_B32)) ||
381       (ST.hasReadM0SendMsgHazard() && isSendMsgTraceDataOrGDS(TII, *MI)) ||
382       (ST.hasReadM0LdsDmaHazard() && isLdsDma(*MI)) ||
383       (ST.hasReadM0LdsDirectHazard() && MI->readsRegister(AMDGPU::LDS_DIRECT)))
384     return std::max(WaitStates, checkReadM0Hazards(MI));
385 
386   if (SIInstrInfo::isMAI(*MI))
387     return std::max(WaitStates, checkMAIHazards(MI));
388 
389   if (SIInstrInfo::isVMEM(*MI) ||
390       SIInstrInfo::isFLAT(*MI) ||
391       SIInstrInfo::isDS(*MI))
392     return std::max(WaitStates, checkMAILdStHazards(MI));
393 
394   return WaitStates;
395 }
396 
397 void GCNHazardRecognizer::EmitNoop() {
398   EmittedInstrs.push_front(nullptr);
399 }
400 
401 void GCNHazardRecognizer::AdvanceCycle() {
402   // When the scheduler detects a stall, it will call AdvanceCycle() without
403   // emitting any instructions.
404   if (!CurrCycleInstr) {
405     EmittedInstrs.push_front(nullptr);
406     return;
407   }
408 
409   if (CurrCycleInstr->isBundle()) {
410     processBundle();
411     return;
412   }
413 
414   unsigned NumWaitStates = TII.getNumWaitStates(*CurrCycleInstr);
415   if (!NumWaitStates) {
416     CurrCycleInstr = nullptr;
417     return;
418   }
419 
420   // Keep track of emitted instructions
421   EmittedInstrs.push_front(CurrCycleInstr);
422 
423   // Add a nullptr for each additional wait state after the first.  Make sure
424   // not to add more than getMaxLookAhead() items to the list, since we
425   // truncate the list to that size right after this loop.
426   for (unsigned i = 1, e = std::min(NumWaitStates, getMaxLookAhead());
427        i < e; ++i) {
428     EmittedInstrs.push_front(nullptr);
429   }
430 
431   // getMaxLookahead() is the largest number of wait states we will ever need
432   // to insert, so there is no point in keeping track of more than that many
433   // wait states.
434   EmittedInstrs.resize(getMaxLookAhead());
435 
436   CurrCycleInstr = nullptr;
437 }
438 
439 void GCNHazardRecognizer::RecedeCycle() {
440   llvm_unreachable("hazard recognizer does not support bottom-up scheduling.");
441 }
442 
443 //===----------------------------------------------------------------------===//
444 // Helper Functions
445 //===----------------------------------------------------------------------===//
446 
447 typedef enum { HazardFound, HazardExpired, NoHazardFound } HazardFnResult;
448 
449 typedef function_ref<bool(const MachineInstr &, int WaitStates)> IsExpiredFn;
450 typedef function_ref<unsigned int(const MachineInstr &)> GetNumWaitStatesFn;
451 
452 // Search for a hazard in a block and its predecessors.
453 template <typename StateT>
454 static bool
455 hasHazard(StateT State,
456           function_ref<HazardFnResult(StateT &, const MachineInstr &)> IsHazard,
457           function_ref<void(StateT &, const MachineInstr &)> UpdateState,
458           const MachineBasicBlock *MBB,
459           MachineBasicBlock::const_reverse_instr_iterator I,
460           DenseSet<const MachineBasicBlock *> &Visited) {
461   for (auto E = MBB->instr_rend(); I != E; ++I) {
462     // No need to look at parent BUNDLE instructions.
463     if (I->isBundle())
464       continue;
465 
466     switch (IsHazard(State, *I)) {
467     case HazardFound:
468       return true;
469     case HazardExpired:
470       return false;
471     default:
472       // Continue search
473       break;
474     }
475 
476     if (I->isInlineAsm() || I->isMetaInstruction())
477       continue;
478 
479     UpdateState(State, *I);
480   }
481 
482   for (MachineBasicBlock *Pred : MBB->predecessors()) {
483     if (!Visited.insert(Pred).second)
484       continue;
485 
486     if (hasHazard(State, IsHazard, UpdateState, Pred, Pred->instr_rbegin(),
487                   Visited))
488       return true;
489   }
490 
491   return false;
492 }
493 
494 // Returns a minimum wait states since \p I walking all predecessors.
495 // Only scans until \p IsExpired does not return true.
496 // Can only be run in a hazard recognizer mode.
497 static int getWaitStatesSince(
498     GCNHazardRecognizer::IsHazardFn IsHazard, const MachineBasicBlock *MBB,
499     MachineBasicBlock::const_reverse_instr_iterator I, int WaitStates,
500     IsExpiredFn IsExpired, DenseSet<const MachineBasicBlock *> &Visited,
501     GetNumWaitStatesFn GetNumWaitStates = SIInstrInfo::getNumWaitStates) {
502   for (auto E = MBB->instr_rend(); I != E; ++I) {
503     // Don't add WaitStates for parent BUNDLE instructions.
504     if (I->isBundle())
505       continue;
506 
507     if (IsHazard(*I))
508       return WaitStates;
509 
510     if (I->isInlineAsm())
511       continue;
512 
513     WaitStates += GetNumWaitStates(*I);
514 
515     if (IsExpired(*I, WaitStates))
516       return std::numeric_limits<int>::max();
517   }
518 
519   int MinWaitStates = std::numeric_limits<int>::max();
520   for (MachineBasicBlock *Pred : MBB->predecessors()) {
521     if (!Visited.insert(Pred).second)
522       continue;
523 
524     int W = getWaitStatesSince(IsHazard, Pred, Pred->instr_rbegin(), WaitStates,
525                                IsExpired, Visited, GetNumWaitStates);
526 
527     MinWaitStates = std::min(MinWaitStates, W);
528   }
529 
530   return MinWaitStates;
531 }
532 
533 static int getWaitStatesSince(GCNHazardRecognizer::IsHazardFn IsHazard,
534                               const MachineInstr *MI, IsExpiredFn IsExpired) {
535   DenseSet<const MachineBasicBlock *> Visited;
536   return getWaitStatesSince(IsHazard, MI->getParent(),
537                             std::next(MI->getReverseIterator()),
538                             0, IsExpired, Visited);
539 }
540 
541 int GCNHazardRecognizer::getWaitStatesSince(IsHazardFn IsHazard, int Limit) {
542   if (IsHazardRecognizerMode) {
543     auto IsExpiredFn = [Limit](const MachineInstr &, int WaitStates) {
544       return WaitStates >= Limit;
545     };
546     return ::getWaitStatesSince(IsHazard, CurrCycleInstr, IsExpiredFn);
547   }
548 
549   int WaitStates = 0;
550   for (MachineInstr *MI : EmittedInstrs) {
551     if (MI) {
552       if (IsHazard(*MI))
553         return WaitStates;
554 
555       if (MI->isInlineAsm())
556         continue;
557     }
558     ++WaitStates;
559 
560     if (WaitStates >= Limit)
561       break;
562   }
563   return std::numeric_limits<int>::max();
564 }
565 
566 int GCNHazardRecognizer::getWaitStatesSinceDef(unsigned Reg,
567                                                IsHazardFn IsHazardDef,
568                                                int Limit) {
569   const SIRegisterInfo *TRI = ST.getRegisterInfo();
570 
571   auto IsHazardFn = [IsHazardDef, TRI, Reg](const MachineInstr &MI) {
572     return IsHazardDef(MI) && MI.modifiesRegister(Reg, TRI);
573   };
574 
575   return getWaitStatesSince(IsHazardFn, Limit);
576 }
577 
578 int GCNHazardRecognizer::getWaitStatesSinceSetReg(IsHazardFn IsHazard,
579                                                   int Limit) {
580   auto IsHazardFn = [IsHazard](const MachineInstr &MI) {
581     return isSSetReg(MI.getOpcode()) && IsHazard(MI);
582   };
583 
584   return getWaitStatesSince(IsHazardFn, Limit);
585 }
586 
587 //===----------------------------------------------------------------------===//
588 // No-op Hazard Detection
589 //===----------------------------------------------------------------------===//
590 
591 static void addRegUnits(const SIRegisterInfo &TRI, BitVector &BV,
592                         MCRegister Reg) {
593   for (MCRegUnit Unit : TRI.regunits(Reg))
594     BV.set(Unit);
595 }
596 
597 static void addRegsToSet(const SIRegisterInfo &TRI,
598                          iterator_range<MachineInstr::const_mop_iterator> Ops,
599                          BitVector &DefSet, BitVector &UseSet) {
600   for (const MachineOperand &Op : Ops) {
601     if (Op.isReg())
602       addRegUnits(TRI, Op.isDef() ? DefSet : UseSet, Op.getReg().asMCReg());
603   }
604 }
605 
606 void GCNHazardRecognizer::addClauseInst(const MachineInstr &MI) {
607   addRegsToSet(TRI, MI.operands(), ClauseDefs, ClauseUses);
608 }
609 
610 static bool breaksSMEMSoftClause(MachineInstr *MI) {
611   return !SIInstrInfo::isSMRD(*MI);
612 }
613 
614 static bool breaksVMEMSoftClause(MachineInstr *MI) {
615   return !SIInstrInfo::isVMEM(*MI) && !SIInstrInfo::isFLAT(*MI);
616 }
617 
618 int GCNHazardRecognizer::checkSoftClauseHazards(MachineInstr *MEM) {
619   // SMEM soft clause are only present on VI+, and only matter if xnack is
620   // enabled.
621   if (!ST.isXNACKEnabled())
622     return 0;
623 
624   bool IsSMRD = TII.isSMRD(*MEM);
625 
626   resetClause();
627 
628   // A soft-clause is any group of consecutive SMEM instructions.  The
629   // instructions in this group may return out of order and/or may be
630   // replayed (i.e. the same instruction issued more than once).
631   //
632   // In order to handle these situations correctly we need to make sure that
633   // when a clause has more than one instruction, no instruction in the clause
634   // writes to a register that is read by another instruction in the clause
635   // (including itself). If we encounter this situation, we need to break the
636   // clause by inserting a non SMEM instruction.
637 
638   for (MachineInstr *MI : EmittedInstrs) {
639     // When we hit a non-SMEM instruction then we have passed the start of the
640     // clause and we can stop.
641     if (!MI)
642       break;
643 
644     if (IsSMRD ? breaksSMEMSoftClause(MI) : breaksVMEMSoftClause(MI))
645       break;
646 
647     addClauseInst(*MI);
648   }
649 
650   if (ClauseDefs.none())
651     return 0;
652 
653   // We need to make sure not to put loads and stores in the same clause if they
654   // use the same address. For now, just start a new clause whenever we see a
655   // store.
656   if (MEM->mayStore())
657     return 1;
658 
659   addClauseInst(*MEM);
660 
661   // If the set of defs and uses intersect then we cannot add this instruction
662   // to the clause, so we have a hazard.
663   return ClauseDefs.anyCommon(ClauseUses) ? 1 : 0;
664 }
665 
666 int GCNHazardRecognizer::checkSMRDHazards(MachineInstr *SMRD) {
667   int WaitStatesNeeded = 0;
668 
669   WaitStatesNeeded = checkSoftClauseHazards(SMRD);
670 
671   // This SMRD hazard only affects SI.
672   if (!ST.hasSMRDReadVALUDefHazard())
673     return WaitStatesNeeded;
674 
675   // A read of an SGPR by SMRD instruction requires 4 wait states when the
676   // SGPR was written by a VALU instruction.
677   int SmrdSgprWaitStates = 4;
678   auto IsHazardDefFn = [this](const MachineInstr &MI) {
679     return TII.isVALU(MI);
680   };
681   auto IsBufferHazardDefFn = [this](const MachineInstr &MI) {
682     return TII.isSALU(MI);
683   };
684 
685   bool IsBufferSMRD = TII.isBufferSMRD(*SMRD);
686 
687   for (const MachineOperand &Use : SMRD->uses()) {
688     if (!Use.isReg())
689       continue;
690     int WaitStatesNeededForUse =
691         SmrdSgprWaitStates - getWaitStatesSinceDef(Use.getReg(), IsHazardDefFn,
692                                                    SmrdSgprWaitStates);
693     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
694 
695     // This fixes what appears to be undocumented hardware behavior in SI where
696     // s_mov writing a descriptor and s_buffer_load_dword reading the descriptor
697     // needs some number of nops in between. We don't know how many we need, but
698     // let's use 4. This wasn't discovered before probably because the only
699     // case when this happens is when we expand a 64-bit pointer into a full
700     // descriptor and use s_buffer_load_dword instead of s_load_dword, which was
701     // probably never encountered in the closed-source land.
702     if (IsBufferSMRD) {
703       int WaitStatesNeededForUse =
704         SmrdSgprWaitStates - getWaitStatesSinceDef(Use.getReg(),
705                                                    IsBufferHazardDefFn,
706                                                    SmrdSgprWaitStates);
707       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
708     }
709   }
710 
711   return WaitStatesNeeded;
712 }
713 
714 int GCNHazardRecognizer::checkVMEMHazards(MachineInstr* VMEM) {
715   if (!ST.hasVMEMReadSGPRVALUDefHazard())
716     return 0;
717 
718   int WaitStatesNeeded = checkSoftClauseHazards(VMEM);
719 
720   // A read of an SGPR by a VMEM instruction requires 5 wait states when the
721   // SGPR was written by a VALU Instruction.
722   const int VmemSgprWaitStates = 5;
723   auto IsHazardDefFn = [this](const MachineInstr &MI) {
724     return TII.isVALU(MI);
725   };
726   for (const MachineOperand &Use : VMEM->uses()) {
727     if (!Use.isReg() || TRI.isVectorRegister(MF.getRegInfo(), Use.getReg()))
728       continue;
729 
730     int WaitStatesNeededForUse =
731         VmemSgprWaitStates - getWaitStatesSinceDef(Use.getReg(), IsHazardDefFn,
732                                                    VmemSgprWaitStates);
733     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
734   }
735   return WaitStatesNeeded;
736 }
737 
738 int GCNHazardRecognizer::checkDPPHazards(MachineInstr *DPP) {
739   const SIRegisterInfo *TRI = ST.getRegisterInfo();
740   const SIInstrInfo *TII = ST.getInstrInfo();
741 
742   // Check for DPP VGPR read after VALU VGPR write and EXEC write.
743   int DppVgprWaitStates = 2;
744   int DppExecWaitStates = 5;
745   int WaitStatesNeeded = 0;
746   auto IsHazardDefFn = [TII](const MachineInstr &MI) {
747     return TII->isVALU(MI);
748   };
749 
750   for (const MachineOperand &Use : DPP->uses()) {
751     if (!Use.isReg() || !TRI->isVGPR(MF.getRegInfo(), Use.getReg()))
752       continue;
753     int WaitStatesNeededForUse =
754         DppVgprWaitStates - getWaitStatesSinceDef(
755                                 Use.getReg(),
756                                 [](const MachineInstr &) { return true; },
757                                 DppVgprWaitStates);
758     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
759   }
760 
761   WaitStatesNeeded = std::max(
762       WaitStatesNeeded,
763       DppExecWaitStates - getWaitStatesSinceDef(AMDGPU::EXEC, IsHazardDefFn,
764                                                 DppExecWaitStates));
765 
766   return WaitStatesNeeded;
767 }
768 
769 int GCNHazardRecognizer::checkDivFMasHazards(MachineInstr *DivFMas) {
770   const SIInstrInfo *TII = ST.getInstrInfo();
771 
772   // v_div_fmas requires 4 wait states after a write to vcc from a VALU
773   // instruction.
774   const int DivFMasWaitStates = 4;
775   auto IsHazardDefFn = [TII](const MachineInstr &MI) {
776     return TII->isVALU(MI);
777   };
778   int WaitStatesNeeded = getWaitStatesSinceDef(AMDGPU::VCC, IsHazardDefFn,
779                                                DivFMasWaitStates);
780 
781   return DivFMasWaitStates - WaitStatesNeeded;
782 }
783 
784 int GCNHazardRecognizer::checkGetRegHazards(MachineInstr *GetRegInstr) {
785   const SIInstrInfo *TII = ST.getInstrInfo();
786   unsigned GetRegHWReg = getHWReg(TII, *GetRegInstr);
787 
788   const int GetRegWaitStates = 2;
789   auto IsHazardFn = [TII, GetRegHWReg](const MachineInstr &MI) {
790     return GetRegHWReg == getHWReg(TII, MI);
791   };
792   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, GetRegWaitStates);
793 
794   return GetRegWaitStates - WaitStatesNeeded;
795 }
796 
797 int GCNHazardRecognizer::checkSetRegHazards(MachineInstr *SetRegInstr) {
798   const SIInstrInfo *TII = ST.getInstrInfo();
799   unsigned HWReg = getHWReg(TII, *SetRegInstr);
800 
801   const int SetRegWaitStates = ST.getSetRegWaitStates();
802   auto IsHazardFn = [TII, HWReg](const MachineInstr &MI) {
803     return HWReg == getHWReg(TII, MI);
804   };
805   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, SetRegWaitStates);
806   return SetRegWaitStates - WaitStatesNeeded;
807 }
808 
809 int GCNHazardRecognizer::createsVALUHazard(const MachineInstr &MI) {
810   if (!MI.mayStore())
811     return -1;
812 
813   const SIInstrInfo *TII = ST.getInstrInfo();
814   unsigned Opcode = MI.getOpcode();
815   const MCInstrDesc &Desc = MI.getDesc();
816 
817   int VDataIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
818   int VDataRCID = -1;
819   if (VDataIdx != -1)
820     VDataRCID = Desc.operands()[VDataIdx].RegClass;
821 
822   if (TII->isMUBUF(MI) || TII->isMTBUF(MI)) {
823     // There is no hazard if the instruction does not use vector regs
824     // (like wbinvl1)
825     if (VDataIdx == -1)
826       return -1;
827     // For MUBUF/MTBUF instructions this hazard only exists if the
828     // instruction is not using a register in the soffset field.
829     const MachineOperand *SOffset =
830         TII->getNamedOperand(MI, AMDGPU::OpName::soffset);
831     // If we have no soffset operand, then assume this field has been
832     // hardcoded to zero.
833     if (AMDGPU::getRegBitWidth(VDataRCID) > 64 &&
834         (!SOffset || !SOffset->isReg()))
835       return VDataIdx;
836   }
837 
838   // MIMG instructions create a hazard if they don't use a 256-bit T# and
839   // the store size is greater than 8 bytes and they have more than two bits
840   // of their dmask set.
841   // All our MIMG definitions use a 256-bit T#, so we can skip checking for them.
842   if (TII->isMIMG(MI)) {
843     int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
844     assert(SRsrcIdx != -1 &&
845            AMDGPU::getRegBitWidth(Desc.operands()[SRsrcIdx].RegClass) == 256);
846     (void)SRsrcIdx;
847   }
848 
849   if (TII->isFLAT(MI)) {
850     int DataIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
851     if (AMDGPU::getRegBitWidth(Desc.operands()[DataIdx].RegClass) > 64)
852       return DataIdx;
853   }
854 
855   return -1;
856 }
857 
858 int
859 GCNHazardRecognizer::checkVALUHazardsHelper(const MachineOperand &Def,
860                                             const MachineRegisterInfo &MRI) {
861   // Helper to check for the hazard where VMEM instructions that store more than
862   // 8 bytes can have there store data over written by the next instruction.
863   const SIRegisterInfo *TRI = ST.getRegisterInfo();
864 
865   const int VALUWaitStates = ST.hasGFX940Insts() ? 2 : 1;
866   int WaitStatesNeeded = 0;
867 
868   if (!TRI->isVectorRegister(MRI, Def.getReg()))
869     return WaitStatesNeeded;
870   Register Reg = Def.getReg();
871   auto IsHazardFn = [this, Reg, TRI](const MachineInstr &MI) {
872     int DataIdx = createsVALUHazard(MI);
873     return DataIdx >= 0 &&
874            TRI->regsOverlap(MI.getOperand(DataIdx).getReg(), Reg);
875   };
876   int WaitStatesNeededForDef =
877     VALUWaitStates - getWaitStatesSince(IsHazardFn, VALUWaitStates);
878   WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
879 
880   return WaitStatesNeeded;
881 }
882 
883 int GCNHazardRecognizer::checkVALUHazards(MachineInstr *VALU) {
884   int WaitStatesNeeded = 0;
885 
886   if (ST.hasTransForwardingHazard() && !SIInstrInfo::isTRANS(*VALU)) {
887     const int TransDefWaitstates = 1;
888 
889     auto IsTransDefFn = [this, VALU](const MachineInstr &MI) {
890       if (!SIInstrInfo::isTRANS(MI))
891         return false;
892       const SIRegisterInfo *TRI = ST.getRegisterInfo();
893       const SIInstrInfo *TII = ST.getInstrInfo();
894       Register Def = TII->getNamedOperand(MI, AMDGPU::OpName::vdst)->getReg();
895 
896       for (const MachineOperand &Use : VALU->explicit_uses()) {
897         if (Use.isReg() && TRI->regsOverlap(Def, Use.getReg()))
898           return true;
899       }
900 
901       return false;
902     };
903 
904     int WaitStatesNeededForDef =
905         TransDefWaitstates -
906         getWaitStatesSince(IsTransDefFn, TransDefWaitstates);
907     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
908   }
909 
910   if (ST.hasDstSelForwardingHazard()) {
911     const int Shift16DefWaitstates = 1;
912 
913     auto IsShift16BitDefFn = [this, VALU](const MachineInstr &MI) {
914       if (!SIInstrInfo::isVALU(MI))
915         return false;
916       const SIInstrInfo *TII = ST.getInstrInfo();
917       if (SIInstrInfo::isSDWA(MI)) {
918         if (auto *DstSel = TII->getNamedOperand(MI, AMDGPU::OpName::dst_sel))
919           if (DstSel->getImm() == AMDGPU::SDWA::DWORD)
920             return false;
921       } else {
922         if (!AMDGPU::hasNamedOperand(MI.getOpcode(), AMDGPU::OpName::op_sel) ||
923             !(TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)
924                   ->getImm() &
925               SISrcMods::DST_OP_SEL))
926           return false;
927       }
928       const SIRegisterInfo *TRI = ST.getRegisterInfo();
929       if (auto *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst)) {
930         Register Def = Dst->getReg();
931 
932         for (const MachineOperand &Use : VALU->explicit_uses()) {
933           if (Use.isReg() && TRI->regsOverlap(Def, Use.getReg()))
934             return true;
935         }
936       }
937 
938       return false;
939     };
940 
941     int WaitStatesNeededForDef =
942         Shift16DefWaitstates -
943         getWaitStatesSince(IsShift16BitDefFn, Shift16DefWaitstates);
944     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
945   }
946 
947   if (ST.hasVDecCoExecHazard()) {
948     const int VALUWriteSGPRVALUReadWaitstates = 2;
949     const int VALUWriteEXECRWLane = 4;
950     const int VALUWriteVGPRReadlaneRead = 1;
951 
952     const SIRegisterInfo *TRI = ST.getRegisterInfo();
953     const MachineRegisterInfo &MRI = MF.getRegInfo();
954     Register UseReg;
955     auto IsVALUDefSGPRFn = [&UseReg, TRI](const MachineInstr &MI) {
956       if (!SIInstrInfo::isVALU(MI))
957         return false;
958       return MI.modifiesRegister(UseReg, TRI);
959     };
960 
961     for (const MachineOperand &Use : VALU->explicit_uses()) {
962       if (!Use.isReg())
963         continue;
964 
965       UseReg = Use.getReg();
966       if (TRI->isSGPRReg(MRI, UseReg)) {
967         int WaitStatesNeededForDef =
968             VALUWriteSGPRVALUReadWaitstates -
969             getWaitStatesSince(IsVALUDefSGPRFn,
970                                VALUWriteSGPRVALUReadWaitstates);
971         WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
972       }
973     }
974 
975     if (VALU->readsRegister(AMDGPU::VCC, TRI)) {
976       UseReg = AMDGPU::VCC;
977       int WaitStatesNeededForDef =
978           VALUWriteSGPRVALUReadWaitstates -
979           getWaitStatesSince(IsVALUDefSGPRFn, VALUWriteSGPRVALUReadWaitstates);
980       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
981     }
982 
983     switch (VALU->getOpcode()) {
984     case AMDGPU::V_READLANE_B32:
985     case AMDGPU::V_READFIRSTLANE_B32: {
986       MachineOperand *Src = TII.getNamedOperand(*VALU, AMDGPU::OpName::src0);
987       UseReg = Src->getReg();
988       int WaitStatesNeededForDef =
989           VALUWriteVGPRReadlaneRead -
990           getWaitStatesSince(IsVALUDefSGPRFn, VALUWriteVGPRReadlaneRead);
991       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
992     }
993       [[fallthrough]];
994     case AMDGPU::V_WRITELANE_B32: {
995       UseReg = AMDGPU::EXEC;
996       int WaitStatesNeededForDef =
997           VALUWriteEXECRWLane -
998           getWaitStatesSince(IsVALUDefSGPRFn, VALUWriteEXECRWLane);
999       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
1000       break;
1001     }
1002     default:
1003       break;
1004     }
1005   }
1006 
1007   // This checks for the hazard where VMEM instructions that store more than
1008   // 8 bytes can have there store data over written by the next instruction.
1009   if (!ST.has12DWordStoreHazard())
1010     return WaitStatesNeeded;
1011 
1012   const MachineRegisterInfo &MRI = MF.getRegInfo();
1013 
1014   for (const MachineOperand &Def : VALU->defs()) {
1015     WaitStatesNeeded = std::max(WaitStatesNeeded, checkVALUHazardsHelper(Def, MRI));
1016   }
1017 
1018   return WaitStatesNeeded;
1019 }
1020 
1021 int GCNHazardRecognizer::checkInlineAsmHazards(MachineInstr *IA) {
1022   // This checks for hazards associated with inline asm statements.
1023   // Since inline asms can contain just about anything, we use this
1024   // to call/leverage other check*Hazard routines. Note that
1025   // this function doesn't attempt to address all possible inline asm
1026   // hazards (good luck), but is a collection of what has been
1027   // problematic thus far.
1028 
1029   // see checkVALUHazards()
1030   if (!ST.has12DWordStoreHazard())
1031     return 0;
1032 
1033   const MachineRegisterInfo &MRI = MF.getRegInfo();
1034   int WaitStatesNeeded = 0;
1035 
1036   for (const MachineOperand &Op :
1037        llvm::drop_begin(IA->operands(), InlineAsm::MIOp_FirstOperand)) {
1038     if (Op.isReg() && Op.isDef()) {
1039       WaitStatesNeeded =
1040           std::max(WaitStatesNeeded, checkVALUHazardsHelper(Op, MRI));
1041     }
1042   }
1043 
1044   return WaitStatesNeeded;
1045 }
1046 
1047 int GCNHazardRecognizer::checkRWLaneHazards(MachineInstr *RWLane) {
1048   const SIInstrInfo *TII = ST.getInstrInfo();
1049   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1050   const MachineRegisterInfo &MRI = MF.getRegInfo();
1051 
1052   const MachineOperand *LaneSelectOp =
1053       TII->getNamedOperand(*RWLane, AMDGPU::OpName::src1);
1054 
1055   if (!LaneSelectOp->isReg() || !TRI->isSGPRReg(MRI, LaneSelectOp->getReg()))
1056     return 0;
1057 
1058   Register LaneSelectReg = LaneSelectOp->getReg();
1059   auto IsHazardFn = [TII](const MachineInstr &MI) { return TII->isVALU(MI); };
1060 
1061   const int RWLaneWaitStates = 4;
1062   int WaitStatesSince = getWaitStatesSinceDef(LaneSelectReg, IsHazardFn,
1063                                               RWLaneWaitStates);
1064   return RWLaneWaitStates - WaitStatesSince;
1065 }
1066 
1067 int GCNHazardRecognizer::checkRFEHazards(MachineInstr *RFE) {
1068   if (!ST.hasRFEHazards())
1069     return 0;
1070 
1071   const SIInstrInfo *TII = ST.getInstrInfo();
1072 
1073   const int RFEWaitStates = 1;
1074 
1075   auto IsHazardFn = [TII](const MachineInstr &MI) {
1076     return getHWReg(TII, MI) == AMDGPU::Hwreg::ID_TRAPSTS;
1077   };
1078   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, RFEWaitStates);
1079   return RFEWaitStates - WaitStatesNeeded;
1080 }
1081 
1082 int GCNHazardRecognizer::checkReadM0Hazards(MachineInstr *MI) {
1083   const SIInstrInfo *TII = ST.getInstrInfo();
1084   const int ReadM0WaitStates = 1;
1085   auto IsHazardFn = [TII](const MachineInstr &MI) { return TII->isSALU(MI); };
1086   return ReadM0WaitStates -
1087          getWaitStatesSinceDef(AMDGPU::M0, IsHazardFn, ReadM0WaitStates);
1088 }
1089 
1090 void GCNHazardRecognizer::fixHazards(MachineInstr *MI) {
1091   fixVMEMtoScalarWriteHazards(MI);
1092   fixVcmpxPermlaneHazards(MI);
1093   fixSMEMtoVectorWriteHazards(MI);
1094   fixVcmpxExecWARHazard(MI);
1095   fixLdsBranchVmemWARHazard(MI);
1096   if (ST.hasLdsDirect()) {
1097     fixLdsDirectVALUHazard(MI);
1098     fixLdsDirectVMEMHazard(MI);
1099   }
1100   fixVALUPartialForwardingHazard(MI);
1101   fixVALUTransUseHazard(MI);
1102   fixWMMAHazards(MI);
1103   fixShift64HighRegBug(MI);
1104   fixVALUMaskWriteHazard(MI);
1105 }
1106 
1107 bool GCNHazardRecognizer::fixVcmpxPermlaneHazards(MachineInstr *MI) {
1108   if (!ST.hasVcmpxPermlaneHazard() || !isPermlane(*MI))
1109     return false;
1110 
1111   const SIInstrInfo *TII = ST.getInstrInfo();
1112   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1113   auto IsHazardFn = [TII, TRI](const MachineInstr &MI) {
1114     return (TII->isVOPC(MI) ||
1115             ((TII->isVOP3(MI) || TII->isSDWA(MI)) && MI.isCompare())) &&
1116            MI.modifiesRegister(AMDGPU::EXEC, TRI);
1117   };
1118 
1119   auto IsExpiredFn = [](const MachineInstr &MI, int) {
1120     unsigned Opc = MI.getOpcode();
1121     return SIInstrInfo::isVALU(MI) && Opc != AMDGPU::V_NOP_e32 &&
1122            Opc != AMDGPU::V_NOP_e64 && Opc != AMDGPU::V_NOP_sdwa;
1123   };
1124 
1125   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1126       std::numeric_limits<int>::max())
1127     return false;
1128 
1129   // V_NOP will be discarded by SQ.
1130   // Use V_MOV_B32 v?, v?. Register must be alive so use src0 of V_PERMLANE*
1131   // which is always a VGPR and available.
1132   auto *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
1133   Register Reg = Src0->getReg();
1134   bool IsUndef = Src0->isUndef();
1135   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1136           TII->get(AMDGPU::V_MOV_B32_e32))
1137     .addReg(Reg, RegState::Define | (IsUndef ? RegState::Dead : 0))
1138     .addReg(Reg, IsUndef ? RegState::Undef : RegState::Kill);
1139 
1140   return true;
1141 }
1142 
1143 bool GCNHazardRecognizer::fixVMEMtoScalarWriteHazards(MachineInstr *MI) {
1144   if (!ST.hasVMEMtoScalarWriteHazard())
1145     return false;
1146 
1147   if (!SIInstrInfo::isSALU(*MI) && !SIInstrInfo::isSMRD(*MI))
1148     return false;
1149 
1150   if (MI->getNumDefs() == 0)
1151     return false;
1152 
1153   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1154 
1155   auto IsHazardFn = [TRI, MI](const MachineInstr &I) {
1156     if (!SIInstrInfo::isVMEM(I) && !SIInstrInfo::isDS(I) &&
1157         !SIInstrInfo::isFLAT(I))
1158       return false;
1159 
1160     for (const MachineOperand &Def : MI->defs()) {
1161       const MachineOperand *Op =
1162           I.findRegisterUseOperand(Def.getReg(), false, TRI);
1163       if (!Op)
1164         continue;
1165       return true;
1166     }
1167     return false;
1168   };
1169 
1170   auto IsExpiredFn = [](const MachineInstr &MI, int) {
1171     return SIInstrInfo::isVALU(MI) ||
1172            (MI.getOpcode() == AMDGPU::S_WAITCNT &&
1173             !MI.getOperand(0).getImm()) ||
1174            (MI.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1175             AMDGPU::DepCtr::decodeFieldVmVsrc(MI.getOperand(0).getImm()) == 0);
1176   };
1177 
1178   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1179       std::numeric_limits<int>::max())
1180     return false;
1181 
1182   const SIInstrInfo *TII = ST.getInstrInfo();
1183   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1184           TII->get(AMDGPU::S_WAITCNT_DEPCTR))
1185       .addImm(AMDGPU::DepCtr::encodeFieldVmVsrc(0));
1186   return true;
1187 }
1188 
1189 bool GCNHazardRecognizer::fixSMEMtoVectorWriteHazards(MachineInstr *MI) {
1190   if (!ST.hasSMEMtoVectorWriteHazard())
1191     return false;
1192 
1193   if (!SIInstrInfo::isVALU(*MI))
1194     return false;
1195 
1196   unsigned SDSTName;
1197   switch (MI->getOpcode()) {
1198   case AMDGPU::V_READLANE_B32:
1199   case AMDGPU::V_READFIRSTLANE_B32:
1200     SDSTName = AMDGPU::OpName::vdst;
1201     break;
1202   default:
1203     SDSTName = AMDGPU::OpName::sdst;
1204     break;
1205   }
1206 
1207   const SIInstrInfo *TII = ST.getInstrInfo();
1208   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1209   const AMDGPU::IsaVersion IV = AMDGPU::getIsaVersion(ST.getCPU());
1210   const MachineOperand *SDST = TII->getNamedOperand(*MI, SDSTName);
1211   if (!SDST) {
1212     for (const auto &MO : MI->implicit_operands()) {
1213       if (MO.isDef() && TRI->isSGPRClass(TRI->getPhysRegBaseClass(MO.getReg()))) {
1214         SDST = &MO;
1215         break;
1216       }
1217     }
1218   }
1219 
1220   if (!SDST)
1221     return false;
1222 
1223   const Register SDSTReg = SDST->getReg();
1224   auto IsHazardFn = [SDSTReg, TRI](const MachineInstr &I) {
1225     return SIInstrInfo::isSMRD(I) && I.readsRegister(SDSTReg, TRI);
1226   };
1227 
1228   auto IsExpiredFn = [TII, IV](const MachineInstr &MI, int) {
1229     if (TII->isSALU(MI)) {
1230       switch (MI.getOpcode()) {
1231       case AMDGPU::S_SETVSKIP:
1232       case AMDGPU::S_VERSION:
1233       case AMDGPU::S_WAITCNT_VSCNT:
1234       case AMDGPU::S_WAITCNT_VMCNT:
1235       case AMDGPU::S_WAITCNT_EXPCNT:
1236         // These instructions cannot not mitigate the hazard.
1237         return false;
1238       case AMDGPU::S_WAITCNT_LGKMCNT:
1239         // Reducing lgkmcnt count to 0 always mitigates the hazard.
1240         return (MI.getOperand(1).getImm() == 0) &&
1241                (MI.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1242       case AMDGPU::S_WAITCNT: {
1243         const int64_t Imm = MI.getOperand(0).getImm();
1244         AMDGPU::Waitcnt Decoded = AMDGPU::decodeWaitcnt(IV, Imm);
1245         // DsCnt corresponds to LGKMCnt here.
1246         return (Decoded.DsCnt == 0);
1247       }
1248       default:
1249         // SOPP instructions cannot mitigate the hazard.
1250         if (TII->isSOPP(MI))
1251           return false;
1252         // At this point the SALU can be assumed to mitigate the hazard
1253         // because either:
1254         // (a) it is independent of the at risk SMEM (breaking chain),
1255         // or
1256         // (b) it is dependent on the SMEM, in which case an appropriate
1257         //     s_waitcnt lgkmcnt _must_ exist between it and the at risk
1258         //     SMEM instruction.
1259         return true;
1260       }
1261     }
1262     return false;
1263   };
1264 
1265   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1266       std::numeric_limits<int>::max())
1267     return false;
1268 
1269   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1270           TII->get(AMDGPU::S_MOV_B32), AMDGPU::SGPR_NULL)
1271       .addImm(0);
1272   return true;
1273 }
1274 
1275 bool GCNHazardRecognizer::fixVcmpxExecWARHazard(MachineInstr *MI) {
1276   if (!ST.hasVcmpxExecWARHazard() || !SIInstrInfo::isVALU(*MI))
1277     return false;
1278 
1279   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1280   if (!MI->modifiesRegister(AMDGPU::EXEC, TRI))
1281     return false;
1282 
1283   auto IsHazardFn = [TRI](const MachineInstr &I) {
1284     if (SIInstrInfo::isVALU(I))
1285       return false;
1286     return I.readsRegister(AMDGPU::EXEC, TRI);
1287   };
1288 
1289   const SIInstrInfo *TII = ST.getInstrInfo();
1290   auto IsExpiredFn = [TII, TRI](const MachineInstr &MI, int) {
1291     if (SIInstrInfo::isVALU(MI)) {
1292       if (TII->getNamedOperand(MI, AMDGPU::OpName::sdst))
1293         return true;
1294       for (auto MO : MI.implicit_operands())
1295         if (MO.isDef() && TRI->isSGPRClass(TRI->getPhysRegBaseClass(MO.getReg())))
1296           return true;
1297     }
1298     if (MI.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1299         AMDGPU::DepCtr::decodeFieldSaSdst(MI.getOperand(0).getImm()) == 0)
1300       return true;
1301     return false;
1302   };
1303 
1304   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1305       std::numeric_limits<int>::max())
1306     return false;
1307 
1308   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1309           TII->get(AMDGPU::S_WAITCNT_DEPCTR))
1310       .addImm(AMDGPU::DepCtr::encodeFieldSaSdst(0));
1311   return true;
1312 }
1313 
1314 static bool shouldRunLdsBranchVmemWARHazardFixup(const MachineFunction &MF,
1315                                                  const GCNSubtarget &ST) {
1316   if (!ST.hasLdsBranchVmemWARHazard())
1317     return false;
1318 
1319   // Check if the necessary condition for the hazard is met: both LDS and VMEM
1320   // instructions need to appear in the same function.
1321   bool HasLds = false;
1322   bool HasVmem = false;
1323   for (auto &MBB : MF) {
1324     for (auto &MI : MBB) {
1325       HasLds |= SIInstrInfo::isDS(MI);
1326       HasVmem |=
1327           SIInstrInfo::isVMEM(MI) || SIInstrInfo::isSegmentSpecificFLAT(MI);
1328       if (HasLds && HasVmem)
1329         return true;
1330     }
1331   }
1332   return false;
1333 }
1334 
1335 static bool isStoreCountWaitZero(const MachineInstr &I) {
1336   return I.getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1337          I.getOperand(0).getReg() == AMDGPU::SGPR_NULL &&
1338          !I.getOperand(1).getImm();
1339 }
1340 
1341 bool GCNHazardRecognizer::fixLdsBranchVmemWARHazard(MachineInstr *MI) {
1342   if (!RunLdsBranchVmemWARHazardFixup)
1343     return false;
1344 
1345   assert(ST.hasLdsBranchVmemWARHazard());
1346 
1347   auto IsHazardInst = [](const MachineInstr &MI) {
1348     if (SIInstrInfo::isDS(MI))
1349       return 1;
1350     if (SIInstrInfo::isVMEM(MI) || SIInstrInfo::isSegmentSpecificFLAT(MI))
1351       return 2;
1352     return 0;
1353   };
1354 
1355   auto InstType = IsHazardInst(*MI);
1356   if (!InstType)
1357     return false;
1358 
1359   auto IsExpiredFn = [&IsHazardInst](const MachineInstr &I, int) {
1360     return IsHazardInst(I) || isStoreCountWaitZero(I);
1361   };
1362 
1363   auto IsHazardFn = [InstType, &IsHazardInst](const MachineInstr &I) {
1364     if (!I.isBranch())
1365       return false;
1366 
1367     auto IsHazardFn = [InstType, IsHazardInst](const MachineInstr &I) {
1368       auto InstType2 = IsHazardInst(I);
1369       return InstType2 && InstType != InstType2;
1370     };
1371 
1372     auto IsExpiredFn = [InstType, &IsHazardInst](const MachineInstr &I, int) {
1373       auto InstType2 = IsHazardInst(I);
1374       if (InstType == InstType2)
1375         return true;
1376 
1377       return isStoreCountWaitZero(I);
1378     };
1379 
1380     return ::getWaitStatesSince(IsHazardFn, &I, IsExpiredFn) !=
1381            std::numeric_limits<int>::max();
1382   };
1383 
1384   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1385       std::numeric_limits<int>::max())
1386     return false;
1387 
1388   const SIInstrInfo *TII = ST.getInstrInfo();
1389   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1390           TII->get(AMDGPU::S_WAITCNT_VSCNT))
1391     .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1392     .addImm(0);
1393 
1394   return true;
1395 }
1396 
1397 bool GCNHazardRecognizer::fixLdsDirectVALUHazard(MachineInstr *MI) {
1398   if (!SIInstrInfo::isLDSDIR(*MI))
1399     return false;
1400 
1401   const int NoHazardWaitStates = 15;
1402   const MachineOperand *VDST = TII.getNamedOperand(*MI, AMDGPU::OpName::vdst);
1403   const Register VDSTReg = VDST->getReg();
1404 
1405   bool VisitedTrans = false;
1406   auto IsHazardFn = [this, VDSTReg, &VisitedTrans](const MachineInstr &I) {
1407     if (!SIInstrInfo::isVALU(I))
1408       return false;
1409     VisitedTrans = VisitedTrans || SIInstrInfo::isTRANS(I);
1410     // Cover both WAR and WAW
1411     return I.readsRegister(VDSTReg, &TRI) || I.modifiesRegister(VDSTReg, &TRI);
1412   };
1413   auto IsExpiredFn = [&](const MachineInstr &I, int WaitStates) {
1414     if (WaitStates >= NoHazardWaitStates)
1415       return true;
1416     // Instructions which cause va_vdst==0 expire hazard
1417     return SIInstrInfo::isVMEM(I) || SIInstrInfo::isFLAT(I) ||
1418            SIInstrInfo::isDS(I) || SIInstrInfo::isEXP(I);
1419   };
1420   auto GetWaitStatesFn = [](const MachineInstr &MI) {
1421     return SIInstrInfo::isVALU(MI) ? 1 : 0;
1422   };
1423 
1424   DenseSet<const MachineBasicBlock *> Visited;
1425   auto Count = ::getWaitStatesSince(IsHazardFn, MI->getParent(),
1426                                     std::next(MI->getReverseIterator()), 0,
1427                                     IsExpiredFn, Visited, GetWaitStatesFn);
1428 
1429   // Transcendentals can execute in parallel to other VALUs.
1430   // This makes va_vdst count unusable with a mixture of VALU and TRANS.
1431   if (VisitedTrans)
1432     Count = 0;
1433 
1434   MachineOperand *WaitVdstOp =
1435       TII.getNamedOperand(*MI, AMDGPU::OpName::waitvdst);
1436   WaitVdstOp->setImm(std::min(Count, NoHazardWaitStates));
1437 
1438   return true;
1439 }
1440 
1441 bool GCNHazardRecognizer::fixLdsDirectVMEMHazard(MachineInstr *MI) {
1442   if (!SIInstrInfo::isLDSDIR(*MI))
1443     return false;
1444 
1445   const MachineOperand *VDST = TII.getNamedOperand(*MI, AMDGPU::OpName::vdst);
1446   const Register VDSTReg = VDST->getReg();
1447 
1448   auto IsHazardFn = [this, VDSTReg](const MachineInstr &I) {
1449     if (!SIInstrInfo::isVMEM(I) && !SIInstrInfo::isFLAT(I) &&
1450         !SIInstrInfo::isDS(I))
1451       return false;
1452     return I.readsRegister(VDSTReg, &TRI) || I.modifiesRegister(VDSTReg, &TRI);
1453   };
1454   bool LdsdirCanWait = ST.hasLdsWaitVMSRC();
1455   auto IsExpiredFn = [this, LdsdirCanWait](const MachineInstr &I, int) {
1456     return SIInstrInfo::isVALU(I) || SIInstrInfo::isEXP(I) ||
1457            (I.getOpcode() == AMDGPU::S_WAITCNT && !I.getOperand(0).getImm()) ||
1458            (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1459             AMDGPU::DepCtr::decodeFieldVmVsrc(I.getOperand(0).getImm()) == 0) ||
1460            (LdsdirCanWait && SIInstrInfo::isLDSDIR(I) &&
1461             !TII.getNamedOperand(I, AMDGPU::OpName::waitvsrc)->getImm());
1462   };
1463 
1464   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1465       std::numeric_limits<int>::max())
1466     return false;
1467 
1468   if (LdsdirCanWait) {
1469     TII.getNamedOperand(*MI, AMDGPU::OpName::waitvsrc)->setImm(0);
1470   } else {
1471     BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1472             TII.get(AMDGPU::S_WAITCNT_DEPCTR))
1473         .addImm(AMDGPU::DepCtr::encodeFieldVmVsrc(0));
1474   }
1475 
1476   return true;
1477 }
1478 
1479 bool GCNHazardRecognizer::fixVALUPartialForwardingHazard(MachineInstr *MI) {
1480   if (!ST.isWave64())
1481     return false;
1482   if (!ST.hasVALUPartialForwardingHazard())
1483     return false;
1484   if (!SIInstrInfo::isVALU(*MI))
1485     return false;
1486 
1487   SmallSetVector<Register, 4> SrcVGPRs;
1488 
1489   for (const MachineOperand &Use : MI->explicit_uses()) {
1490     if (Use.isReg() && TRI.isVGPR(MF.getRegInfo(), Use.getReg()))
1491       SrcVGPRs.insert(Use.getReg());
1492   }
1493 
1494   // Only applies with >= 2 unique VGPR sources
1495   if (SrcVGPRs.size() <= 1)
1496     return false;
1497 
1498   // Look for the following pattern:
1499   //   Va <- VALU [PreExecPos]
1500   //   intv1
1501   //   Exec <- SALU [ExecPos]
1502   //   intv2
1503   //   Vb <- VALU [PostExecPos]
1504   //   intv3
1505   //   MI Va, Vb (WaitState = 0)
1506   //
1507   // Where:
1508   // intv1 + intv2 <= 2 VALUs
1509   // intv3 <= 4 VALUs
1510   //
1511   // If found, insert an appropriate S_WAITCNT_DEPCTR before MI.
1512 
1513   const int Intv1plus2MaxVALUs = 2;
1514   const int Intv3MaxVALUs = 4;
1515   const int IntvMaxVALUs = 6;
1516   const int NoHazardVALUWaitStates = IntvMaxVALUs + 2;
1517 
1518   struct StateType {
1519     SmallDenseMap<Register, int, 4> DefPos;
1520     int ExecPos = std::numeric_limits<int>::max();
1521     int VALUs = 0;
1522   };
1523 
1524   StateType State;
1525 
1526   // This overloads expiry testing with all the hazard detection
1527   auto IsHazardFn = [&, this](StateType &State, const MachineInstr &I) {
1528     // Too many VALU states have passed
1529     if (State.VALUs > NoHazardVALUWaitStates)
1530       return HazardExpired;
1531 
1532     // Instructions which cause va_vdst==0 expire hazard
1533     if (SIInstrInfo::isVMEM(I) || SIInstrInfo::isFLAT(I) ||
1534         SIInstrInfo::isDS(I) || SIInstrInfo::isEXP(I) ||
1535         (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1536          AMDGPU::DepCtr::decodeFieldVaVdst(I.getOperand(0).getImm()) == 0))
1537       return HazardExpired;
1538 
1539     // Track registers writes
1540     bool Changed = false;
1541     if (SIInstrInfo::isVALU(I)) {
1542       for (Register Src : SrcVGPRs) {
1543         if (!State.DefPos.count(Src) && I.modifiesRegister(Src, &TRI)) {
1544           State.DefPos[Src] = State.VALUs;
1545           Changed = true;
1546         }
1547       }
1548     } else if (SIInstrInfo::isSALU(I)) {
1549       if (State.ExecPos == std::numeric_limits<int>::max()) {
1550         if (!State.DefPos.empty() && I.modifiesRegister(AMDGPU::EXEC, &TRI)) {
1551           State.ExecPos = State.VALUs;
1552           Changed = true;
1553         }
1554       }
1555     }
1556 
1557     // Early expiration: too many VALUs in intv3
1558     if (State.VALUs > Intv3MaxVALUs && State.DefPos.empty())
1559       return HazardExpired;
1560 
1561     // Only evaluate state if something changed
1562     if (!Changed)
1563       return NoHazardFound;
1564 
1565     // Determine positions of VALUs pre/post exec change
1566     if (State.ExecPos == std::numeric_limits<int>::max())
1567       return NoHazardFound;
1568 
1569     int PreExecPos = std::numeric_limits<int>::max();
1570     int PostExecPos = std::numeric_limits<int>::max();
1571 
1572     for (auto Entry : State.DefPos) {
1573       int DefVALUs = Entry.second;
1574       if (DefVALUs != std::numeric_limits<int>::max()) {
1575         if (DefVALUs >= State.ExecPos)
1576           PreExecPos = std::min(PreExecPos, DefVALUs);
1577         else if (DefVALUs < State.ExecPos)
1578           PostExecPos = std::min(PostExecPos, DefVALUs);
1579       }
1580     }
1581 
1582     // Need a VALUs post exec change
1583     if (PostExecPos == std::numeric_limits<int>::max())
1584       return NoHazardFound;
1585 
1586     // Too many VALUs in intv3?
1587     int Intv3VALUs = PostExecPos;
1588     if (Intv3VALUs > Intv3MaxVALUs)
1589       return HazardExpired;
1590 
1591     // Too many VALUs in intv2?
1592     int Intv2VALUs = (State.ExecPos - PostExecPos) - 1;
1593     if (Intv2VALUs > Intv1plus2MaxVALUs)
1594       return HazardExpired;
1595 
1596     // Need a VALUs pre exec change
1597     if (PreExecPos == std::numeric_limits<int>::max())
1598       return NoHazardFound;
1599 
1600     // Too many VALUs in intv1?
1601     int Intv1VALUs = PreExecPos - State.ExecPos;
1602     if (Intv1VALUs > Intv1plus2MaxVALUs)
1603       return HazardExpired;
1604 
1605     // Too many VALUs in intv1 + intv2
1606     if (Intv1VALUs + Intv2VALUs > Intv1plus2MaxVALUs)
1607       return HazardExpired;
1608 
1609     return HazardFound;
1610   };
1611   auto UpdateStateFn = [](StateType &State, const MachineInstr &MI) {
1612     if (SIInstrInfo::isVALU(MI))
1613       State.VALUs += 1;
1614   };
1615 
1616   DenseSet<const MachineBasicBlock *> Visited;
1617   if (!hasHazard<StateType>(State, IsHazardFn, UpdateStateFn, MI->getParent(),
1618                             std::next(MI->getReverseIterator()), Visited))
1619     return false;
1620 
1621   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1622           TII.get(AMDGPU::S_WAITCNT_DEPCTR))
1623       .addImm(0x0fff);
1624 
1625   return true;
1626 }
1627 
1628 bool GCNHazardRecognizer::fixVALUTransUseHazard(MachineInstr *MI) {
1629   if (!ST.hasVALUTransUseHazard())
1630     return false;
1631   if (!SIInstrInfo::isVALU(*MI))
1632     return false;
1633 
1634   SmallSet<Register, 4> SrcVGPRs;
1635 
1636   for (const MachineOperand &Use : MI->explicit_uses()) {
1637     if (Use.isReg() && TRI.isVGPR(MF.getRegInfo(), Use.getReg()))
1638       SrcVGPRs.insert(Use.getReg());
1639   }
1640 
1641   // Look for the following pattern:
1642   //   Va <- TRANS VALU
1643   //   intv
1644   //   MI Va (WaitState = 0)
1645   //
1646   // Where:
1647   // intv <= 5 VALUs / 1 TRANS
1648   //
1649   // If found, insert an appropriate S_WAITCNT_DEPCTR before MI.
1650 
1651   const int IntvMaxVALUs = 5;
1652   const int IntvMaxTRANS = 1;
1653 
1654   struct StateType {
1655     int VALUs = 0;
1656     int TRANS = 0;
1657   };
1658 
1659   StateType State;
1660 
1661   // This overloads expiry testing with all the hazard detection
1662   auto IsHazardFn = [&, this](StateType &State, const MachineInstr &I) {
1663     // Too many VALU states have passed
1664     if (State.VALUs > IntvMaxVALUs || State.TRANS > IntvMaxTRANS)
1665       return HazardExpired;
1666 
1667     // Instructions which cause va_vdst==0 expire hazard
1668     if (SIInstrInfo::isVMEM(I) || SIInstrInfo::isFLAT(I) ||
1669         SIInstrInfo::isDS(I) || SIInstrInfo::isEXP(I) ||
1670         (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1671          I.getOperand(0).getImm() == 0x0fff))
1672       return HazardExpired;
1673 
1674     // Track registers writes
1675     if (SIInstrInfo::isTRANS(I)) {
1676       for (Register Src : SrcVGPRs) {
1677         if (I.modifiesRegister(Src, &TRI)) {
1678           return HazardFound;
1679         }
1680       }
1681     }
1682 
1683     return NoHazardFound;
1684   };
1685   auto UpdateStateFn = [](StateType &State, const MachineInstr &MI) {
1686     if (SIInstrInfo::isVALU(MI))
1687       State.VALUs += 1;
1688     if (SIInstrInfo::isTRANS(MI))
1689       State.TRANS += 1;
1690   };
1691 
1692   DenseSet<const MachineBasicBlock *> Visited;
1693   if (!hasHazard<StateType>(State, IsHazardFn, UpdateStateFn, MI->getParent(),
1694                             std::next(MI->getReverseIterator()), Visited))
1695     return false;
1696 
1697   // Hazard is observed - insert a wait on va_dst counter to ensure hazard is
1698   // avoided.
1699   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1700           TII.get(AMDGPU::S_WAITCNT_DEPCTR))
1701       .addImm(AMDGPU::DepCtr::encodeFieldVaVdst(0));
1702 
1703   return true;
1704 }
1705 
1706 bool GCNHazardRecognizer::fixWMMAHazards(MachineInstr *MI) {
1707   if (!SIInstrInfo::isWMMA(*MI))
1708     return false;
1709 
1710   const SIInstrInfo *TII = ST.getInstrInfo();
1711   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1712 
1713   auto IsHazardFn = [MI, TII, TRI](const MachineInstr &I) {
1714     if (!SIInstrInfo::isWMMA(I))
1715       return false;
1716 
1717     // Src0 or Src1 of the current wmma instruction overlaps with the dest of
1718     // the previous wmma.
1719     const Register CurSrc0Reg =
1720         TII->getNamedOperand(*MI, AMDGPU::OpName::src0)->getReg();
1721     const Register CurSrc1Reg =
1722         TII->getNamedOperand(*MI, AMDGPU::OpName::src1)->getReg();
1723 
1724     const Register PrevDstReg =
1725         TII->getNamedOperand(I, AMDGPU::OpName::vdst)->getReg();
1726 
1727     if (TRI->regsOverlap(PrevDstReg, CurSrc0Reg) ||
1728         TRI->regsOverlap(PrevDstReg, CurSrc1Reg)) {
1729       return true;
1730     }
1731 
1732     // Src2 of the current wmma instruction overlaps with the dest of the
1733     // previous wmma.
1734     const MachineOperand *Src2 =
1735         TII->getNamedOperand(*MI, AMDGPU::OpName::src2);
1736     const Register CurSrc2Reg = Src2->isReg() ? Src2->getReg() : Register();
1737 
1738     if (CurSrc2Reg != AMDGPU::NoRegister &&
1739         TRI->regsOverlap(PrevDstReg, CurSrc2Reg)) {
1740 
1741       const MachineOperand *Src2Mods =
1742           TII->getNamedOperand(*MI, AMDGPU::OpName::src2_modifiers);
1743       const bool NoSrc2Mods =
1744           (Src2Mods->getImm() & (SISrcMods::NEG | SISrcMods::NEG_HI)) == 0;
1745       // Exception: there is no hazard if the wmma instructions are of the same
1746       // type and there is no input modifier on src2 of the current instruction.
1747       return !(NoSrc2Mods && (TII->pseudoToMCOpcode(I.getOpcode()) ==
1748                               TII->pseudoToMCOpcode(MI->getOpcode())));
1749     }
1750 
1751     return false;
1752   };
1753 
1754   auto IsExpiredFn = [](const MachineInstr &I, int) {
1755     return SIInstrInfo::isVALU(I);
1756   };
1757 
1758   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1759       std::numeric_limits<int>::max())
1760     return false;
1761 
1762   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(AMDGPU::V_NOP_e32));
1763 
1764   return true;
1765 }
1766 
1767 bool GCNHazardRecognizer::fixShift64HighRegBug(MachineInstr *MI) {
1768   if (!ST.hasShift64HighRegBug())
1769     return false;
1770 
1771   switch (MI->getOpcode()) {
1772   default:
1773     return false;
1774   case AMDGPU::V_LSHLREV_B64_e64:
1775   case AMDGPU::V_LSHRREV_B64_e64:
1776   case AMDGPU::V_ASHRREV_I64_e64:
1777     break;
1778   }
1779 
1780   MachineOperand *Amt = TII.getNamedOperand(*MI, AMDGPU::OpName::src0);
1781   if (!Amt->isReg())
1782     return false;
1783 
1784   Register AmtReg = Amt->getReg();
1785   const MachineRegisterInfo &MRI = MF.getRegInfo();
1786   // Check if this is a last VGPR in the allocation block.
1787   if (!TRI.isVGPR(MRI, AmtReg) || ((AmtReg - AMDGPU::VGPR0) & 7) != 7)
1788     return false;
1789 
1790   if (AmtReg != AMDGPU::VGPR255 && MRI.isPhysRegUsed(AmtReg + 1))
1791     return false;
1792 
1793   MachineOperand *Src1 = TII.getNamedOperand(*MI, AMDGPU::OpName::src1);
1794   bool OverlappedSrc = Src1->isReg() && TRI.regsOverlap(Src1->getReg(), AmtReg);
1795   bool OverlappedDst = MI->modifiesRegister(AmtReg, &TRI);
1796   bool Overlapped = OverlappedSrc || OverlappedDst;
1797 
1798   assert(!OverlappedDst || !OverlappedSrc ||
1799          Src1->getReg() == MI->getOperand(0).getReg());
1800   assert(ST.needsAlignedVGPRs());
1801   static_assert(AMDGPU::VGPR0 + 1 == AMDGPU::VGPR1);
1802 
1803   Register NewReg;
1804   for (MCRegister Reg : Overlapped ? AMDGPU::VReg_64_Align2RegClass
1805                                    : AMDGPU::VGPR_32RegClass) {
1806     if (!MI->modifiesRegister(Reg, &TRI) && !MI->readsRegister(Reg, &TRI)) {
1807       NewReg = Reg;
1808       break;
1809     }
1810   }
1811 
1812   Register NewAmt = Overlapped ? (Register)TRI.getSubReg(NewReg, AMDGPU::sub1)
1813                                : NewReg;
1814   Register NewAmtLo;
1815 
1816   if (Overlapped)
1817     NewAmtLo = TRI.getSubReg(NewReg, AMDGPU::sub0);
1818 
1819   DebugLoc DL = MI->getDebugLoc();
1820   MachineBasicBlock *MBB = MI->getParent();
1821   // Insert a full wait count because found register might be pending a wait.
1822   BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_WAITCNT))
1823       .addImm(0);
1824 
1825   // Insert V_SWAP_B32 instruction(s) and run hazard recognizer on them.
1826   if (Overlapped)
1827     runOnInstruction(
1828         BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_SWAP_B32), NewAmtLo)
1829             .addDef(AmtReg - 1)
1830             .addReg(AmtReg - 1, RegState::Undef)
1831             .addReg(NewAmtLo, RegState::Undef));
1832   runOnInstruction(BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_SWAP_B32), NewAmt)
1833                        .addDef(AmtReg)
1834                        .addReg(AmtReg, RegState::Undef)
1835                        .addReg(NewAmt, RegState::Undef));
1836 
1837   // Instructions emitted after the current instruction will be processed by the
1838   // parent loop of the hazard recognizer in a natural way.
1839   BuildMI(*MBB, std::next(MI->getIterator()), DL, TII.get(AMDGPU::V_SWAP_B32),
1840           AmtReg)
1841       .addDef(NewAmt)
1842       .addReg(NewAmt)
1843       .addReg(AmtReg);
1844   if (Overlapped)
1845     BuildMI(*MBB, std::next(MI->getIterator()), DL, TII.get(AMDGPU::V_SWAP_B32),
1846             AmtReg - 1)
1847         .addDef(NewAmtLo)
1848         .addReg(NewAmtLo)
1849         .addReg(AmtReg - 1);
1850 
1851   // Re-running hazard recognizer on the modified instruction is not necessary,
1852   // inserted V_SWAP_B32 has already both read and write new registers so
1853   // hazards related to these register has already been handled.
1854   Amt->setReg(NewAmt);
1855   Amt->setIsKill(false);
1856   // We do not update liveness, so verifier may see it as undef.
1857   Amt->setIsUndef();
1858   if (OverlappedDst)
1859     MI->getOperand(0).setReg(NewReg);
1860   if (OverlappedSrc) {
1861     Src1->setReg(NewReg);
1862     Src1->setIsKill(false);
1863     Src1->setIsUndef();
1864   }
1865 
1866   return true;
1867 }
1868 
1869 int GCNHazardRecognizer::checkNSAtoVMEMHazard(MachineInstr *MI) {
1870   int NSAtoVMEMWaitStates = 1;
1871 
1872   if (!ST.hasNSAtoVMEMBug())
1873     return 0;
1874 
1875   if (!SIInstrInfo::isMUBUF(*MI) && !SIInstrInfo::isMTBUF(*MI))
1876     return 0;
1877 
1878   const SIInstrInfo *TII = ST.getInstrInfo();
1879   const auto *Offset = TII->getNamedOperand(*MI, AMDGPU::OpName::offset);
1880   if (!Offset || (Offset->getImm() & 6) == 0)
1881     return 0;
1882 
1883   auto IsHazardFn = [TII](const MachineInstr &I) {
1884     if (!SIInstrInfo::isMIMG(I))
1885       return false;
1886     const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(I.getOpcode());
1887     return Info->MIMGEncoding == AMDGPU::MIMGEncGfx10NSA &&
1888            TII->getInstSizeInBytes(I) >= 16;
1889   };
1890 
1891   return NSAtoVMEMWaitStates - getWaitStatesSince(IsHazardFn, 1);
1892 }
1893 
1894 int GCNHazardRecognizer::checkFPAtomicToDenormModeHazard(MachineInstr *MI) {
1895   int FPAtomicToDenormModeWaitStates = 3;
1896 
1897   if (!ST.hasFPAtomicToDenormModeHazard())
1898     return 0;
1899 
1900   if (MI->getOpcode() != AMDGPU::S_DENORM_MODE)
1901     return 0;
1902 
1903   auto IsHazardFn = [](const MachineInstr &I) {
1904     if (!SIInstrInfo::isVMEM(I) && !SIInstrInfo::isFLAT(I))
1905       return false;
1906     return SIInstrInfo::isFPAtomic(I);
1907   };
1908 
1909   auto IsExpiredFn = [](const MachineInstr &MI, int WaitStates) {
1910     if (WaitStates >= 3 || SIInstrInfo::isVALU(MI))
1911       return true;
1912 
1913     switch (MI.getOpcode()) {
1914     case AMDGPU::S_WAITCNT:
1915     case AMDGPU::S_WAITCNT_VSCNT:
1916     case AMDGPU::S_WAITCNT_VMCNT:
1917     case AMDGPU::S_WAITCNT_EXPCNT:
1918     case AMDGPU::S_WAITCNT_LGKMCNT:
1919     case AMDGPU::S_WAIT_IDLE:
1920       return true;
1921     default:
1922       break;
1923     }
1924 
1925     return false;
1926   };
1927 
1928   return FPAtomicToDenormModeWaitStates -
1929          ::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn);
1930 }
1931 
1932 int GCNHazardRecognizer::checkMAIHazards(MachineInstr *MI) {
1933   assert(SIInstrInfo::isMAI(*MI));
1934 
1935   return ST.hasGFX90AInsts() ? checkMAIHazards90A(MI) : checkMAIHazards908(MI);
1936 }
1937 
1938 int GCNHazardRecognizer::checkMFMAPadding(MachineInstr *MI) {
1939   // Early exit if no padding is requested.
1940   if (MFMAPaddingRatio == 0)
1941     return 0;
1942 
1943   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1944   if (!SIInstrInfo::isMFMA(*MI) || MFI->getOccupancy() < 2)
1945     return 0;
1946 
1947   int NeighborMFMALatency = 0;
1948   auto IsNeighboringMFMA = [&NeighborMFMALatency,
1949                             this](const MachineInstr &MI) {
1950     if (!SIInstrInfo::isMFMA(MI))
1951       return false;
1952 
1953     NeighborMFMALatency = this->getMFMAPipelineWaitStates(MI);
1954     return true;
1955   };
1956 
1957   const int MaxMFMAPipelineWaitStates = 16;
1958   int WaitStatesSinceNeighborMFMA =
1959       getWaitStatesSince(IsNeighboringMFMA, MaxMFMAPipelineWaitStates);
1960 
1961   int NeighborMFMAPaddingNeeded =
1962       (NeighborMFMALatency * MFMAPaddingRatio / 100) -
1963       WaitStatesSinceNeighborMFMA;
1964 
1965   return std::max(0, NeighborMFMAPaddingNeeded);
1966 }
1967 
1968 int GCNHazardRecognizer::checkMAIHazards908(MachineInstr *MI) {
1969   int WaitStatesNeeded = 0;
1970   unsigned Opc = MI->getOpcode();
1971 
1972   auto IsVALUFn = [](const MachineInstr &MI) {
1973     return SIInstrInfo::isVALU(MI) || MI.isInlineAsm();
1974   };
1975 
1976   if (Opc != AMDGPU::V_ACCVGPR_READ_B32_e64) { // MFMA or v_accvgpr_write
1977     const int LegacyVALUWritesVGPRWaitStates = 2;
1978     const int VALUWritesExecWaitStates = 4;
1979     const int MaxWaitStates = 4;
1980 
1981     int WaitStatesNeededForUse = VALUWritesExecWaitStates -
1982       getWaitStatesSinceDef(AMDGPU::EXEC, IsVALUFn, MaxWaitStates);
1983     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
1984 
1985     if (WaitStatesNeeded < MaxWaitStates) {
1986       for (const MachineOperand &Use : MI->explicit_uses()) {
1987         const int MaxWaitStates = 2;
1988 
1989         if (!Use.isReg() || !TRI.isVGPR(MF.getRegInfo(), Use.getReg()))
1990           continue;
1991 
1992         int WaitStatesNeededForUse = LegacyVALUWritesVGPRWaitStates -
1993           getWaitStatesSinceDef(Use.getReg(), IsVALUFn, MaxWaitStates);
1994         WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
1995 
1996         if (WaitStatesNeeded == MaxWaitStates)
1997           break;
1998       }
1999     }
2000   }
2001 
2002   for (const MachineOperand &Op : MI->explicit_operands()) {
2003     if (!Op.isReg() || !TRI.isAGPR(MF.getRegInfo(), Op.getReg()))
2004       continue;
2005 
2006     if (Op.isDef() && Opc != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
2007       continue;
2008 
2009     const int MFMAWritesAGPROverlappedSrcABWaitStates = 4;
2010     const int MFMAWritesAGPROverlappedSrcCWaitStates = 2;
2011     const int MFMA4x4WritesAGPRAccVgprReadWaitStates = 4;
2012     const int MFMA16x16WritesAGPRAccVgprReadWaitStates = 10;
2013     const int MFMA32x32WritesAGPRAccVgprReadWaitStates = 18;
2014     const int MFMA4x4WritesAGPRAccVgprWriteWaitStates = 1;
2015     const int MFMA16x16WritesAGPRAccVgprWriteWaitStates = 7;
2016     const int MFMA32x32WritesAGPRAccVgprWriteWaitStates = 15;
2017     const int MaxWaitStates = 18;
2018     Register Reg = Op.getReg();
2019     unsigned HazardDefLatency = 0;
2020 
2021     auto IsOverlappedMFMAFn = [Reg, &HazardDefLatency,
2022                                this](const MachineInstr &MI) {
2023       if (!SIInstrInfo::isMFMA(MI))
2024         return false;
2025       Register DstReg = MI.getOperand(0).getReg();
2026       if (DstReg == Reg)
2027         return false;
2028       HazardDefLatency =
2029           std::max(HazardDefLatency, TSchedModel.computeInstrLatency(&MI));
2030       return TRI.regsOverlap(DstReg, Reg);
2031     };
2032 
2033     int WaitStatesSinceDef = getWaitStatesSinceDef(Reg, IsOverlappedMFMAFn,
2034                                                    MaxWaitStates);
2035     int NeedWaitStates = MFMAWritesAGPROverlappedSrcABWaitStates;
2036     int SrcCIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
2037     int OpNo = Op.getOperandNo();
2038     if (OpNo == SrcCIdx) {
2039       NeedWaitStates = MFMAWritesAGPROverlappedSrcCWaitStates;
2040     } else if (Opc == AMDGPU::V_ACCVGPR_READ_B32_e64) {
2041       switch (HazardDefLatency) {
2042       case 2:  NeedWaitStates = MFMA4x4WritesAGPRAccVgprReadWaitStates;
2043                break;
2044       case 8:  NeedWaitStates = MFMA16x16WritesAGPRAccVgprReadWaitStates;
2045                break;
2046       case 16: [[fallthrough]];
2047       default: NeedWaitStates = MFMA32x32WritesAGPRAccVgprReadWaitStates;
2048                break;
2049       }
2050     } else if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64) {
2051       switch (HazardDefLatency) {
2052       case 2:  NeedWaitStates = MFMA4x4WritesAGPRAccVgprWriteWaitStates;
2053                break;
2054       case 8:  NeedWaitStates = MFMA16x16WritesAGPRAccVgprWriteWaitStates;
2055                break;
2056       case 16: [[fallthrough]];
2057       default: NeedWaitStates = MFMA32x32WritesAGPRAccVgprWriteWaitStates;
2058                break;
2059       }
2060     }
2061 
2062     int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceDef;
2063     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2064 
2065     if (WaitStatesNeeded == MaxWaitStates)
2066       return WaitStatesNeeded; // Early exit.
2067 
2068     auto IsAccVgprWriteFn = [Reg, this](const MachineInstr &MI) {
2069       if (MI.getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
2070         return false;
2071       Register DstReg = MI.getOperand(0).getReg();
2072       return TRI.regsOverlap(Reg, DstReg);
2073     };
2074 
2075     const int AccVGPRWriteMFMAReadSrcCWaitStates = 1;
2076     const int AccVGPRWriteMFMAReadSrcABWaitStates = 3;
2077     const int AccVGPRWriteAccVgprReadWaitStates = 3;
2078     NeedWaitStates = AccVGPRWriteMFMAReadSrcABWaitStates;
2079     if (OpNo == SrcCIdx)
2080       NeedWaitStates = AccVGPRWriteMFMAReadSrcCWaitStates;
2081     else if (Opc == AMDGPU::V_ACCVGPR_READ_B32_e64)
2082       NeedWaitStates = AccVGPRWriteAccVgprReadWaitStates;
2083 
2084     WaitStatesNeededForUse = NeedWaitStates -
2085       getWaitStatesSinceDef(Reg, IsAccVgprWriteFn, MaxWaitStates);
2086     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2087 
2088     if (WaitStatesNeeded == MaxWaitStates)
2089       return WaitStatesNeeded; // Early exit.
2090   }
2091 
2092   if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64) {
2093     const int MFMA4x4ReadSrcCAccVgprWriteWaitStates = 0;
2094     const int MFMA16x16ReadSrcCAccVgprWriteWaitStates = 5;
2095     const int MFMA32x32ReadSrcCAccVgprWriteWaitStates = 13;
2096     const int MaxWaitStates = 13;
2097     Register DstReg = MI->getOperand(0).getReg();
2098     unsigned HazardDefLatency = 0;
2099 
2100     auto IsSrcCMFMAFn = [DstReg, &HazardDefLatency,
2101                          this](const MachineInstr &MI) {
2102       if (!SIInstrInfo::isMFMA(MI))
2103         return false;
2104       Register Reg = TII.getNamedOperand(MI, AMDGPU::OpName::src2)->getReg();
2105       HazardDefLatency =
2106           std::max(HazardDefLatency, TSchedModel.computeInstrLatency(&MI));
2107       return TRI.regsOverlap(Reg, DstReg);
2108     };
2109 
2110     int WaitStatesSince = getWaitStatesSince(IsSrcCMFMAFn, MaxWaitStates);
2111     int NeedWaitStates;
2112     switch (HazardDefLatency) {
2113     case 2:  NeedWaitStates = MFMA4x4ReadSrcCAccVgprWriteWaitStates;
2114              break;
2115     case 8:  NeedWaitStates = MFMA16x16ReadSrcCAccVgprWriteWaitStates;
2116              break;
2117     case 16: [[fallthrough]];
2118     default: NeedWaitStates = MFMA32x32ReadSrcCAccVgprWriteWaitStates;
2119              break;
2120     }
2121 
2122     int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSince;
2123     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2124   }
2125 
2126   // Pad neighboring MFMA with noops for better inter-wave performance.
2127   WaitStatesNeeded = std::max(WaitStatesNeeded, checkMFMAPadding(MI));
2128 
2129   return WaitStatesNeeded;
2130 }
2131 
2132 int GCNHazardRecognizer::checkMAIHazards90A(MachineInstr *MI) {
2133   int WaitStatesNeeded = 0;
2134   unsigned Opc = MI->getOpcode();
2135 
2136   auto IsLegacyVALUFn = [](const MachineInstr &MI) {
2137     return SIInstrInfo::isVALU(MI) && !SIInstrInfo::isMFMA(MI);
2138   };
2139 
2140   auto IsLegacyVALUNotDotFn = [](const MachineInstr &MI) {
2141     return SIInstrInfo::isVALU(MI) && !SIInstrInfo::isMFMA(MI) &&
2142            !SIInstrInfo::isDOT(MI);
2143   };
2144 
2145   if (!SIInstrInfo::isMFMA(*MI))
2146     return WaitStatesNeeded;
2147 
2148   const int VALUWritesExecWaitStates = 4;
2149   int WaitStatesNeededForUse = VALUWritesExecWaitStates -
2150     getWaitStatesSinceDef(AMDGPU::EXEC, IsLegacyVALUFn,
2151                           VALUWritesExecWaitStates);
2152   WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2153 
2154   int SrcCIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
2155 
2156   // Loop for both DGEMM and S/HGEMM 2nd instruction.
2157   for (const MachineOperand &Use : MI->explicit_uses()) {
2158     const int LegacyVALUNotDotWritesVGPRWaitStates = 2;
2159     const int SMFMA4x4WritesVGPROverlappedSMFMASrcCWaitStates = 2;
2160     const int GFX940_XDL2PassWritesVGPROverlappedSMFMASrcCWaitStates = 3;
2161     const int GFX940_XDL4PassWritesVGPROverlappedSMFMASrcCWaitStates = 5;
2162     const int GFX940_SMFMA4PassWritesVGPROverlappedSMFMASrcCWaitStates = 4;
2163     const int GFX940_XDL8PassWritesVGPROverlappedSMFMASrcCWaitStates = 9;
2164     const int GFX940_SMFMA8PassWritesVGPROverlappedSMFMASrcCWaitStates = 8;
2165     const int GFX940_XDL16PassWritesVGPROverlappedSMFMASrcCWaitStates = 17;
2166     const int GFX940_SMFMA16PassWritesVGPROverlappedSMFMASrcCWaitStates = 16;
2167     const int SMFMA16x16WritesVGPROverlappedSMFMASrcCWaitStates = 8;
2168     const int SMFMA32x32WritesVGPROverlappedSMFMASrcCWaitStates = 16;
2169     const int SMFMA4x4WritesVGPROverlappedDMFMASrcCWaitStates = 3;
2170     const int SMFMA16x16WritesVGPROverlappedDMFMASrcCWaitStates = 9;
2171     const int SMFMA32x32WritesVGPROverlappedDMFMASrcCWaitStates = 17;
2172     const int DMFMA16x16WritesVGPROverlappedSrcCWaitStates = 9;
2173     const int DMFMA4x4WritesVGPROverlappedSrcCWaitStates = 4;
2174     const int SMFMA4x4WritesVGPROverlappedSrcABWaitStates = 5;
2175     const int SMFMA16x16WritesVGPROverlappedSrcABWaitStates = 11;
2176     const int SMFMA32x32WritesVGPROverlappedSrcABWaitStates = 19;
2177     const int GFX940_SMFMA2PassWritesVGPROverlappedSrcABWaitStates = 4;
2178     const int GFX940_SMFMA4PassWritesVGPROverlappedSrcABWaitStates = 6;
2179     const int GFX940_SMFMA8PassWritesVGPROverlappedSrcABWaitStates = 10;
2180     const int GFX940_SMFMA16PassWritesVGPROverlappedSrcABWaitStates = 18;
2181     const int GFX940_XDL2PassWritesVGPROverlappedSrcABWaitStates = 5;
2182     const int GFX940_XDL4PassWritesVGPROverlappedSrcABWaitStates = 7;
2183     const int GFX940_XDL8PassWritesVGPROverlappedSrcABWaitStates = 11;
2184     const int GFX940_XDL16PassWritesVGPROverlappedSrcABWaitStates = 19;
2185     const int DMFMA4x4WritesVGPROverlappedMFMASrcABWaitStates = 6;
2186     const int DMFMA16x16WritesVGPROverlappedMFMASrcABWaitStates = 11;
2187     const int DMFMA4x4WritesVGPRFullSrcCWaitStates = 4;
2188     const int GFX940_SMFMA4x4WritesVGPRFullSrcCWaitStates = 2;
2189     const int MaxWaitStates = 19;
2190 
2191     if (!Use.isReg())
2192       continue;
2193     Register Reg = Use.getReg();
2194     bool FullReg;
2195     const MachineInstr *MI1;
2196 
2197     auto IsOverlappedMFMAFn = [Reg, &FullReg, &MI1,
2198                                this](const MachineInstr &MI) {
2199       if (!SIInstrInfo::isMFMA(MI))
2200         return false;
2201       Register DstReg = MI.getOperand(0).getReg();
2202       FullReg = (DstReg == Reg);
2203       MI1 = &MI;
2204       return TRI.regsOverlap(DstReg, Reg);
2205     };
2206 
2207     WaitStatesNeededForUse = LegacyVALUNotDotWritesVGPRWaitStates -
2208       getWaitStatesSinceDef(Reg, IsLegacyVALUNotDotFn, MaxWaitStates);
2209     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2210 
2211     int NumWaitStates =
2212         getWaitStatesSinceDef(Reg, IsOverlappedMFMAFn, MaxWaitStates);
2213     if (NumWaitStates == std::numeric_limits<int>::max())
2214       continue;
2215 
2216     int OpNo = Use.getOperandNo();
2217     unsigned Opc1 = MI1->getOpcode();
2218     int NeedWaitStates = 0;
2219     if (OpNo == SrcCIdx) {
2220       if (!isDGEMM(Opc) && (!ST.hasGFX940Insts() && isDGEMM(Opc1))) {
2221         NeedWaitStates = 0;
2222       } else if (FullReg) {
2223         if ((Opc == AMDGPU::V_MFMA_F64_4X4X4F64_e64 ||
2224              Opc == AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64) &&
2225             (Opc1 == AMDGPU::V_MFMA_F64_4X4X4F64_e64 ||
2226              Opc1 == AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64))
2227           NeedWaitStates = DMFMA4x4WritesVGPRFullSrcCWaitStates;
2228         else if (ST.hasGFX940Insts() &&
2229                  TSchedModel.computeInstrLatency(MI1) == 2)
2230           NeedWaitStates = GFX940_SMFMA4x4WritesVGPRFullSrcCWaitStates;
2231       } else {
2232         switch (Opc1) {
2233         case AMDGPU::V_MFMA_F64_16X16X4F64_e64:
2234         case AMDGPU::V_MFMA_F64_16X16X4F64_vgprcd_e64:
2235         case AMDGPU::V_MFMA_F64_16X16X4F64_mac_e64:
2236         case AMDGPU::V_MFMA_F64_16X16X4F64_mac_vgprcd_e64:
2237           if (!isXDL(ST, *MI))
2238             NeedWaitStates = DMFMA16x16WritesVGPROverlappedSrcCWaitStates;
2239           break;
2240         case AMDGPU::V_MFMA_F64_4X4X4F64_e64:
2241         case AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64:
2242           if (!isXDL(ST, *MI))
2243             NeedWaitStates = DMFMA4x4WritesVGPROverlappedSrcCWaitStates;
2244           break;
2245         default:
2246           if (ST.hasGFX940Insts() && isXDL(ST, *MI) && !isXDL(ST, *MI1))
2247             break;
2248           switch (TSchedModel.computeInstrLatency(MI1)) {
2249           case 2:
2250             NeedWaitStates = ST.hasGFX940Insts()
2251               ? isXDL(ST, *MI1)
2252                 ? GFX940_XDL2PassWritesVGPROverlappedSMFMASrcCWaitStates
2253                 : SMFMA4x4WritesVGPROverlappedSMFMASrcCWaitStates
2254               : isDGEMM(Opc)
2255                 ? SMFMA4x4WritesVGPROverlappedDMFMASrcCWaitStates
2256                 : SMFMA4x4WritesVGPROverlappedSMFMASrcCWaitStates;
2257             break;
2258           case 4:
2259             assert(ST.hasGFX940Insts());
2260             NeedWaitStates = isXDL(ST, *MI1)
2261               ? GFX940_XDL4PassWritesVGPROverlappedSMFMASrcCWaitStates
2262               : GFX940_SMFMA4PassWritesVGPROverlappedSMFMASrcCWaitStates;
2263             break;
2264           case 8:
2265             NeedWaitStates = ST.hasGFX940Insts()
2266               ? isXDL(ST, *MI1)
2267                 ? GFX940_XDL8PassWritesVGPROverlappedSMFMASrcCWaitStates
2268                 : GFX940_SMFMA8PassWritesVGPROverlappedSMFMASrcCWaitStates
2269               : isDGEMM(Opc)
2270                 ? SMFMA16x16WritesVGPROverlappedDMFMASrcCWaitStates
2271                 : SMFMA16x16WritesVGPROverlappedSMFMASrcCWaitStates;
2272             break;
2273           case 16: [[fallthrough]];
2274           default:
2275             NeedWaitStates = ST.hasGFX940Insts()
2276               ? isXDL(ST, *MI1)
2277                 ? GFX940_XDL16PassWritesVGPROverlappedSMFMASrcCWaitStates
2278                 : GFX940_SMFMA16PassWritesVGPROverlappedSMFMASrcCWaitStates
2279               : isDGEMM(Opc)
2280                 ? SMFMA32x32WritesVGPROverlappedDMFMASrcCWaitStates
2281                 : SMFMA32x32WritesVGPROverlappedSMFMASrcCWaitStates;
2282           }
2283         }
2284       }
2285     } else {
2286       switch (Opc1) {
2287       case AMDGPU::V_MFMA_F64_16X16X4F64_e64:
2288       case AMDGPU::V_MFMA_F64_16X16X4F64_vgprcd_e64:
2289       case AMDGPU::V_MFMA_F64_16X16X4F64_mac_e64:
2290       case AMDGPU::V_MFMA_F64_16X16X4F64_mac_vgprcd_e64:
2291         NeedWaitStates = DMFMA16x16WritesVGPROverlappedMFMASrcABWaitStates;
2292         break;
2293       case AMDGPU::V_MFMA_F64_4X4X4F64_e64:
2294       case AMDGPU::V_MFMA_F64_4X4X4F64_vgprcd_e64:
2295         NeedWaitStates = DMFMA4x4WritesVGPROverlappedMFMASrcABWaitStates;
2296         break;
2297       default:
2298         switch (TSchedModel.computeInstrLatency(MI1)) {
2299         case 2:
2300           NeedWaitStates = ST.hasGFX940Insts()
2301             ? isXDL(ST, *MI1)
2302               ? GFX940_XDL2PassWritesVGPROverlappedSrcABWaitStates
2303               : GFX940_SMFMA2PassWritesVGPROverlappedSrcABWaitStates
2304             : SMFMA4x4WritesVGPROverlappedSrcABWaitStates;
2305           break;
2306         case 4:
2307           assert(ST.hasGFX940Insts());
2308           NeedWaitStates = isXDL(ST, *MI1)
2309             ? GFX940_XDL4PassWritesVGPROverlappedSrcABWaitStates
2310             : GFX940_SMFMA4PassWritesVGPROverlappedSrcABWaitStates;
2311           break;
2312         case 8:
2313           NeedWaitStates = ST.hasGFX940Insts()
2314             ? isXDL(ST, *MI1)
2315               ? GFX940_XDL8PassWritesVGPROverlappedSrcABWaitStates
2316               : GFX940_SMFMA8PassWritesVGPROverlappedSrcABWaitStates
2317             : SMFMA16x16WritesVGPROverlappedSrcABWaitStates;
2318           break;
2319         case 16: [[fallthrough]];
2320         default:
2321           NeedWaitStates = ST.hasGFX940Insts()
2322             ? isXDL(ST, *MI1)
2323               ? GFX940_XDL16PassWritesVGPROverlappedSrcABWaitStates
2324               : GFX940_SMFMA16PassWritesVGPROverlappedSrcABWaitStates
2325             : SMFMA32x32WritesVGPROverlappedSrcABWaitStates;
2326         }
2327       }
2328     }
2329     if (WaitStatesNeeded >= NeedWaitStates)
2330       continue;
2331 
2332     WaitStatesNeededForUse = NeedWaitStates - NumWaitStates;
2333     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2334 
2335     if (WaitStatesNeeded == MaxWaitStates)
2336       break;
2337   }
2338 
2339   return WaitStatesNeeded;
2340 }
2341 
2342 int GCNHazardRecognizer::checkMAILdStHazards(MachineInstr *MI) {
2343   // On gfx90a+ relevant hazards are checked in checkMAIVALUHazards()
2344   if (!ST.hasMAIInsts() || ST.hasGFX90AInsts())
2345     return 0;
2346 
2347   int WaitStatesNeeded = 0;
2348 
2349   auto IsAccVgprReadFn = [](const MachineInstr &MI) {
2350     return MI.getOpcode() == AMDGPU::V_ACCVGPR_READ_B32_e64;
2351   };
2352 
2353   for (const MachineOperand &Op : MI->explicit_uses()) {
2354     if (!Op.isReg() || !TRI.isVGPR(MF.getRegInfo(), Op.getReg()))
2355       continue;
2356 
2357     Register Reg = Op.getReg();
2358 
2359     const int AccVgprReadLdStWaitStates = 2;
2360     const int VALUWriteAccVgprRdWrLdStDepVALUWaitStates = 1;
2361     const int MaxWaitStates = 2;
2362 
2363     int WaitStatesNeededForUse = AccVgprReadLdStWaitStates -
2364       getWaitStatesSinceDef(Reg, IsAccVgprReadFn, MaxWaitStates);
2365     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2366 
2367     if (WaitStatesNeeded == MaxWaitStates)
2368       return WaitStatesNeeded; // Early exit.
2369 
2370     auto IsVALUAccVgprRdWrCheckFn = [Reg, this](const MachineInstr &MI) {
2371       if (MI.getOpcode() != AMDGPU::V_ACCVGPR_READ_B32_e64 &&
2372           MI.getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
2373         return false;
2374       auto IsVALUFn = [](const MachineInstr &MI) {
2375         return SIInstrInfo::isVALU(MI) && !SIInstrInfo::isMAI(MI);
2376       };
2377       return getWaitStatesSinceDef(Reg, IsVALUFn, 2 /*MaxWaitStates*/) <
2378              std::numeric_limits<int>::max();
2379     };
2380 
2381     WaitStatesNeededForUse = VALUWriteAccVgprRdWrLdStDepVALUWaitStates -
2382       getWaitStatesSince(IsVALUAccVgprRdWrCheckFn, MaxWaitStates);
2383     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2384   }
2385 
2386   return WaitStatesNeeded;
2387 }
2388 
2389 int GCNHazardRecognizer::checkMAIVALUHazards(MachineInstr *MI) {
2390   if (!ST.hasGFX90AInsts())
2391     return 0;
2392 
2393   auto IsDGEMMFn = [](const MachineInstr &MI) -> bool {
2394     return isDGEMM(MI.getOpcode());
2395   };
2396 
2397   // This is checked in checkMAIHazards90A()
2398   if (SIInstrInfo::isMFMA(*MI))
2399     return 0;
2400 
2401   const MachineRegisterInfo &MRI = MF.getRegInfo();
2402 
2403   int WaitStatesNeeded = 0;
2404 
2405   bool IsMem = SIInstrInfo::isVMEM(*MI) ||
2406                SIInstrInfo::isFLAT(*MI) ||
2407                SIInstrInfo::isDS(*MI);
2408   bool IsMemOrExport = IsMem || SIInstrInfo::isEXP(*MI);
2409   bool IsVALU = SIInstrInfo::isVALU(*MI);
2410 
2411   const MachineInstr *MFMA = nullptr;
2412   unsigned Reg;
2413   auto IsMFMAWriteFn = [&Reg, &MFMA, this](const MachineInstr &MI) {
2414     if (!SIInstrInfo::isMFMA(MI) ||
2415         !TRI.regsOverlap(MI.getOperand(0).getReg(), Reg))
2416       return false;
2417     MFMA = &MI;
2418     return true;
2419   };
2420 
2421   const MachineInstr *DOT = nullptr;
2422   auto IsDotWriteFn = [&Reg, &DOT, this](const MachineInstr &MI) {
2423     if (!SIInstrInfo::isDOT(MI) ||
2424         !TRI.regsOverlap(MI.getOperand(0).getReg(), Reg))
2425       return false;
2426     DOT = &MI;
2427     return true;
2428   };
2429 
2430   bool DGEMMAfterVALUWrite = false;
2431   auto IsDGEMMHazard = [&DGEMMAfterVALUWrite, this](const MachineInstr &MI) {
2432     // Found DGEMM on reverse traversal to def.
2433     if (isDGEMM(MI.getOpcode()))
2434       DGEMMAfterVALUWrite = true;
2435 
2436     // Only hazard if register is defined by a VALU and a DGEMM is found after
2437     // after the def.
2438     if (!TII.isVALU(MI) || !DGEMMAfterVALUWrite)
2439       return false;
2440 
2441     return true;
2442   };
2443 
2444   int SrcCIdx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
2445                                            AMDGPU::OpName::src2);
2446 
2447   if (IsMemOrExport || IsVALU) {
2448     const int SMFMA4x4WriteVgprVALUMemExpReadWaitStates = 5;
2449     const int SMFMA16x16WriteVgprVALUMemExpReadWaitStates = 11;
2450     const int SMFMA32x32WriteVgprVALUMemExpReadWaitStates = 19;
2451     const int GFX940_SMFMA2PassWriteVgprVALUMemExpReadWaitStates = 4;
2452     const int GFX940_SMFMA4PassWriteVgprVALUMemExpReadWaitStates = 6;
2453     const int GFX940_SMFMA8PassWriteVgprVALUMemExpReadWaitStates = 10;
2454     const int GFX940_SMFMA16PassWriteVgprVALUMemExpReadWaitStates = 18;
2455     const int GFX940_XDL2PassWriteVgprVALUMemExpReadWaitStates = 5;
2456     const int GFX940_XDL4PassWriteVgprVALUMemExpReadWaitStates = 7;
2457     const int GFX940_XDL8PassWriteVgprVALUMemExpReadWaitStates = 11;
2458     const int GFX940_XDL16PassWriteVgprVALUMemExpReadWaitStates = 19;
2459     const int DMFMA4x4WriteVgprMemExpReadWaitStates = 9;
2460     const int DMFMA16x16WriteVgprMemExpReadWaitStates = 18;
2461     const int DMFMA4x4WriteVgprVALUReadWaitStates = 6;
2462     const int DMFMA16x16WriteVgprVALUReadWaitStates = 11;
2463     const int DotWriteSameDotReadSrcAB = 3;
2464     const int DotWriteDifferentVALURead = 3;
2465     const int DMFMABetweenVALUWriteVMEMRead = 2;
2466     const int MaxWaitStates = 19;
2467 
2468     for (const MachineOperand &Use : MI->explicit_uses()) {
2469       if (!Use.isReg())
2470         continue;
2471       Reg = Use.getReg();
2472 
2473       DOT = nullptr;
2474       int WaitStatesSinceDef = getWaitStatesSinceDef(Reg, IsDotWriteFn,
2475                                                      MaxWaitStates);
2476       if (DOT) {
2477         int NeedWaitStates = 0;
2478         if (DOT->getOpcode() == MI->getOpcode()) {
2479           if (&Use - &MI->getOperand(0) != SrcCIdx)
2480             NeedWaitStates = DotWriteSameDotReadSrcAB;
2481         } else {
2482           NeedWaitStates = DotWriteDifferentVALURead;
2483         }
2484 
2485         int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceDef;
2486         WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2487       }
2488 
2489       // Workaround for HW data hazard bug observed only in GFX90A. When there
2490       // is a DGEMM instruction in-between a VALU and a VMEM instruction it
2491       // causes the SQ to incorrectly not insert two wait states between the two
2492       // instructions needed to avoid data hazard.
2493       if (IsMem && ST.hasGFX90AInsts() && !ST.hasGFX940Insts()) {
2494         DGEMMAfterVALUWrite = false;
2495         if (TRI.isVectorRegister(MRI, Reg)) {
2496           int WaitStatesNeededForUse =
2497                 DMFMABetweenVALUWriteVMEMRead -
2498                 getWaitStatesSinceDef(Reg, IsDGEMMHazard,
2499                                       DMFMABetweenVALUWriteVMEMRead);
2500 
2501           WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2502         }
2503       }
2504 
2505       MFMA = nullptr;
2506       WaitStatesSinceDef =
2507           getWaitStatesSinceDef(Reg, IsMFMAWriteFn, MaxWaitStates);
2508       if (!MFMA)
2509         continue;
2510 
2511       unsigned HazardDefLatency = TSchedModel.computeInstrLatency(MFMA);
2512       int NeedWaitStates = MaxWaitStates;
2513       switch (HazardDefLatency) {
2514       case 2:
2515         NeedWaitStates =
2516           ST.hasGFX940Insts()
2517             ? isXDL(ST, *MFMA)
2518               ? GFX940_XDL2PassWriteVgprVALUMemExpReadWaitStates
2519               : GFX940_SMFMA2PassWriteVgprVALUMemExpReadWaitStates
2520             : SMFMA4x4WriteVgprVALUMemExpReadWaitStates;
2521         break;
2522       case 4:
2523         assert(isDGEMM(MFMA->getOpcode()) || ST.hasGFX940Insts());
2524         NeedWaitStates =
2525           isDGEMM(MFMA->getOpcode())
2526             ? IsMemOrExport ? DMFMA4x4WriteVgprMemExpReadWaitStates
2527                             : DMFMA4x4WriteVgprVALUReadWaitStates
2528             : isXDL(ST, *MFMA)
2529               ? GFX940_XDL4PassWriteVgprVALUMemExpReadWaitStates
2530               : GFX940_SMFMA4PassWriteVgprVALUMemExpReadWaitStates;
2531         break;
2532       case 8:
2533         NeedWaitStates =
2534           ST.hasGFX940Insts()
2535             ? isXDL(ST, *MFMA)
2536               ? GFX940_XDL8PassWriteVgprVALUMemExpReadWaitStates
2537               : GFX940_SMFMA8PassWriteVgprVALUMemExpReadWaitStates
2538             : SMFMA16x16WriteVgprVALUMemExpReadWaitStates;
2539         break;
2540       case 16: [[fallthrough]];
2541       default:
2542         NeedWaitStates =
2543           isDGEMM(MFMA->getOpcode())
2544             ? IsMemOrExport ? DMFMA16x16WriteVgprMemExpReadWaitStates
2545                             : DMFMA16x16WriteVgprVALUReadWaitStates
2546             : ST.hasGFX940Insts()
2547               ? isXDL(ST, *MFMA)
2548                 ? GFX940_XDL16PassWriteVgprVALUMemExpReadWaitStates
2549                 : GFX940_SMFMA16PassWriteVgprVALUMemExpReadWaitStates
2550               : SMFMA32x32WriteVgprVALUMemExpReadWaitStates;
2551         break;
2552       }
2553 
2554       int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceDef;
2555       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2556 
2557       if (WaitStatesNeeded == MaxWaitStates)
2558         break;
2559     }
2560   }
2561 
2562   unsigned Opc = MI->getOpcode();
2563   const int DMFMAToFMA64WaitStates = 2;
2564   if ((Opc == AMDGPU::V_FMA_F64_e64 ||
2565        Opc == AMDGPU::V_FMAC_F64_e32 || Opc == AMDGPU::V_FMAC_F64_e64 ||
2566        Opc == AMDGPU::V_FMAC_F64_dpp) &&
2567       WaitStatesNeeded < DMFMAToFMA64WaitStates) {
2568     int WaitStatesNeededForUse = DMFMAToFMA64WaitStates -
2569       getWaitStatesSince(IsDGEMMFn, DMFMAToFMA64WaitStates);
2570     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2571   }
2572 
2573   if (!IsVALU && !IsMemOrExport)
2574     return WaitStatesNeeded;
2575 
2576   for (const MachineOperand &Def : MI->defs()) {
2577     const int SMFMA4x4WriteVgprVALUWawWaitStates = 5;
2578     const int SMFMA16x16WriteVgprVALUWawWaitStates = 11;
2579     const int SMFMA32x32WriteVgprVALUWawWaitStates = 19;
2580     const int GFX940_SMFMA2PassWriteVgprVALUWawWaitStates = 4;
2581     const int GFX940_SMFMA4PassWriteVgprVALUWawWaitStates = 6;
2582     const int GFX940_SMFMA8PassWriteVgprVALUWawWaitStates = 10;
2583     const int GFX940_SMFMA16PassWriteVgprVALUWawWaitStates = 18;
2584     const int GFX940_XDL2PassWriteVgprVALUWawWaitStates = 5;
2585     const int GFX940_XDL4PassWriteVgprVALUWawWaitStates = 7;
2586     const int GFX940_XDL8PassWriteVgprVALUWawWaitStates = 11;
2587     const int GFX940_XDL16PassWriteVgprVALUWawWaitStates = 19;
2588     const int SMFMA4x4ReadVgprVALUWarWaitStates = 1;
2589     const int GFX940_XDL4PassReadVgprVALUWarWaitStates = 3;
2590     const int SMFMA16x16ReadVgprVALUWarWaitStates = 7;
2591     const int SMFMA32x32ReadVgprVALUWarWaitStates = 15;
2592     const int DMFMA4x4WriteVgprVALUWriteWaitStates = 6;
2593     const int DMFMA16x16WriteVgprVALUWriteWaitStates = 11;
2594     const int DotWriteDifferentVALUWrite = 3;
2595     const int MaxWaitStates = 19;
2596     const int MaxWarWaitStates = 15;
2597 
2598     Reg = Def.getReg();
2599 
2600     DOT = nullptr;
2601     int WaitStatesSinceDef = getWaitStatesSinceDef(Reg, IsDotWriteFn,
2602                                                    MaxWaitStates);
2603     if (DOT && DOT->getOpcode() != MI->getOpcode())
2604       WaitStatesNeeded = std::max(WaitStatesNeeded, DotWriteDifferentVALUWrite -
2605                                                     WaitStatesSinceDef);
2606 
2607     MFMA = nullptr;
2608     WaitStatesSinceDef =
2609         getWaitStatesSinceDef(Reg, IsMFMAWriteFn, MaxWaitStates);
2610     if (MFMA) {
2611       int NeedWaitStates = MaxWaitStates;
2612       switch (TSchedModel.computeInstrLatency(MFMA)) {
2613       case 2:
2614         NeedWaitStates = ST.hasGFX940Insts()
2615           ? isXDL(ST, *MFMA)
2616             ? GFX940_XDL2PassWriteVgprVALUWawWaitStates
2617             : GFX940_SMFMA2PassWriteVgprVALUWawWaitStates
2618           : SMFMA4x4WriteVgprVALUWawWaitStates;
2619         break;
2620       case 4:
2621         assert(isDGEMM(MFMA->getOpcode()) || ST.hasGFX940Insts());
2622         NeedWaitStates = isDGEMM(MFMA->getOpcode())
2623             ? DMFMA4x4WriteVgprVALUWriteWaitStates
2624             : isXDL(ST, *MFMA)
2625               ? GFX940_XDL4PassWriteVgprVALUWawWaitStates
2626               : GFX940_SMFMA4PassWriteVgprVALUWawWaitStates;
2627         break;
2628       case 8:
2629         NeedWaitStates = ST.hasGFX940Insts()
2630           ? isXDL(ST, *MFMA)
2631             ? GFX940_XDL8PassWriteVgprVALUWawWaitStates
2632             : GFX940_SMFMA8PassWriteVgprVALUWawWaitStates
2633           : SMFMA16x16WriteVgprVALUWawWaitStates;
2634         break;
2635       case 16: [[fallthrough]];
2636       default:
2637         NeedWaitStates = isDGEMM(MFMA->getOpcode())
2638                    ? DMFMA16x16WriteVgprVALUWriteWaitStates
2639                    : ST.hasGFX940Insts()
2640                      ? isXDL(ST, *MFMA)
2641                        ? GFX940_XDL16PassWriteVgprVALUWawWaitStates
2642                        : GFX940_SMFMA16PassWriteVgprVALUWawWaitStates
2643                    : SMFMA32x32WriteVgprVALUWawWaitStates;
2644         break;
2645       }
2646 
2647       int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceDef;
2648       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2649 
2650       if (WaitStatesNeeded == MaxWaitStates)
2651         break;
2652     }
2653 
2654     auto IsSMFMAReadAsCFn = [&Reg, &MFMA, this](const MachineInstr &MI) {
2655       if (!SIInstrInfo::isMFMA(MI) || isDGEMM(MI.getOpcode()) ||
2656           !MI.readsRegister(Reg, &TRI))
2657         return false;
2658 
2659       if (ST.hasGFX940Insts() && !isXDL(ST, MI))
2660         return false;
2661 
2662       const MachineOperand *SrcC =
2663           TII.getNamedOperand(MI, AMDGPU::OpName::src2);
2664       assert(SrcC);
2665       if (!SrcC->isReg() || !TRI.regsOverlap(SrcC->getReg(), Reg))
2666         return false;
2667 
2668       MFMA = &MI;
2669       return true;
2670     };
2671 
2672     MFMA = nullptr;
2673     int WaitStatesSinceUse = getWaitStatesSince(IsSMFMAReadAsCFn,
2674                                                 MaxWarWaitStates);
2675     if (!MFMA)
2676       continue;
2677 
2678     unsigned HazardDefLatency = TSchedModel.computeInstrLatency(MFMA);
2679     int NeedWaitStates = MaxWaitStates;
2680     switch (HazardDefLatency) {
2681     case 2:  NeedWaitStates = SMFMA4x4ReadVgprVALUWarWaitStates;
2682              break;
2683     case 4:  assert(ST.hasGFX940Insts());
2684              NeedWaitStates = GFX940_XDL4PassReadVgprVALUWarWaitStates;
2685              break;
2686     case 8:  NeedWaitStates = SMFMA16x16ReadVgprVALUWarWaitStates;
2687              break;
2688     case 16: [[fallthrough]];
2689     default: NeedWaitStates = SMFMA32x32ReadVgprVALUWarWaitStates;
2690              break;
2691     }
2692 
2693     int WaitStatesNeededForUse = NeedWaitStates - WaitStatesSinceUse;
2694     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
2695   }
2696 
2697   return WaitStatesNeeded;
2698 }
2699 
2700 bool GCNHazardRecognizer::ShouldPreferAnother(SUnit *SU) {
2701   if (!SU->isInstr())
2702     return false;
2703 
2704   const MachineInstr *MAI = nullptr;
2705 
2706   auto IsMFMAFn = [&MAI](const MachineInstr &MI) {
2707     MAI = nullptr;
2708     if (SIInstrInfo::isMFMA(MI))
2709       MAI = &MI;
2710     return MAI != nullptr;
2711   };
2712 
2713   MachineInstr *MI = SU->getInstr();
2714   if (IsMFMAFn(*MI)) {
2715     int W = getWaitStatesSince(IsMFMAFn, 16);
2716     if (MAI)
2717       return W < (int)TSchedModel.computeInstrLatency(MAI);
2718   }
2719 
2720   return false;
2721 }
2722 
2723 bool GCNHazardRecognizer::fixVALUMaskWriteHazard(MachineInstr *MI) {
2724   if (!ST.isWave64())
2725     return false;
2726   if (!ST.hasVALUMaskWriteHazard())
2727     return false;
2728   if (!SIInstrInfo::isSALU(*MI))
2729     return false;
2730 
2731   // The hazard sequence is three instructions:
2732   //   1. VALU reads SGPR as mask
2733   //   2. SALU writes SGPR
2734   //   3. SALU reads SGPR
2735   // The hazard can expire if the distance between 2 and 3 is sufficient.
2736   // In practice this happens <10% of the time, hence this always assumes
2737   // the hazard exists if 1 and 2 are present to avoid searching.
2738 
2739   const MachineOperand *SDSTOp = TII.getNamedOperand(*MI, AMDGPU::OpName::sdst);
2740   if (!SDSTOp || !SDSTOp->isReg())
2741     return false;
2742 
2743   const Register HazardReg = SDSTOp->getReg();
2744   if (HazardReg == AMDGPU::EXEC ||
2745       HazardReg == AMDGPU::EXEC_LO ||
2746       HazardReg == AMDGPU::EXEC_HI ||
2747       HazardReg == AMDGPU::M0)
2748     return false;
2749 
2750   auto IsHazardFn = [HazardReg, this](const MachineInstr &I) {
2751     switch (I.getOpcode()) {
2752     case AMDGPU::V_ADDC_U32_e32:
2753     case AMDGPU::V_ADDC_U32_dpp:
2754     case AMDGPU::V_CNDMASK_B16_e32:
2755     case AMDGPU::V_CNDMASK_B16_dpp:
2756     case AMDGPU::V_CNDMASK_B32_e32:
2757     case AMDGPU::V_CNDMASK_B32_dpp:
2758     case AMDGPU::V_DIV_FMAS_F32_e64:
2759     case AMDGPU::V_DIV_FMAS_F64_e64:
2760     case AMDGPU::V_SUBB_U32_e32:
2761     case AMDGPU::V_SUBB_U32_dpp:
2762     case AMDGPU::V_SUBBREV_U32_e32:
2763     case AMDGPU::V_SUBBREV_U32_dpp:
2764       // These implicitly read VCC as mask source.
2765       return HazardReg == AMDGPU::VCC ||
2766              HazardReg == AMDGPU::VCC_LO ||
2767              HazardReg == AMDGPU::VCC_HI;
2768     case AMDGPU::V_ADDC_U32_e64:
2769     case AMDGPU::V_ADDC_U32_e64_dpp:
2770     case AMDGPU::V_CNDMASK_B16_e64:
2771     case AMDGPU::V_CNDMASK_B16_e64_dpp:
2772     case AMDGPU::V_CNDMASK_B32_e64:
2773     case AMDGPU::V_CNDMASK_B32_e64_dpp:
2774     case AMDGPU::V_SUBB_U32_e64:
2775     case AMDGPU::V_SUBB_U32_e64_dpp:
2776     case AMDGPU::V_SUBBREV_U32_e64:
2777     case AMDGPU::V_SUBBREV_U32_e64_dpp: {
2778       // Only check mask register overlaps.
2779       const MachineOperand *SSRCOp = TII.getNamedOperand(I, AMDGPU::OpName::src2);
2780       assert(SSRCOp);
2781       return TRI.regsOverlap(SSRCOp->getReg(), HazardReg);
2782     }
2783     default:
2784       return false;
2785     }
2786   };
2787 
2788   const MachineRegisterInfo &MRI = MF.getRegInfo();
2789   auto IsExpiredFn = [&MRI, this](const MachineInstr &I, int) {
2790     // s_waitcnt_depctr sa_sdst(0) mitigates hazard.
2791     if (I.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
2792         AMDGPU::DepCtr::decodeFieldSaSdst(I.getOperand(0).getImm()) == 0)
2793       return true;
2794 
2795     // VALU access to any SGPR or literal constant other than HazardReg
2796     // mitigates hazard. No need to check HazardReg here as this will
2797     // only be called when !IsHazardFn.
2798     if (!SIInstrInfo::isVALU(I))
2799       return false;
2800     for (int OpNo = 0, End = I.getNumOperands(); OpNo < End; ++OpNo) {
2801       const MachineOperand &Op = I.getOperand(OpNo);
2802       if (Op.isReg()) {
2803         Register OpReg = Op.getReg();
2804         // Only consider uses
2805         if (!Op.isUse())
2806           continue;
2807         // Ignore EXEC
2808         if (OpReg == AMDGPU::EXEC ||
2809             OpReg == AMDGPU::EXEC_LO ||
2810             OpReg == AMDGPU::EXEC_HI)
2811           continue;
2812         // Ignore all implicit uses except VCC
2813         if (Op.isImplicit()) {
2814           if (OpReg == AMDGPU::VCC ||
2815               OpReg == AMDGPU::VCC_LO ||
2816               OpReg == AMDGPU::VCC_HI)
2817             return true;
2818           continue;
2819         }
2820         if (TRI.isSGPRReg(MRI, OpReg))
2821           return true;
2822       } else {
2823         const MCInstrDesc &InstDesc = I.getDesc();
2824         const MCOperandInfo &OpInfo = InstDesc.operands()[OpNo];
2825         if (!TII.isInlineConstant(Op, OpInfo))
2826           return true;
2827       }
2828     }
2829     return false;
2830   };
2831 
2832   // Check for hazard
2833   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
2834       std::numeric_limits<int>::max())
2835     return false;
2836 
2837   auto NextMI = std::next(MI->getIterator());
2838 
2839   // Add s_waitcnt_depctr sa_sdst(0) after SALU write.
2840   BuildMI(*MI->getParent(), NextMI, MI->getDebugLoc(),
2841           TII.get(AMDGPU::S_WAITCNT_DEPCTR))
2842       .addImm(AMDGPU::DepCtr::encodeFieldSaSdst(0));
2843 
2844   // SALU write may be s_getpc in a bundle.
2845   if (MI->getOpcode() == AMDGPU::S_GETPC_B64) {
2846     // Update offsets of any references in the bundle.
2847     while (NextMI != MI->getParent()->end() &&
2848            NextMI->isBundledWithPred()) {
2849       for (auto &Operand : NextMI->operands()) {
2850         if (Operand.isGlobal())
2851           Operand.setOffset(Operand.getOffset() + 4);
2852       }
2853       NextMI++;
2854     }
2855   }
2856 
2857   return true;
2858 }
2859