xref: /llvm-project/llvm/lib/Target/AMDGPU/GCNHazardRecognizer.cpp (revision 5f581c9f08e6cbb22002371caa2d1f23337a9054)
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.getGeneration() != AMDGPUSubtarget::SOUTHERN_ISLANDS)
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.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
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 =
644       ST.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS ? 1 : 2;
645   auto IsHazardFn = [TII, HWReg] (MachineInstr *MI) {
646     return HWReg == getHWReg(TII, *MI);
647   };
648   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, SetRegWaitStates);
649   return SetRegWaitStates - WaitStatesNeeded;
650 }
651 
652 int GCNHazardRecognizer::createsVALUHazard(const MachineInstr &MI) {
653   if (!MI.mayStore())
654     return -1;
655 
656   const SIInstrInfo *TII = ST.getInstrInfo();
657   unsigned Opcode = MI.getOpcode();
658   const MCInstrDesc &Desc = MI.getDesc();
659 
660   int VDataIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
661   int VDataRCID = -1;
662   if (VDataIdx != -1)
663     VDataRCID = Desc.OpInfo[VDataIdx].RegClass;
664 
665   if (TII->isMUBUF(MI) || TII->isMTBUF(MI)) {
666     // There is no hazard if the instruction does not use vector regs
667     // (like wbinvl1)
668     if (VDataIdx == -1)
669       return -1;
670     // For MUBUF/MTBUF instructions this hazard only exists if the
671     // instruction is not using a register in the soffset field.
672     const MachineOperand *SOffset =
673         TII->getNamedOperand(MI, AMDGPU::OpName::soffset);
674     // If we have no soffset operand, then assume this field has been
675     // hardcoded to zero.
676     if (AMDGPU::getRegBitWidth(VDataRCID) > 64 &&
677         (!SOffset || !SOffset->isReg()))
678       return VDataIdx;
679   }
680 
681   // MIMG instructions create a hazard if they don't use a 256-bit T# and
682   // the store size is greater than 8 bytes and they have more than two bits
683   // of their dmask set.
684   // All our MIMG definitions use a 256-bit T#, so we can skip checking for them.
685   if (TII->isMIMG(MI)) {
686     int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
687     assert(SRsrcIdx != -1 &&
688            AMDGPU::getRegBitWidth(Desc.OpInfo[SRsrcIdx].RegClass) == 256);
689     (void)SRsrcIdx;
690   }
691 
692   if (TII->isFLAT(MI)) {
693     int DataIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdata);
694     if (AMDGPU::getRegBitWidth(Desc.OpInfo[DataIdx].RegClass) > 64)
695       return DataIdx;
696   }
697 
698   return -1;
699 }
700 
701 int GCNHazardRecognizer::checkVALUHazardsHelper(const MachineOperand &Def,
702 						const MachineRegisterInfo &MRI) {
703   // Helper to check for the hazard where VMEM instructions that store more than
704   // 8 bytes can have there store data over written by the next instruction.
705   const SIRegisterInfo *TRI = ST.getRegisterInfo();
706 
707   const int VALUWaitStates = 1;
708   int WaitStatesNeeded = 0;
709 
710   if (!TRI->isVGPR(MRI, Def.getReg()))
711     return WaitStatesNeeded;
712   unsigned Reg = Def.getReg();
713   auto IsHazardFn = [this, Reg, TRI] (MachineInstr *MI) {
714     int DataIdx = createsVALUHazard(*MI);
715     return DataIdx >= 0 &&
716     TRI->regsOverlap(MI->getOperand(DataIdx).getReg(), Reg);
717   };
718   int WaitStatesNeededForDef =
719     VALUWaitStates - getWaitStatesSince(IsHazardFn, VALUWaitStates);
720   WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForDef);
721 
722   return WaitStatesNeeded;
723 }
724 
725 int GCNHazardRecognizer::checkVALUHazards(MachineInstr *VALU) {
726   // This checks for the hazard where VMEM instructions that store more than
727   // 8 bytes can have there store data over written by the next instruction.
728   if (!ST.has12DWordStoreHazard())
729     return 0;
730 
731   const MachineRegisterInfo &MRI = MF.getRegInfo();
732   int WaitStatesNeeded = 0;
733 
734   for (const MachineOperand &Def : VALU->defs()) {
735     WaitStatesNeeded = std::max(WaitStatesNeeded, checkVALUHazardsHelper(Def, MRI));
736   }
737 
738   return WaitStatesNeeded;
739 }
740 
741 int GCNHazardRecognizer::checkInlineAsmHazards(MachineInstr *IA) {
742   // This checks for hazards associated with inline asm statements.
743   // Since inline asms can contain just about anything, we use this
744   // to call/leverage other check*Hazard routines. Note that
745   // this function doesn't attempt to address all possible inline asm
746   // hazards (good luck), but is a collection of what has been
747   // problematic thus far.
748 
749   // see checkVALUHazards()
750   if (!ST.has12DWordStoreHazard())
751     return 0;
752 
753   const MachineRegisterInfo &MRI = MF.getRegInfo();
754   int WaitStatesNeeded = 0;
755 
756   for (unsigned I = InlineAsm::MIOp_FirstOperand, E = IA->getNumOperands();
757        I != E; ++I) {
758     const MachineOperand &Op = IA->getOperand(I);
759     if (Op.isReg() && Op.isDef()) {
760       WaitStatesNeeded = std::max(WaitStatesNeeded, checkVALUHazardsHelper(Op, MRI));
761     }
762   }
763 
764   return WaitStatesNeeded;
765 }
766 
767 int GCNHazardRecognizer::checkRWLaneHazards(MachineInstr *RWLane) {
768   const SIInstrInfo *TII = ST.getInstrInfo();
769   const SIRegisterInfo *TRI = ST.getRegisterInfo();
770   const MachineRegisterInfo &MRI = MF.getRegInfo();
771 
772   const MachineOperand *LaneSelectOp =
773       TII->getNamedOperand(*RWLane, AMDGPU::OpName::src1);
774 
775   if (!LaneSelectOp->isReg() || !TRI->isSGPRReg(MRI, LaneSelectOp->getReg()))
776     return 0;
777 
778   unsigned LaneSelectReg = LaneSelectOp->getReg();
779   auto IsHazardFn = [TII] (MachineInstr *MI) {
780     return TII->isVALU(*MI);
781   };
782 
783   const int RWLaneWaitStates = 4;
784   int WaitStatesSince = getWaitStatesSinceDef(LaneSelectReg, IsHazardFn,
785                                               RWLaneWaitStates);
786   return RWLaneWaitStates - WaitStatesSince;
787 }
788 
789 int GCNHazardRecognizer::checkRFEHazards(MachineInstr *RFE) {
790   if (ST.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
791     return 0;
792 
793   const SIInstrInfo *TII = ST.getInstrInfo();
794 
795   const int RFEWaitStates = 1;
796 
797   auto IsHazardFn = [TII] (MachineInstr *MI) {
798     return getHWReg(TII, *MI) == AMDGPU::Hwreg::ID_TRAPSTS;
799   };
800   int WaitStatesNeeded = getWaitStatesSinceSetReg(IsHazardFn, RFEWaitStates);
801   return RFEWaitStates - WaitStatesNeeded;
802 }
803 
804 int GCNHazardRecognizer::checkAnyInstHazards(MachineInstr *MI) {
805   if (MI->isDebugInstr())
806     return 0;
807 
808   const SIRegisterInfo *TRI = ST.getRegisterInfo();
809   if (!ST.hasSMovFedHazard())
810     return 0;
811 
812   // Check for any instruction reading an SGPR after a write from
813   // s_mov_fed_b32.
814   int MovFedWaitStates = 1;
815   int WaitStatesNeeded = 0;
816 
817   for (const MachineOperand &Use : MI->uses()) {
818     if (!Use.isReg() || TRI->isVGPR(MF.getRegInfo(), Use.getReg()))
819       continue;
820     auto IsHazardFn = [] (MachineInstr *MI) {
821       return MI->getOpcode() == AMDGPU::S_MOV_FED_B32;
822     };
823     int WaitStatesNeededForUse =
824         MovFedWaitStates - getWaitStatesSinceDef(Use.getReg(), IsHazardFn,
825                                                  MovFedWaitStates);
826     WaitStatesNeeded = std::max(WaitStatesNeeded, WaitStatesNeededForUse);
827   }
828 
829   return WaitStatesNeeded;
830 }
831 
832 int GCNHazardRecognizer::checkReadM0Hazards(MachineInstr *MI) {
833   const SIInstrInfo *TII = ST.getInstrInfo();
834   const int SMovRelWaitStates = 1;
835   auto IsHazardFn = [TII] (MachineInstr *MI) {
836     return TII->isSALU(*MI);
837   };
838   return SMovRelWaitStates - getWaitStatesSinceDef(AMDGPU::M0, IsHazardFn,
839                                                    SMovRelWaitStates);
840 }
841 
842 void GCNHazardRecognizer::fixHazards(MachineInstr *MI) {
843   fixVMEMtoScalarWriteHazards(MI);
844   fixVcmpxPermlaneHazards(MI);
845   fixSMEMtoVectorWriteHazards(MI);
846   fixVcmpxExecWARHazard(MI);
847   fixLdsBranchVmemWARHazard(MI);
848 }
849 
850 bool GCNHazardRecognizer::fixVcmpxPermlaneHazards(MachineInstr *MI) {
851   if (!ST.hasVcmpxPermlaneHazard() || !isPermlane(*MI))
852     return false;
853 
854   const SIInstrInfo *TII = ST.getInstrInfo();
855   auto IsHazardFn = [TII] (MachineInstr *MI) {
856     return TII->isVOPC(*MI);
857   };
858 
859   auto IsExpiredFn = [] (MachineInstr *MI, int) {
860     if (!MI)
861       return false;
862     unsigned Opc = MI->getOpcode();
863     return SIInstrInfo::isVALU(*MI) &&
864            Opc != AMDGPU::V_NOP_e32 &&
865            Opc != AMDGPU::V_NOP_e64 &&
866            Opc != AMDGPU::V_NOP_sdwa;
867   };
868 
869   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
870       std::numeric_limits<int>::max())
871     return false;
872 
873   // V_NOP will be discarded by SQ.
874   // Use V_MOB_B32 v?, v?. Register must be alive so use src0 of V_PERMLANE*
875   // which is always a VGPR and available.
876   auto *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0);
877   unsigned Reg = Src0->getReg();
878   bool IsUndef = Src0->isUndef();
879   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
880           TII->get(AMDGPU::V_MOV_B32_e32))
881     .addReg(Reg, RegState::Define | (IsUndef ? RegState::Dead : 0))
882     .addReg(Reg, IsUndef ? RegState::Undef : RegState::Kill);
883 
884   return true;
885 }
886 
887 bool GCNHazardRecognizer::fixVMEMtoScalarWriteHazards(MachineInstr *MI) {
888   if (!ST.hasVMEMtoScalarWriteHazard())
889     return false;
890 
891   if (!SIInstrInfo::isSALU(*MI) && !SIInstrInfo::isSMRD(*MI))
892     return false;
893 
894   if (MI->getNumDefs() == 0)
895     return false;
896 
897   const SIRegisterInfo *TRI = ST.getRegisterInfo();
898 
899   auto IsHazardFn = [TRI, MI] (MachineInstr *I) {
900     if (!SIInstrInfo::isVMEM(*I) && !SIInstrInfo::isDS(*I) &&
901         !SIInstrInfo::isFLAT(*I))
902       return false;
903 
904     for (const MachineOperand &Def : MI->defs()) {
905       MachineOperand *Op = I->findRegisterUseOperand(Def.getReg(), false, TRI);
906       if (!Op || (Op->isImplicit() && Op->getReg() == AMDGPU::EXEC))
907         continue;
908       return true;
909     }
910     return false;
911   };
912 
913   auto IsExpiredFn = [] (MachineInstr *MI, int) {
914     return MI && (SIInstrInfo::isVALU(*MI) ||
915                   (MI->getOpcode() == AMDGPU::S_WAITCNT &&
916                    !MI->getOperand(0).getImm()));
917   };
918 
919   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
920       std::numeric_limits<int>::max())
921     return false;
922 
923   const SIInstrInfo *TII = ST.getInstrInfo();
924   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(AMDGPU::V_NOP_e32));
925   return true;
926 }
927 
928 bool GCNHazardRecognizer::fixSMEMtoVectorWriteHazards(MachineInstr *MI) {
929   if (!ST.hasSMEMtoVectorWriteHazard())
930     return false;
931 
932   if (!SIInstrInfo::isVALU(*MI))
933     return false;
934 
935   unsigned SDSTName;
936   switch (MI->getOpcode()) {
937   case AMDGPU::V_READLANE_B32:
938   case AMDGPU::V_READFIRSTLANE_B32:
939     SDSTName = AMDGPU::OpName::vdst;
940     break;
941   default:
942     SDSTName = AMDGPU::OpName::sdst;
943     break;
944   }
945 
946   const SIInstrInfo *TII = ST.getInstrInfo();
947   const SIRegisterInfo *TRI = ST.getRegisterInfo();
948   const AMDGPU::IsaVersion IV = AMDGPU::getIsaVersion(ST.getCPU());
949   const MachineOperand *SDST = TII->getNamedOperand(*MI, SDSTName);
950   if (!SDST) {
951     for (const auto &MO : MI->implicit_operands()) {
952       if (MO.isDef() && TRI->isSGPRClass(TRI->getPhysRegClass(MO.getReg()))) {
953         SDST = &MO;
954         break;
955       }
956     }
957   }
958 
959   if (!SDST)
960     return false;
961 
962   const unsigned SDSTReg = SDST->getReg();
963   auto IsHazardFn = [SDSTReg, TRI] (MachineInstr *I) {
964     return SIInstrInfo::isSMRD(*I) && I->readsRegister(SDSTReg, TRI);
965   };
966 
967   auto IsExpiredFn = [TII, IV] (MachineInstr *MI, int) {
968     if (MI) {
969       if (TII->isSALU(*MI)) {
970         switch (MI->getOpcode()) {
971         case AMDGPU::S_SETVSKIP:
972         case AMDGPU::S_VERSION:
973         case AMDGPU::S_WAITCNT_VSCNT:
974         case AMDGPU::S_WAITCNT_VMCNT:
975         case AMDGPU::S_WAITCNT_EXPCNT:
976           // These instructions cannot not mitigate the hazard.
977           return false;
978         case AMDGPU::S_WAITCNT_LGKMCNT:
979           // Reducing lgkmcnt count to 0 always mitigates the hazard.
980           return (MI->getOperand(1).getImm() == 0) &&
981                  (MI->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
982         case AMDGPU::S_WAITCNT: {
983           const int64_t Imm = MI->getOperand(0).getImm();
984           AMDGPU::Waitcnt Decoded = AMDGPU::decodeWaitcnt(IV, Imm);
985           return (Decoded.LgkmCnt == 0);
986         }
987         default:
988           // SOPP instructions cannot mitigate the hazard.
989           if (TII->isSOPP(*MI))
990             return false;
991           // At this point the SALU can be assumed to mitigate the hazard
992           // because either:
993           // (a) it is independent of the at risk SMEM (breaking chain),
994           // or
995           // (b) it is dependent on the SMEM, in which case an appropriate
996           //     s_waitcnt lgkmcnt _must_ exist between it and the at risk
997           //     SMEM instruction.
998           return true;
999         }
1000       }
1001     }
1002     return false;
1003   };
1004 
1005   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1006       std::numeric_limits<int>::max())
1007     return false;
1008 
1009   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1010           TII->get(AMDGPU::S_MOV_B32), AMDGPU::SGPR_NULL)
1011       .addImm(0);
1012   return true;
1013 }
1014 
1015 bool GCNHazardRecognizer::fixVcmpxExecWARHazard(MachineInstr *MI) {
1016   if (!ST.hasVcmpxExecWARHazard() || !SIInstrInfo::isVALU(*MI))
1017     return false;
1018 
1019   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1020   if (!MI->modifiesRegister(AMDGPU::EXEC, TRI))
1021     return false;
1022 
1023   auto IsHazardFn = [TRI] (MachineInstr *I) {
1024     if (SIInstrInfo::isVALU(*I))
1025       return false;
1026     return I->readsRegister(AMDGPU::EXEC, TRI);
1027   };
1028 
1029   const SIInstrInfo *TII = ST.getInstrInfo();
1030   auto IsExpiredFn = [TII, TRI] (MachineInstr *MI, int) {
1031     if (!MI)
1032       return false;
1033     if (SIInstrInfo::isVALU(*MI)) {
1034       if (TII->getNamedOperand(*MI, AMDGPU::OpName::sdst))
1035         return true;
1036       for (auto MO : MI->implicit_operands())
1037         if (MO.isDef() && TRI->isSGPRClass(TRI->getPhysRegClass(MO.getReg())))
1038           return true;
1039     }
1040     if (MI->getOpcode() == AMDGPU::S_WAITCNT_DEPCTR &&
1041         (MI->getOperand(0).getImm() & 0xfffe) == 0xfffe)
1042       return true;
1043     return false;
1044   };
1045 
1046   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1047       std::numeric_limits<int>::max())
1048     return false;
1049 
1050   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1051           TII->get(AMDGPU::S_WAITCNT_DEPCTR))
1052     .addImm(0xfffe);
1053   return true;
1054 }
1055 
1056 bool GCNHazardRecognizer::fixLdsBranchVmemWARHazard(MachineInstr *MI) {
1057   if (!ST.hasLdsBranchVmemWARHazard())
1058     return false;
1059 
1060   auto IsHazardInst = [] (const MachineInstr *MI) {
1061     if (SIInstrInfo::isDS(*MI))
1062       return 1;
1063     if (SIInstrInfo::isVMEM(*MI) || SIInstrInfo::isSegmentSpecificFLAT(*MI))
1064       return 2;
1065     return 0;
1066   };
1067 
1068   auto InstType = IsHazardInst(MI);
1069   if (!InstType)
1070     return false;
1071 
1072   auto IsExpiredFn = [&IsHazardInst] (MachineInstr *I, int) {
1073     return I && (IsHazardInst(I) ||
1074                  (I->getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1075                   I->getOperand(0).getReg() == AMDGPU::SGPR_NULL &&
1076                   !I->getOperand(1).getImm()));
1077   };
1078 
1079   auto IsHazardFn = [InstType, &IsHazardInst] (MachineInstr *I) {
1080     if (!I->isBranch())
1081       return false;
1082 
1083     auto IsHazardFn = [InstType, IsHazardInst] (MachineInstr *I) {
1084       auto InstType2 = IsHazardInst(I);
1085       return InstType2 && InstType != InstType2;
1086     };
1087 
1088     auto IsExpiredFn = [InstType, &IsHazardInst] (MachineInstr *I, int) {
1089       if (!I)
1090         return false;
1091 
1092       auto InstType2 = IsHazardInst(I);
1093       if (InstType == InstType2)
1094         return true;
1095 
1096       return I->getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1097              I->getOperand(0).getReg() == AMDGPU::SGPR_NULL &&
1098              !I->getOperand(1).getImm();
1099     };
1100 
1101     return ::getWaitStatesSince(IsHazardFn, I, IsExpiredFn) !=
1102            std::numeric_limits<int>::max();
1103   };
1104 
1105   if (::getWaitStatesSince(IsHazardFn, MI, IsExpiredFn) ==
1106       std::numeric_limits<int>::max())
1107     return false;
1108 
1109   const SIInstrInfo *TII = ST.getInstrInfo();
1110   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1111           TII->get(AMDGPU::S_WAITCNT_VSCNT))
1112     .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1113     .addImm(0);
1114 
1115   return true;
1116 }
1117 
1118 int GCNHazardRecognizer::checkNSAtoVMEMHazard(MachineInstr *MI) {
1119   int NSAtoVMEMWaitStates = 1;
1120 
1121   if (!ST.hasNSAtoVMEMBug())
1122     return 0;
1123 
1124   if (!SIInstrInfo::isMUBUF(*MI) && !SIInstrInfo::isMTBUF(*MI))
1125     return 0;
1126 
1127   const SIInstrInfo *TII = ST.getInstrInfo();
1128   const auto *Offset = TII->getNamedOperand(*MI, AMDGPU::OpName::offset);
1129   if (!Offset || (Offset->getImm() & 6) == 0)
1130     return 0;
1131 
1132   auto IsHazardFn = [TII] (MachineInstr *I) {
1133     if (!SIInstrInfo::isMIMG(*I))
1134       return false;
1135     const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(I->getOpcode());
1136     return Info->MIMGEncoding == AMDGPU::MIMGEncGfx10NSA &&
1137            TII->getInstSizeInBytes(*I) >= 16;
1138   };
1139 
1140   return NSAtoVMEMWaitStates - getWaitStatesSince(IsHazardFn, 1);
1141 }
1142