xref: /llvm-project/llvm/lib/Target/AMDGPU/GCNHazardRecognizer.cpp (revision e4c2e9b016c411cb75d3c1877007bace03d3b37f)
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 "AMDGPUSubtarget.h"
15 #include "SIDefines.h"
16 #include "SIInstrInfo.h"
17 #include "SIRegisterInfo.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "Utils/AMDGPUBaseInfo.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/ScheduleDAG.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include <algorithm>
29 #include <cassert>
30 #include <limits>
31 #include <set>
32 #include <vector>
33 
34 using namespace llvm;
35 
36 //===----------------------------------------------------------------------===//
37 // Hazard Recoginizer Implementation
38 //===----------------------------------------------------------------------===//
39 
40 GCNHazardRecognizer::GCNHazardRecognizer(const MachineFunction &MF) :
41   IsHazardRecognizerMode(false),
42   CurrCycleInstr(nullptr),
43   MF(MF),
44   ST(MF.getSubtarget<GCNSubtarget>()),
45   TII(*ST.getInstrInfo()),
46   TRI(TII.getRegisterInfo()),
47   ClauseUses(TRI.getNumRegUnits()),
48   ClauseDefs(TRI.getNumRegUnits()) {
49   MaxLookAhead = 5;
50 }
51 
52 void GCNHazardRecognizer::EmitInstruction(SUnit *SU) {
53   EmitInstruction(SU->getInstr());
54 }
55 
56 void GCNHazardRecognizer::EmitInstruction(MachineInstr *MI) {
57   CurrCycleInstr = MI;
58 }
59 
60 static bool isDivFMas(unsigned Opcode) {
61   return Opcode == AMDGPU::V_DIV_FMAS_F32 || Opcode == AMDGPU::V_DIV_FMAS_F64;
62 }
63 
64 static bool isSGetReg(unsigned Opcode) {
65   return Opcode == AMDGPU::S_GETREG_B32;
66 }
67 
68 static bool isSSetReg(unsigned Opcode) {
69   return Opcode == AMDGPU::S_SETREG_B32 || Opcode == AMDGPU::S_SETREG_IMM32_B32;
70 }
71 
72 static bool isRWLane(unsigned Opcode) {
73   return Opcode == AMDGPU::V_READLANE_B32 || Opcode == AMDGPU::V_WRITELANE_B32;
74 }
75 
76 static bool isRFE(unsigned Opcode) {
77   return Opcode == AMDGPU::S_RFE_B64;
78 }
79 
80 static bool isSMovRel(unsigned Opcode) {
81   switch (Opcode) {
82   case AMDGPU::S_MOVRELS_B32:
83   case AMDGPU::S_MOVRELS_B64:
84   case AMDGPU::S_MOVRELD_B32:
85   case AMDGPU::S_MOVRELD_B64:
86     return true;
87   default:
88     return false;
89   }
90 }
91 
92 static bool isSendMsgTraceDataOrGDS(const SIInstrInfo &TII,
93                                     const MachineInstr &MI) {
94   if (TII.isAlwaysGDS(MI.getOpcode()))
95     return true;
96 
97   switch (MI.getOpcode()) {
98   case AMDGPU::S_SENDMSG:
99   case AMDGPU::S_SENDMSGHALT:
100   case AMDGPU::S_TTRACEDATA:
101     return true;
102   // These DS opcodes don't support GDS.
103   case AMDGPU::DS_NOP:
104   case AMDGPU::DS_PERMUTE_B32:
105   case AMDGPU::DS_BPERMUTE_B32:
106     return false;
107   default:
108     if (TII.isDS(MI.getOpcode())) {
109       int GDS = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
110                                            AMDGPU::OpName::gds);
111       if (MI.getOperand(GDS).getImm())
112         return true;
113     }
114     return false;
115   }
116 }
117 
118 static bool isPermlane(const MachineInstr &MI) {
119   unsigned Opcode = MI.getOpcode();
120   return Opcode == AMDGPU::V_PERMLANE16_B32 ||
121          Opcode == AMDGPU::V_PERMLANEX16_B32;
122 }
123 
124 static unsigned getHWReg(const SIInstrInfo *TII, const MachineInstr &RegInstr) {
125   const MachineOperand *RegOp = TII->getNamedOperand(RegInstr,
126                                                      AMDGPU::OpName::simm16);
127   return RegOp->getImm() & AMDGPU::Hwreg::ID_MASK_;
128 }
129 
130 ScheduleHazardRecognizer::HazardType
131 GCNHazardRecognizer::getHazardType(SUnit *SU, int Stalls) {
132   MachineInstr *MI = SU->getInstr();
133   if (MI->isBundle())
134    return NoHazard;
135 
136   if (SIInstrInfo::isSMRD(*MI) && checkSMRDHazards(MI) > 0)
137     return NoopHazard;
138 
139   // FIXME: Should flat be considered vmem?
140   if ((SIInstrInfo::isVMEM(*MI) ||
141        SIInstrInfo::isFLAT(*MI))
142       && checkVMEMHazards(MI) > 0)
143     return NoopHazard;
144 
145   if (ST.hasNSAtoVMEMBug() && checkNSAtoVMEMHazard(MI) > 0)
146     return NoopHazard;
147 
148   if (ST.hasNoDataDepHazard())
149     return NoHazard;
150 
151   if (SIInstrInfo::isVALU(*MI) && checkVALUHazards(MI) > 0)
152     return NoopHazard;
153 
154   if (SIInstrInfo::isDPP(*MI) && checkDPPHazards(MI) > 0)
155     return NoopHazard;
156 
157   if (isDivFMas(MI->getOpcode()) && checkDivFMasHazards(MI) > 0)
158     return NoopHazard;
159 
160   if (isRWLane(MI->getOpcode()) && checkRWLaneHazards(MI) > 0)
161     return NoopHazard;
162 
163   if (isSGetReg(MI->getOpcode()) && checkGetRegHazards(MI) > 0)
164     return NoopHazard;
165 
166   if (isSSetReg(MI->getOpcode()) && checkSetRegHazards(MI) > 0)
167     return NoopHazard;
168 
169   if (isRFE(MI->getOpcode()) && checkRFEHazards(MI) > 0)
170     return NoopHazard;
171 
172   if (ST.hasReadM0MovRelInterpHazard() &&
173       (TII.isVINTRP(*MI) || isSMovRel(MI->getOpcode())) &&
174       checkReadM0Hazards(MI) > 0)
175     return NoopHazard;
176 
177   if (ST.hasReadM0SendMsgHazard() && isSendMsgTraceDataOrGDS(TII, *MI) &&
178       checkReadM0Hazards(MI) > 0)
179     return NoopHazard;
180 
181   if (MI->isInlineAsm() && checkInlineAsmHazards(MI) > 0)
182     return NoopHazard;
183 
184   if (checkAnyInstHazards(MI) > 0)
185     return NoopHazard;
186 
187   return NoHazard;
188 }
189 
190 static void insertNoopInBundle(MachineInstr *MI, const SIInstrInfo &TII) {
191   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII.get(AMDGPU::S_NOP))
192       .addImm(0);
193 }
194 
195 void GCNHazardRecognizer::processBundle() {
196   MachineBasicBlock::instr_iterator MI = std::next(CurrCycleInstr->getIterator());
197   MachineBasicBlock::instr_iterator E = CurrCycleInstr->getParent()->instr_end();
198   // Check bundled MachineInstr's for hazards.
199   for (; MI != E && MI->isInsideBundle(); ++MI) {
200     CurrCycleInstr = &*MI;
201     unsigned WaitStates = PreEmitNoopsCommon(CurrCycleInstr);
202 
203     if (IsHazardRecognizerMode)
204       fixHazards(CurrCycleInstr);
205 
206     for (unsigned i = 0; i < WaitStates; ++i)
207       insertNoopInBundle(CurrCycleInstr, TII);
208 
209     // It’s unnecessary to track more than MaxLookAhead instructions. Since we
210     // include the bundled MI directly after, only add a maximum of
211     // (MaxLookAhead - 1) noops to EmittedInstrs.
212     for (unsigned i = 0, e = std::min(WaitStates, MaxLookAhead - 1); i < e; ++i)
213       EmittedInstrs.push_front(nullptr);
214 
215     EmittedInstrs.push_front(CurrCycleInstr);
216     EmittedInstrs.resize(MaxLookAhead);
217   }
218   CurrCycleInstr = nullptr;
219 }
220 
221 unsigned GCNHazardRecognizer::PreEmitNoops(SUnit *SU) {
222   IsHazardRecognizerMode = false;
223   return PreEmitNoopsCommon(SU->getInstr());
224 }
225 
226 unsigned GCNHazardRecognizer::PreEmitNoops(MachineInstr *MI) {
227   IsHazardRecognizerMode = true;
228   CurrCycleInstr = MI;
229   unsigned W = PreEmitNoopsCommon(MI);
230   fixHazards(MI);
231   CurrCycleInstr = nullptr;
232   return W;
233 }
234 
235 unsigned GCNHazardRecognizer::PreEmitNoopsCommon(MachineInstr *MI) {
236   if (MI->isBundle())
237     return 0;
238 
239   int WaitStates = std::max(0, checkAnyInstHazards(MI));
240 
241   if (SIInstrInfo::isSMRD(*MI))
242     return std::max(WaitStates, checkSMRDHazards(MI));
243 
244   if (SIInstrInfo::isVMEM(*MI) || SIInstrInfo::isFLAT(*MI))
245     WaitStates = std::max(WaitStates, checkVMEMHazards(MI));
246 
247   if (ST.hasNSAtoVMEMBug())
248     WaitStates = std::max(WaitStates, checkNSAtoVMEMHazard(MI));
249 
250   if (ST.hasNoDataDepHazard())
251     return WaitStates;
252 
253   if (SIInstrInfo::isVALU(*MI))
254     WaitStates = std::max(WaitStates, checkVALUHazards(MI));
255 
256   if (SIInstrInfo::isDPP(*MI))
257     WaitStates = std::max(WaitStates, checkDPPHazards(MI));
258 
259   if (isDivFMas(MI->getOpcode()))
260     WaitStates = std::max(WaitStates, checkDivFMasHazards(MI));
261 
262   if (isRWLane(MI->getOpcode()))
263     WaitStates = std::max(WaitStates, checkRWLaneHazards(MI));
264 
265   if (MI->isInlineAsm())
266     return std::max(WaitStates, checkInlineAsmHazards(MI));
267 
268   if (isSGetReg(MI->getOpcode()))
269     return std::max(WaitStates, checkGetRegHazards(MI));
270 
271   if (isSSetReg(MI->getOpcode()))
272     return std::max(WaitStates, checkSetRegHazards(MI));
273 
274   if (isRFE(MI->getOpcode()))
275     return std::max(WaitStates, checkRFEHazards(MI));
276 
277   if (ST.hasReadM0MovRelInterpHazard() && (TII.isVINTRP(*MI) ||
278                                            isSMovRel(MI->getOpcode())))
279     return std::max(WaitStates, checkReadM0Hazards(MI));
280 
281   if (ST.hasReadM0SendMsgHazard() && isSendMsgTraceDataOrGDS(TII, *MI))
282     return std::max(WaitStates, checkReadM0Hazards(MI));
283 
284   return WaitStates;
285 }
286 
287 void GCNHazardRecognizer::EmitNoop() {
288   EmittedInstrs.push_front(nullptr);
289 }
290 
291 void GCNHazardRecognizer::AdvanceCycle() {
292   // When the scheduler detects a stall, it will call AdvanceCycle() without
293   // emitting any instructions.
294   if (!CurrCycleInstr)
295     return;
296 
297   // Do not track non-instructions which do not affect the wait states.
298   // If included, these instructions can lead to buffer overflow such that
299   // detectable hazards are missed.
300   if (CurrCycleInstr->isImplicitDef() || CurrCycleInstr->isDebugInstr() ||
301       CurrCycleInstr->isKill())
302     return;
303 
304   if (CurrCycleInstr->isBundle()) {
305     processBundle();
306     return;
307   }
308 
309   unsigned NumWaitStates = TII.getNumWaitStates(*CurrCycleInstr);
310 
311   // Keep track of emitted instructions
312   EmittedInstrs.push_front(CurrCycleInstr);
313 
314   // Add a nullptr for each additional wait state after the first.  Make sure
315   // not to add more than getMaxLookAhead() items to the list, since we
316   // truncate the list to that size right after this loop.
317   for (unsigned i = 1, e = std::min(NumWaitStates, getMaxLookAhead());
318        i < e; ++i) {
319     EmittedInstrs.push_front(nullptr);
320   }
321 
322   // getMaxLookahead() is the largest number of wait states we will ever need
323   // to insert, so there is no point in keeping track of more than that many
324   // wait states.
325   EmittedInstrs.resize(getMaxLookAhead());
326 
327   CurrCycleInstr = nullptr;
328 }
329 
330 void GCNHazardRecognizer::RecedeCycle() {
331   llvm_unreachable("hazard recognizer does not support bottom-up scheduling.");
332 }
333 
334 //===----------------------------------------------------------------------===//
335 // Helper Functions
336 //===----------------------------------------------------------------------===//
337 
338 typedef function_ref<bool(MachineInstr *, int WaitStates)> IsExpiredFn;
339 
340 // Returns a minimum wait states since \p I walking all predecessors.
341 // Only scans until \p IsExpired does not return true.
342 // Can only be run in a hazard recognizer mode.
343 static int getWaitStatesSince(GCNHazardRecognizer::IsHazardFn IsHazard,
344                               MachineBasicBlock *MBB,
345                               MachineBasicBlock::reverse_instr_iterator I,
346                               int WaitStates,
347                               IsExpiredFn IsExpired,
348                               DenseSet<const MachineBasicBlock *> &Visited) {
349   for (auto E = MBB->instr_rend(); I != E; ++I) {
350     // Don't add WaitStates for parent BUNDLE instructions.
351     if (I->isBundle())
352       continue;
353 
354     if (IsHazard(&*I))
355       return WaitStates;
356 
357     if (I->isInlineAsm() || I->isImplicitDef() || I->isDebugInstr())
358       continue;
359 
360     WaitStates += SIInstrInfo::getNumWaitStates(*I);
361 
362     if (IsExpired(&*I, WaitStates))
363       return std::numeric_limits<int>::max();
364   }
365 
366   int MinWaitStates = WaitStates;
367   bool Found = false;
368   for (MachineBasicBlock *Pred : MBB->predecessors()) {
369     if (!Visited.insert(Pred).second)
370       continue;
371 
372     int W = getWaitStatesSince(IsHazard, Pred, Pred->instr_rbegin(),
373                                WaitStates, IsExpired, Visited);
374 
375     if (W == std::numeric_limits<int>::max())
376       continue;
377 
378     MinWaitStates = Found ? std::min(MinWaitStates, W) : W;
379     if (IsExpired(nullptr, MinWaitStates))
380       return MinWaitStates;
381 
382     Found = true;
383   }
384 
385   if (Found)
386     return MinWaitStates;
387 
388   return std::numeric_limits<int>::max();
389 }
390 
391 static int getWaitStatesSince(GCNHazardRecognizer::IsHazardFn IsHazard,
392                               MachineInstr *MI,
393                               IsExpiredFn IsExpired) {
394   DenseSet<const MachineBasicBlock *> Visited;
395   return getWaitStatesSince(IsHazard, MI->getParent(),
396                             std::next(MI->getReverseIterator()),
397                             0, IsExpired, Visited);
398 }
399 
400 int GCNHazardRecognizer::getWaitStatesSince(IsHazardFn IsHazard, int Limit) {
401   if (IsHazardRecognizerMode) {
402     auto IsExpiredFn = [Limit] (MachineInstr *, int WaitStates) {
403       return WaitStates >= Limit;
404     };
405     return ::getWaitStatesSince(IsHazard, CurrCycleInstr, IsExpiredFn);
406   }
407 
408   int WaitStates = 0;
409   for (MachineInstr *MI : EmittedInstrs) {
410     if (MI) {
411       if (IsHazard(MI))
412         return WaitStates;
413 
414       if (MI->isInlineAsm())
415         continue;
416     }
417     ++WaitStates;
418 
419     if (WaitStates >= Limit)
420       break;
421   }
422   return std::numeric_limits<int>::max();
423 }
424 
425 int GCNHazardRecognizer::getWaitStatesSinceDef(unsigned Reg,
426                                                IsHazardFn IsHazardDef,
427                                                int Limit) {
428   const SIRegisterInfo *TRI = ST.getRegisterInfo();
429 
430   auto IsHazardFn = [IsHazardDef, TRI, Reg] (MachineInstr *MI) {
431     return IsHazardDef(MI) && MI->modifiesRegister(Reg, TRI);
432   };
433 
434   return getWaitStatesSince(IsHazardFn, Limit);
435 }
436 
437 int GCNHazardRecognizer::getWaitStatesSinceSetReg(IsHazardFn IsHazard,
438                                                   int Limit) {
439   auto IsHazardFn = [IsHazard] (MachineInstr *MI) {
440     return isSSetReg(MI->getOpcode()) && IsHazard(MI);
441   };
442 
443   return getWaitStatesSince(IsHazardFn, Limit);
444 }
445 
446 //===----------------------------------------------------------------------===//
447 // No-op Hazard Detection
448 //===----------------------------------------------------------------------===//
449 
450 static void addRegUnits(const SIRegisterInfo &TRI,
451                         BitVector &BV, unsigned Reg) {
452   for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI)
453     BV.set(*RUI);
454 }
455 
456 static void addRegsToSet(const SIRegisterInfo &TRI,
457                          iterator_range<MachineInstr::const_mop_iterator> Ops,
458                          BitVector &Set) {
459   for (const MachineOperand &Op : Ops) {
460     if (Op.isReg())
461       addRegUnits(TRI, Set, Op.getReg());
462   }
463 }
464 
465 void GCNHazardRecognizer::addClauseInst(const MachineInstr &MI) {
466   // XXX: Do we need to worry about implicit operands
467   addRegsToSet(TRI, MI.defs(), ClauseDefs);
468   addRegsToSet(TRI, MI.uses(), ClauseUses);
469 }
470 
471 int GCNHazardRecognizer::checkSoftClauseHazards(MachineInstr *MEM) {
472   // SMEM soft clause are only present on VI+, and only matter if xnack is
473   // enabled.
474   if (!ST.isXNACKEnabled())
475     return 0;
476 
477   bool IsSMRD = TII.isSMRD(*MEM);
478 
479   resetClause();
480 
481   // A soft-clause is any group of consecutive SMEM instructions.  The
482   // instructions in this group may return out of order and/or may be
483   // replayed (i.e. the same instruction issued more than once).
484   //
485   // In order to handle these situations correctly we need to make sure that
486   // when a clause has more than one instruction, no instruction in the clause
487   // writes to a register that is read by another instruction in the clause
488   // (including itself). If we encounter this situaion, we need to break the
489   // clause by inserting a non SMEM instruction.
490 
491   for (MachineInstr *MI : EmittedInstrs) {
492     // When we hit a non-SMEM instruction then we have passed the start of the
493     // clause and we can stop.
494     if (!MI)
495       break;
496 
497     if (IsSMRD != SIInstrInfo::isSMRD(*MI))
498       break;
499 
500     addClauseInst(*MI);
501   }
502 
503   if (ClauseDefs.none())
504     return 0;
505 
506   // We need to make sure not to put loads and stores in the same clause if they
507   // use the same address. For now, just start a new clause whenever we see a
508   // store.
509   if (MEM->mayStore())
510     return 1;
511 
512   addClauseInst(*MEM);
513 
514   // If the set of defs and uses intersect then we cannot add this instruction
515   // to the clause, so we have a hazard.
516   return ClauseDefs.anyCommon(ClauseUses) ? 1 : 0;
517 }
518 
519 int GCNHazardRecognizer::checkSMRDHazards(MachineInstr *SMRD) {
520   int WaitStatesNeeded = 0;
521 
522   WaitStatesNeeded = checkSoftClauseHazards(SMRD);
523 
524   // This SMRD hazard only affects SI.
525   if (!ST.hasSMRDReadVALUDefHazard())
526     return WaitStatesNeeded;
527 
528   // A read of an SGPR by SMRD instruction requires 4 wait states when the
529   // SGPR was written by a VALU instruction.
530   int SmrdSgprWaitStates = 4;
531   auto IsHazardDefFn = [this] (MachineInstr *MI) { return TII.isVALU(*MI); };
532   auto IsBufferHazardDefFn = [this] (MachineInstr *MI) { return TII.isSALU(*MI); };
533 
534   bool IsBufferSMRD = TII.isBufferSMRD(*SMRD);
535 
536   for (const MachineOperand &Use : SMRD->uses()) {
537     if (!Use.isReg())
538       continue;
539     int WaitStatesNeededForUse =
540         SmrdSgprWaitStates - getWaitStatesSinceDef(Use.getReg(), IsHazardDefFn,
541                                                    SmrdSgprWaitStates);
542     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
543 
544     // This fixes what appears to be undocumented hardware behavior in SI where
545     // s_mov writing a descriptor and s_buffer_load_dword reading the descriptor
546     // needs some number of nops in between. We don't know how many we need, but
547     // let's use 4. This wasn't discovered before probably because the only
548     // case when this happens is when we expand a 64-bit pointer into a full
549     // descriptor and use s_buffer_load_dword instead of s_load_dword, which was
550     // probably never encountered in the closed-source land.
551     if (IsBufferSMRD) {
552       int WaitStatesNeededForUse =
553         SmrdSgprWaitStates - getWaitStatesSinceDef(Use.getReg(),
554                                                    IsBufferHazardDefFn,
555                                                    SmrdSgprWaitStates);
556       WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
557     }
558   }
559 
560   return WaitStatesNeeded;
561 }
562 
563 int GCNHazardRecognizer::checkVMEMHazards(MachineInstr* VMEM) {
564   if (!ST.hasVMEMReadSGPRVALUDefHazard())
565     return 0;
566 
567   int WaitStatesNeeded = checkSoftClauseHazards(VMEM);
568 
569   // A read of an SGPR by a VMEM instruction requires 5 wait states when the
570   // SGPR was written by a VALU Instruction.
571   const int VmemSgprWaitStates = 5;
572   auto IsHazardDefFn = [this] (MachineInstr *MI) { return TII.isVALU(*MI); };
573   for (const MachineOperand &Use : VMEM->uses()) {
574     if (!Use.isReg() || TRI.isVGPR(MF.getRegInfo(), Use.getReg()))
575       continue;
576 
577     int WaitStatesNeededForUse =
578         VmemSgprWaitStates - getWaitStatesSinceDef(Use.getReg(), IsHazardDefFn,
579                                                    VmemSgprWaitStates);
580     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
581   }
582   return WaitStatesNeeded;
583 }
584 
585 int GCNHazardRecognizer::checkDPPHazards(MachineInstr *DPP) {
586   const SIRegisterInfo *TRI = ST.getRegisterInfo();
587   const SIInstrInfo *TII = ST.getInstrInfo();
588 
589   // Check for DPP VGPR read after VALU VGPR write and EXEC write.
590   int DppVgprWaitStates = 2;
591   int DppExecWaitStates = 5;
592   int WaitStatesNeeded = 0;
593   auto IsHazardDefFn = [TII] (MachineInstr *MI) { return TII->isVALU(*MI); };
594 
595   for (const MachineOperand &Use : DPP->uses()) {
596     if (!Use.isReg() || !TRI->isVGPR(MF.getRegInfo(), Use.getReg()))
597       continue;
598     int WaitStatesNeededForUse =
599         DppVgprWaitStates - getWaitStatesSinceDef(Use.getReg(),
600                               [](MachineInstr *) { return true; },
601                               DppVgprWaitStates);
602     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
603   }
604 
605   WaitStatesNeeded = std::max(
606       WaitStatesNeeded,
607       DppExecWaitStates - getWaitStatesSinceDef(AMDGPU::EXEC, IsHazardDefFn,
608                                                 DppExecWaitStates));
609 
610   return WaitStatesNeeded;
611 }
612 
613 int GCNHazardRecognizer::checkDivFMasHazards(MachineInstr *DivFMas) {
614   const SIInstrInfo *TII = ST.getInstrInfo();
615 
616   // v_div_fmas requires 4 wait states after a write to vcc from a VALU
617   // instruction.
618   const int DivFMasWaitStates = 4;
619   auto IsHazardDefFn = [TII] (MachineInstr *MI) { return TII->isVALU(*MI); };
620   int WaitStatesNeeded = getWaitStatesSinceDef(AMDGPU::VCC, IsHazardDefFn,
621                                                DivFMasWaitStates);
622 
623   return DivFMasWaitStates - WaitStatesNeeded;
624 }
625 
626 int GCNHazardRecognizer::checkGetRegHazards(MachineInstr *GetRegInstr) {
627   const SIInstrInfo *TII = ST.getInstrInfo();
628   unsigned GetRegHWReg = getHWReg(TII, *GetRegInstr);
629 
630   const int GetRegWaitStates = 2;
631   auto IsHazardFn = [TII, GetRegHWReg] (MachineInstr *MI) {
632     return GetRegHWReg == getHWReg(TII, *MI);
633   };
634   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, GetRegWaitStates);
635 
636   return GetRegWaitStates - WaitStatesNeeded;
637 }
638 
639 int GCNHazardRecognizer::checkSetRegHazards(MachineInstr *SetRegInstr) {
640   const SIInstrInfo *TII = ST.getInstrInfo();
641   unsigned HWReg = getHWReg(TII, *SetRegInstr);
642 
643   const int SetRegWaitStates = ST.getSetRegWaitStates();
644   auto IsHazardFn = [TII, HWReg] (MachineInstr *MI) {
645     return HWReg == getHWReg(TII, *MI);
646   };
647   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, SetRegWaitStates);
648   return SetRegWaitStates - WaitStatesNeeded;
649 }
650 
651 int GCNHazardRecognizer::createsVALUHazard(const MachineInstr &MI) {
652   if (!MI.mayStore())
653     return -1;
654 
655   const SIInstrInfo *TII = ST.getInstrInfo();
656   unsigned Opcode = MI.getOpcode();
657   const MCInstrDesc &Desc = MI.getDesc();
658 
659   int VDataIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
660   int VDataRCID = -1;
661   if (VDataIdx != -1)
662     VDataRCID = Desc.OpInfo[VDataIdx].RegClass;
663 
664   if (TII->isMUBUF(MI) || TII->isMTBUF(MI)) {
665     // There is no hazard if the instruction does not use vector regs
666     // (like wbinvl1)
667     if (VDataIdx == -1)
668       return -1;
669     // For MUBUF/MTBUF instructions this hazard only exists if the
670     // instruction is not using a register in the soffset field.
671     const MachineOperand *SOffset =
672         TII->getNamedOperand(MI, AMDGPU::OpName::soffset);
673     // If we have no soffset operand, then assume this field has been
674     // hardcoded to zero.
675     if (AMDGPU::getRegBitWidth(VDataRCID) > 64 &&
676         (!SOffset || !SOffset->isReg()))
677       return VDataIdx;
678   }
679 
680   // MIMG instructions create a hazard if they don't use a 256-bit T# and
681   // the store size is greater than 8 bytes and they have more than two bits
682   // of their dmask set.
683   // All our MIMG definitions use a 256-bit T#, so we can skip checking for them.
684   if (TII->isMIMG(MI)) {
685     int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
686     assert(SRsrcIdx != -1 &&
687            AMDGPU::getRegBitWidth(Desc.OpInfo[SRsrcIdx].RegClass) == 256);
688     (void)SRsrcIdx;
689   }
690 
691   if (TII->isFLAT(MI)) {
692     int DataIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
693     if (AMDGPU::getRegBitWidth(Desc.OpInfo[DataIdx].RegClass) > 64)
694       return DataIdx;
695   }
696 
697   return -1;
698 }
699 
700 int GCNHazardRecognizer::checkVALUHazardsHelper(const MachineOperand &Def,
701 						const MachineRegisterInfo &MRI) {
702   // Helper to check for the hazard where VMEM instructions that store more than
703   // 8 bytes can have there store data over written by the next instruction.
704   const SIRegisterInfo *TRI = ST.getRegisterInfo();
705 
706   const int VALUWaitStates = 1;
707   int WaitStatesNeeded = 0;
708 
709   if (!TRI->isVGPR(MRI, Def.getReg()))
710     return WaitStatesNeeded;
711   unsigned Reg = Def.getReg();
712   auto IsHazardFn = [this, Reg, TRI] (MachineInstr *MI) {
713     int DataIdx = createsVALUHazard(*MI);
714     return DataIdx >= 0 &&
715     TRI->regsOverlap(MI->getOperand(DataIdx).getReg(), Reg);
716   };
717   int WaitStatesNeededForDef =
718     VALUWaitStates - getWaitStatesSince(IsHazardFn, VALUWaitStates);
719   WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
720 
721   return WaitStatesNeeded;
722 }
723 
724 int GCNHazardRecognizer::checkVALUHazards(MachineInstr *VALU) {
725   // This checks for the hazard where VMEM instructions that store more than
726   // 8 bytes can have there store data over written by the next instruction.
727   if (!ST.has12DWordStoreHazard())
728     return 0;
729 
730   const MachineRegisterInfo &MRI = MF.getRegInfo();
731   int WaitStatesNeeded = 0;
732 
733   for (const MachineOperand &Def : VALU->defs()) {
734     WaitStatesNeeded = std::max(WaitStatesNeeded, checkVALUHazardsHelper(Def, MRI));
735   }
736 
737   return WaitStatesNeeded;
738 }
739 
740 int GCNHazardRecognizer::checkInlineAsmHazards(MachineInstr *IA) {
741   // This checks for hazards associated with inline asm statements.
742   // Since inline asms can contain just about anything, we use this
743   // to call/leverage other check*Hazard routines. Note that
744   // this function doesn't attempt to address all possible inline asm
745   // hazards (good luck), but is a collection of what has been
746   // problematic thus far.
747 
748   // see checkVALUHazards()
749   if (!ST.has12DWordStoreHazard())
750     return 0;
751 
752   const MachineRegisterInfo &MRI = MF.getRegInfo();
753   int WaitStatesNeeded = 0;
754 
755   for (unsigned I = InlineAsm::MIOp_FirstOperand, E = IA->getNumOperands();
756        I != E; ++I) {
757     const MachineOperand &Op = IA->getOperand(I);
758     if (Op.isReg() && Op.isDef()) {
759       WaitStatesNeeded = std::max(WaitStatesNeeded, checkVALUHazardsHelper(Op, MRI));
760     }
761   }
762 
763   return WaitStatesNeeded;
764 }
765 
766 int GCNHazardRecognizer::checkRWLaneHazards(MachineInstr *RWLane) {
767   const SIInstrInfo *TII = ST.getInstrInfo();
768   const SIRegisterInfo *TRI = ST.getRegisterInfo();
769   const MachineRegisterInfo &MRI = MF.getRegInfo();
770 
771   const MachineOperand *LaneSelectOp =
772       TII->getNamedOperand(*RWLane, AMDGPU::OpName::src1);
773 
774   if (!LaneSelectOp->isReg() || !TRI->isSGPRReg(MRI, LaneSelectOp->getReg()))
775     return 0;
776 
777   unsigned LaneSelectReg = LaneSelectOp->getReg();
778   auto IsHazardFn = [TII] (MachineInstr *MI) {
779     return TII->isVALU(*MI);
780   };
781 
782   const int RWLaneWaitStates = 4;
783   int WaitStatesSince = getWaitStatesSinceDef(LaneSelectReg, IsHazardFn,
784                                               RWLaneWaitStates);
785   return RWLaneWaitStates - WaitStatesSince;
786 }
787 
788 int GCNHazardRecognizer::checkRFEHazards(MachineInstr *RFE) {
789   if (!ST.hasRFEHazards())
790     return 0;
791 
792   const SIInstrInfo *TII = ST.getInstrInfo();
793 
794   const int RFEWaitStates = 1;
795 
796   auto IsHazardFn = [TII] (MachineInstr *MI) {
797     return getHWReg(TII, *MI) == AMDGPU::Hwreg::ID_TRAPSTS;
798   };
799   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, RFEWaitStates);
800   return RFEWaitStates - WaitStatesNeeded;
801 }
802 
803 int GCNHazardRecognizer::checkAnyInstHazards(MachineInstr *MI) {
804   if (MI->isDebugInstr())
805     return 0;
806 
807   const SIRegisterInfo *TRI = ST.getRegisterInfo();
808   if (!ST.hasSMovFedHazard())
809     return 0;
810 
811   // Check for any instruction reading an SGPR after a write from
812   // s_mov_fed_b32.
813   int MovFedWaitStates = 1;
814   int WaitStatesNeeded = 0;
815 
816   for (const MachineOperand &Use : MI->uses()) {
817     if (!Use.isReg() || TRI->isVGPR(MF.getRegInfo(), Use.getReg()))
818       continue;
819     auto IsHazardFn = [] (MachineInstr *MI) {
820       return MI->getOpcode() == AMDGPU::S_MOV_FED_B32;
821     };
822     int WaitStatesNeededForUse =
823         MovFedWaitStates - getWaitStatesSinceDef(Use.getReg(), IsHazardFn,
824                                                  MovFedWaitStates);
825     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
826   }
827 
828   return WaitStatesNeeded;
829 }
830 
831 int GCNHazardRecognizer::checkReadM0Hazards(MachineInstr *MI) {
832   const SIInstrInfo *TII = ST.getInstrInfo();
833   const int SMovRelWaitStates = 1;
834   auto IsHazardFn = [TII] (MachineInstr *MI) {
835     return TII->isSALU(*MI);
836   };
837   return SMovRelWaitStates - getWaitStatesSinceDef(AMDGPU::M0, IsHazardFn,
838                                                    SMovRelWaitStates);
839 }
840 
841 void GCNHazardRecognizer::fixHazards(MachineInstr *MI) {
842   fixVMEMtoScalarWriteHazards(MI);
843   fixVcmpxPermlaneHazards(MI);
844   fixSMEMtoVectorWriteHazards(MI);
845   fixVcmpxExecWARHazard(MI);
846   fixLdsBranchVmemWARHazard(MI);
847 }
848 
849 bool GCNHazardRecognizer::fixVcmpxPermlaneHazards(MachineInstr *MI) {
850   if (!ST.hasVcmpxPermlaneHazard() || !isPermlane(*MI))
851     return false;
852 
853   const SIInstrInfo *TII = ST.getInstrInfo();
854   auto IsHazardFn = [TII] (MachineInstr *MI) {
855     return TII->isVOPC(*MI);
856   };
857 
858   auto IsExpiredFn = [] (MachineInstr *MI, int) {
859     if (!MI)
860       return false;
861     unsigned Opc = MI->getOpcode();
862     return SIInstrInfo::isVALU(*MI) &&
863            Opc != AMDGPU::V_NOP_e32 &&
864            Opc != AMDGPU::V_NOP_e64 &&
865            Opc != AMDGPU::V_NOP_sdwa;
866   };
867 
868   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
869       std::numeric_limits<int>::max())
870     return false;
871 
872   // V_NOP will be discarded by SQ.
873   // Use V_MOB_B32 v?, v?. Register must be alive so use src0 of V_PERMLANE*
874   // which is always a VGPR and available.
875   auto *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
876   unsigned Reg = Src0->getReg();
877   bool IsUndef = Src0->isUndef();
878   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
879           TII->get(AMDGPU::V_MOV_B32_e32))
880     .addReg(Reg, RegState::Define | (IsUndef ? RegState::Dead : 0))
881     .addReg(Reg, IsUndef ? RegState::Undef : RegState::Kill);
882 
883   return true;
884 }
885 
886 bool GCNHazardRecognizer::fixVMEMtoScalarWriteHazards(MachineInstr *MI) {
887   if (!ST.hasVMEMtoScalarWriteHazard())
888     return false;
889 
890   if (!SIInstrInfo::isSALU(*MI) && !SIInstrInfo::isSMRD(*MI))
891     return false;
892 
893   if (MI->getNumDefs() == 0)
894     return false;
895 
896   const SIRegisterInfo *TRI = ST.getRegisterInfo();
897 
898   auto IsHazardFn = [TRI, MI] (MachineInstr *I) {
899     if (!SIInstrInfo::isVMEM(*I) && !SIInstrInfo::isDS(*I) &&
900         !SIInstrInfo::isFLAT(*I))
901       return false;
902 
903     for (const MachineOperand &Def : MI->defs()) {
904       MachineOperand *Op = I->findRegisterUseOperand(Def.getReg(), false, TRI);
905       if (!Op || (Op->isImplicit() && Op->getReg() == AMDGPU::EXEC))
906         continue;
907       return true;
908     }
909     return false;
910   };
911 
912   auto IsExpiredFn = [] (MachineInstr *MI, int) {
913     return MI && (SIInstrInfo::isVALU(*MI) ||
914                   (MI->getOpcode() == AMDGPU::S_WAITCNT &&
915                    !MI->getOperand(0).getImm()));
916   };
917 
918   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
919       std::numeric_limits<int>::max())
920     return false;
921 
922   const SIInstrInfo *TII = ST.getInstrInfo();
923   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(AMDGPU::V_NOP_e32));
924   return true;
925 }
926 
927 bool GCNHazardRecognizer::fixSMEMtoVectorWriteHazards(MachineInstr *MI) {
928   if (!ST.hasSMEMtoVectorWriteHazard())
929     return false;
930 
931   if (!SIInstrInfo::isVALU(*MI))
932     return false;
933 
934   unsigned SDSTName;
935   switch (MI->getOpcode()) {
936   case AMDGPU::V_READLANE_B32:
937   case AMDGPU::V_READFIRSTLANE_B32:
938     SDSTName = AMDGPU::OpName::vdst;
939     break;
940   default:
941     SDSTName = AMDGPU::OpName::sdst;
942     break;
943   }
944 
945   const SIInstrInfo *TII = ST.getInstrInfo();
946   const SIRegisterInfo *TRI = ST.getRegisterInfo();
947   const AMDGPU::IsaVersion IV = AMDGPU::getIsaVersion(ST.getCPU());
948   const MachineOperand *SDST = TII->getNamedOperand(*MI, SDSTName);
949   if (!SDST) {
950     for (const auto &MO : MI->implicit_operands()) {
951       if (MO.isDef() && TRI->isSGPRClass(TRI->getPhysRegClass(MO.getReg()))) {
952         SDST = &MO;
953         break;
954       }
955     }
956   }
957 
958   if (!SDST)
959     return false;
960 
961   const unsigned SDSTReg = SDST->getReg();
962   auto IsHazardFn = [SDSTReg, TRI] (MachineInstr *I) {
963     return SIInstrInfo::isSMRD(*I) && I->readsRegister(SDSTReg, TRI);
964   };
965 
966   auto IsExpiredFn = [TII, IV] (MachineInstr *MI, int) {
967     if (MI) {
968       if (TII->isSALU(*MI)) {
969         switch (MI->getOpcode()) {
970         case AMDGPU::S_SETVSKIP:
971         case AMDGPU::S_VERSION:
972         case AMDGPU::S_WAITCNT_VSCNT:
973         case AMDGPU::S_WAITCNT_VMCNT:
974         case AMDGPU::S_WAITCNT_EXPCNT:
975           // These instructions cannot not mitigate the hazard.
976           return false;
977         case AMDGPU::S_WAITCNT_LGKMCNT:
978           // Reducing lgkmcnt count to 0 always mitigates the hazard.
979           return (MI->getOperand(1).getImm() == 0) &&
980                  (MI->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
981         case AMDGPU::S_WAITCNT: {
982           const int64_t Imm = MI->getOperand(0).getImm();
983           AMDGPU::Waitcnt Decoded = AMDGPU::decodeWaitcnt(IV, Imm);
984           return (Decoded.LgkmCnt == 0);
985         }
986         default:
987           // SOPP instructions cannot mitigate the hazard.
988           if (TII->isSOPP(*MI))
989             return false;
990           // At this point the SALU can be assumed to mitigate the hazard
991           // because either:
992           // (a) it is independent of the at risk SMEM (breaking chain),
993           // or
994           // (b) it is dependent on the SMEM, in which case an appropriate
995           //     s_waitcnt lgkmcnt _must_ exist between it and the at risk
996           //     SMEM instruction.
997           return true;
998         }
999       }
1000     }
1001     return false;
1002   };
1003 
1004   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1005       std::numeric_limits<int>::max())
1006     return false;
1007 
1008   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1009           TII->get(AMDGPU::S_MOV_B32), AMDGPU::SGPR_NULL)
1010       .addImm(0);
1011   return true;
1012 }
1013 
1014 bool GCNHazardRecognizer::fixVcmpxExecWARHazard(MachineInstr *MI) {
1015   if (!ST.hasVcmpxExecWARHazard() || !SIInstrInfo::isVALU(*MI))
1016     return false;
1017 
1018   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1019   if (!MI->modifiesRegister(AMDGPU::EXEC, TRI))
1020     return false;
1021 
1022   auto IsHazardFn = [TRI] (MachineInstr *I) {
1023     if (SIInstrInfo::isVALU(*I))
1024       return false;
1025     return I->readsRegister(AMDGPU::EXEC, TRI);
1026   };
1027 
1028   const SIInstrInfo *TII = ST.getInstrInfo();
1029   auto IsExpiredFn = [TII, TRI] (MachineInstr *MI, int) {
1030     if (!MI)
1031       return false;
1032     if (SIInstrInfo::isVALU(*MI)) {
1033       if (TII->getNamedOperand(*MI, AMDGPU::OpName::sdst))
1034         return true;
1035       for (auto MO : MI->implicit_operands())
1036         if (MO.isDef() && TRI->isSGPRClass(TRI->getPhysRegClass(MO.getReg())))
1037           return true;
1038     }
1039     if (MI->getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1040         (MI->getOperand(0).getImm() & 0xfffe) == 0xfffe)
1041       return true;
1042     return false;
1043   };
1044 
1045   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1046       std::numeric_limits<int>::max())
1047     return false;
1048 
1049   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1050           TII->get(AMDGPU::S_WAITCNT_DEPCTR))
1051     .addImm(0xfffe);
1052   return true;
1053 }
1054 
1055 bool GCNHazardRecognizer::fixLdsBranchVmemWARHazard(MachineInstr *MI) {
1056   if (!ST.hasLdsBranchVmemWARHazard())
1057     return false;
1058 
1059   auto IsHazardInst = [] (const MachineInstr *MI) {
1060     if (SIInstrInfo::isDS(*MI))
1061       return 1;
1062     if (SIInstrInfo::isVMEM(*MI) || SIInstrInfo::isSegmentSpecificFLAT(*MI))
1063       return 2;
1064     return 0;
1065   };
1066 
1067   auto InstType = IsHazardInst(MI);
1068   if (!InstType)
1069     return false;
1070 
1071   auto IsExpiredFn = [&IsHazardInst] (MachineInstr *I, int) {
1072     return I && (IsHazardInst(I) ||
1073                  (I->getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1074                   I->getOperand(0).getReg() == AMDGPU::SGPR_NULL &&
1075                   !I->getOperand(1).getImm()));
1076   };
1077 
1078   auto IsHazardFn = [InstType, &IsHazardInst] (MachineInstr *I) {
1079     if (!I->isBranch())
1080       return false;
1081 
1082     auto IsHazardFn = [InstType, IsHazardInst] (MachineInstr *I) {
1083       auto InstType2 = IsHazardInst(I);
1084       return InstType2 && InstType != InstType2;
1085     };
1086 
1087     auto IsExpiredFn = [InstType, &IsHazardInst] (MachineInstr *I, int) {
1088       if (!I)
1089         return false;
1090 
1091       auto InstType2 = IsHazardInst(I);
1092       if (InstType == InstType2)
1093         return true;
1094 
1095       return I->getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1096              I->getOperand(0).getReg() == AMDGPU::SGPR_NULL &&
1097              !I->getOperand(1).getImm();
1098     };
1099 
1100     return ::getWaitStatesSince(IsHazardFn, I, IsExpiredFn) !=
1101            std::numeric_limits<int>::max();
1102   };
1103 
1104   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1105       std::numeric_limits<int>::max())
1106     return false;
1107 
1108   const SIInstrInfo *TII = ST.getInstrInfo();
1109   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1110           TII->get(AMDGPU::S_WAITCNT_VSCNT))
1111     .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1112     .addImm(0);
1113 
1114   return true;
1115 }
1116 
1117 int GCNHazardRecognizer::checkNSAtoVMEMHazard(MachineInstr *MI) {
1118   int NSAtoVMEMWaitStates = 1;
1119 
1120   if (!ST.hasNSAtoVMEMBug())
1121     return 0;
1122 
1123   if (!SIInstrInfo::isMUBUF(*MI) && !SIInstrInfo::isMTBUF(*MI))
1124     return 0;
1125 
1126   const SIInstrInfo *TII = ST.getInstrInfo();
1127   const auto *Offset = TII->getNamedOperand(*MI, AMDGPU::OpName::offset);
1128   if (!Offset || (Offset->getImm() & 6) == 0)
1129     return 0;
1130 
1131   auto IsHazardFn = [TII] (MachineInstr *I) {
1132     if (!SIInstrInfo::isMIMG(*I))
1133       return false;
1134     const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(I->getOpcode());
1135     return Info->MIMGEncoding == AMDGPU::MIMGEncGfx10NSA &&
1136            TII->getInstSizeInBytes(*I) >= 16;
1137   };
1138 
1139   return NSAtoVMEMWaitStates - getWaitStatesSince(IsHazardFn, 1);
1140 }
1141