1 //===- SIInsertWaitcnts.cpp - Insert Wait Instructions --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Insert wait instructions for memory reads and writes.
11 ///
12 /// Memory reads and writes are issued asynchronously, so we need to insert
13 /// S_WAITCNT instructions when we want to access any of their results or
14 /// overwrite any register that's used asynchronously.
15 ///
16 /// TODO: This pass currently keeps one timeline per hardware counter. A more
17 /// finely-grained approach that keeps one timeline per event type could
18 /// sometimes get away with generating weaker s_waitcnt instructions. For
19 /// example, when both SMEM and LDS are in flight and we need to wait for
20 /// the i-th-last LDS instruction, then an lgkmcnt(i) is actually sufficient,
21 /// but the pass will currently generate a conservative lgkmcnt(0) because
22 /// multiple event types are in flight.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "AMDGPU.h"
27 #include "GCNSubtarget.h"
28 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
29 #include "SIMachineFunctionInfo.h"
30 #include "Utils/AMDGPUBaseInfo.h"
31 #include "llvm/ADT/MapVector.h"
32 #include "llvm/ADT/PostOrderIterator.h"
33 #include "llvm/ADT/Sequence.h"
34 #include "llvm/CodeGen/MachinePostDominators.h"
35 #include "llvm/InitializePasses.h"
36 #include "llvm/Support/DebugCounter.h"
37 #include "llvm/Support/TargetParser.h"
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "si-insert-waitcnts"
41 
42 DEBUG_COUNTER(ForceExpCounter, DEBUG_TYPE"-forceexp",
43               "Force emit s_waitcnt expcnt(0) instrs");
44 DEBUG_COUNTER(ForceLgkmCounter, DEBUG_TYPE"-forcelgkm",
45               "Force emit s_waitcnt lgkmcnt(0) instrs");
46 DEBUG_COUNTER(ForceVMCounter, DEBUG_TYPE"-forcevm",
47               "Force emit s_waitcnt vmcnt(0) instrs");
48 
49 static cl::opt<bool> ForceEmitZeroFlag(
50   "amdgpu-waitcnt-forcezero",
51   cl::desc("Force all waitcnt instrs to be emitted as s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
52   cl::init(false), cl::Hidden);
53 
54 namespace {
55 // Class of object that encapsulates latest instruction counter score
56 // associated with the operand.  Used for determining whether
57 // s_waitcnt instruction needs to be emitted.
58 
59 #define CNT_MASK(t) (1u << (t))
60 
61 enum InstCounterType { VM_CNT = 0, LGKM_CNT, EXP_CNT, VS_CNT, NUM_INST_CNTS };
62 } // namespace
63 
64 namespace llvm {
65 template <> struct enum_iteration_traits<InstCounterType> {
66   static constexpr bool is_iterable = true;
67 };
68 } // namespace llvm
69 
70 namespace {
71 auto inst_counter_types() { return enum_seq(VM_CNT, NUM_INST_CNTS); }
72 
73 using RegInterval = std::pair<int, int>;
74 
75 struct HardwareLimits {
76   unsigned VmcntMax;
77   unsigned ExpcntMax;
78   unsigned LgkmcntMax;
79   unsigned VscntMax;
80 };
81 
82 struct RegisterEncoding {
83   unsigned VGPR0;
84   unsigned VGPRL;
85   unsigned SGPR0;
86   unsigned SGPRL;
87 };
88 
89 enum WaitEventType {
90   VMEM_ACCESS,      // vector-memory read & write
91   VMEM_READ_ACCESS, // vector-memory read
92   VMEM_WRITE_ACCESS,// vector-memory write
93   LDS_ACCESS,       // lds read & write
94   GDS_ACCESS,       // gds read & write
95   SQ_MESSAGE,       // send message
96   SMEM_ACCESS,      // scalar-memory read & write
97   EXP_GPR_LOCK,     // export holding on its data src
98   GDS_GPR_LOCK,     // GDS holding on its data and addr src
99   EXP_POS_ACCESS,   // write to export position
100   EXP_PARAM_ACCESS, // write to export parameter
101   VMW_GPR_LOCK,     // vector-memory write holding on its data src
102   NUM_WAIT_EVENTS,
103 };
104 
105 static const unsigned WaitEventMaskForInst[NUM_INST_CNTS] = {
106   (1 << VMEM_ACCESS) | (1 << VMEM_READ_ACCESS),
107   (1 << SMEM_ACCESS) | (1 << LDS_ACCESS) | (1 << GDS_ACCESS) |
108       (1 << SQ_MESSAGE),
109   (1 << EXP_GPR_LOCK) | (1 << GDS_GPR_LOCK) | (1 << VMW_GPR_LOCK) |
110       (1 << EXP_PARAM_ACCESS) | (1 << EXP_POS_ACCESS),
111   (1 << VMEM_WRITE_ACCESS)
112 };
113 
114 // The mapping is:
115 //  0                .. SQ_MAX_PGM_VGPRS-1               real VGPRs
116 //  SQ_MAX_PGM_VGPRS .. NUM_ALL_VGPRS-1                  extra VGPR-like slots
117 //  NUM_ALL_VGPRS    .. NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS-1 real SGPRs
118 // We reserve a fixed number of VGPR slots in the scoring tables for
119 // special tokens like SCMEM_LDS (needed for buffer load to LDS).
120 enum RegisterMapping {
121   SQ_MAX_PGM_VGPRS = 512, // Maximum programmable VGPRs across all targets.
122   AGPR_OFFSET = 256,      // Maximum programmable ArchVGPRs across all targets.
123   SQ_MAX_PGM_SGPRS = 256, // Maximum programmable SGPRs across all targets.
124   NUM_EXTRA_VGPRS = 1,    // A reserved slot for DS.
125   EXTRA_VGPR_LDS = 0,     // An artificial register to track LDS writes.
126   NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_EXTRA_VGPRS, // Where SGPR starts.
127 };
128 
129 // Enumerate different types of result-returning VMEM operations. Although
130 // s_waitcnt orders them all with a single vmcnt counter, in the absence of
131 // s_waitcnt only instructions of the same VmemType are guaranteed to write
132 // their results in order -- so there is no need to insert an s_waitcnt between
133 // two instructions of the same type that write the same vgpr.
134 enum VmemType {
135   // BUF instructions and MIMG instructions without a sampler.
136   VMEM_NOSAMPLER,
137   // MIMG instructions with a sampler.
138   VMEM_SAMPLER,
139   // BVH instructions
140   VMEM_BVH
141 };
142 
143 VmemType getVmemType(const MachineInstr &Inst) {
144   assert(SIInstrInfo::isVMEM(Inst));
145   if (!SIInstrInfo::isMIMG(Inst))
146     return VMEM_NOSAMPLER;
147   const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Inst.getOpcode());
148   const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
149       AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
150   return BaseInfo->BVH ? VMEM_BVH
151                        : BaseInfo->Sampler ? VMEM_SAMPLER : VMEM_NOSAMPLER;
152 }
153 
154 void addWait(AMDGPU::Waitcnt &Wait, InstCounterType T, unsigned Count) {
155   switch (T) {
156   case VM_CNT:
157     Wait.VmCnt = std::min(Wait.VmCnt, Count);
158     break;
159   case EXP_CNT:
160     Wait.ExpCnt = std::min(Wait.ExpCnt, Count);
161     break;
162   case LGKM_CNT:
163     Wait.LgkmCnt = std::min(Wait.LgkmCnt, Count);
164     break;
165   case VS_CNT:
166     Wait.VsCnt = std::min(Wait.VsCnt, Count);
167     break;
168   default:
169     llvm_unreachable("bad InstCounterType");
170   }
171 }
172 
173 // This objects maintains the current score brackets of each wait counter, and
174 // a per-register scoreboard for each wait counter.
175 //
176 // We also maintain the latest score for every event type that can change the
177 // waitcnt in order to know if there are multiple types of events within
178 // the brackets. When multiple types of event happen in the bracket,
179 // wait count may get decreased out of order, therefore we need to put in
180 // "s_waitcnt 0" before use.
181 class WaitcntBrackets {
182 public:
183   WaitcntBrackets(const GCNSubtarget *SubTarget, HardwareLimits Limits,
184                   RegisterEncoding Encoding)
185       : ST(SubTarget), Limits(Limits), Encoding(Encoding) {}
186 
187   unsigned getWaitCountMax(InstCounterType T) const {
188     switch (T) {
189     case VM_CNT:
190       return Limits.VmcntMax;
191     case LGKM_CNT:
192       return Limits.LgkmcntMax;
193     case EXP_CNT:
194       return Limits.ExpcntMax;
195     case VS_CNT:
196       return Limits.VscntMax;
197     default:
198       break;
199     }
200     return 0;
201   }
202 
203   unsigned getScoreLB(InstCounterType T) const {
204     assert(T < NUM_INST_CNTS);
205     return ScoreLBs[T];
206   }
207 
208   unsigned getScoreUB(InstCounterType T) const {
209     assert(T < NUM_INST_CNTS);
210     return ScoreUBs[T];
211   }
212 
213   // Mapping from event to counter.
214   InstCounterType eventCounter(WaitEventType E) {
215     if (WaitEventMaskForInst[VM_CNT] & (1 << E))
216       return VM_CNT;
217     if (WaitEventMaskForInst[LGKM_CNT] & (1 << E))
218       return LGKM_CNT;
219     if (WaitEventMaskForInst[VS_CNT] & (1 << E))
220       return VS_CNT;
221     assert(WaitEventMaskForInst[EXP_CNT] & (1 << E));
222     return EXP_CNT;
223   }
224 
225   unsigned getRegScore(int GprNo, InstCounterType T) {
226     if (GprNo < NUM_ALL_VGPRS) {
227       return VgprScores[T][GprNo];
228     }
229     assert(T == LGKM_CNT);
230     return SgprScores[GprNo - NUM_ALL_VGPRS];
231   }
232 
233   bool merge(const WaitcntBrackets &Other);
234 
235   RegInterval getRegInterval(const MachineInstr *MI, const SIInstrInfo *TII,
236                              const MachineRegisterInfo *MRI,
237                              const SIRegisterInfo *TRI, unsigned OpNo) const;
238 
239   bool counterOutOfOrder(InstCounterType T) const;
240   void simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const;
241   void simplifyWaitcnt(InstCounterType T, unsigned &Count) const;
242   void determineWait(InstCounterType T, unsigned ScoreToWait,
243                      AMDGPU::Waitcnt &Wait) const;
244   void applyWaitcnt(const AMDGPU::Waitcnt &Wait);
245   void applyWaitcnt(InstCounterType T, unsigned Count);
246   void updateByEvent(const SIInstrInfo *TII, const SIRegisterInfo *TRI,
247                      const MachineRegisterInfo *MRI, WaitEventType E,
248                      MachineInstr &MI);
249 
250   bool hasPending() const { return PendingEvents != 0; }
251   bool hasPendingEvent(WaitEventType E) const {
252     return PendingEvents & (1 << E);
253   }
254 
255   bool hasMixedPendingEvents(InstCounterType T) const {
256     unsigned Events = PendingEvents & WaitEventMaskForInst[T];
257     // Return true if more than one bit is set in Events.
258     return Events & (Events - 1);
259   }
260 
261   bool hasPendingFlat() const {
262     return ((LastFlat[LGKM_CNT] > ScoreLBs[LGKM_CNT] &&
263              LastFlat[LGKM_CNT] <= ScoreUBs[LGKM_CNT]) ||
264             (LastFlat[VM_CNT] > ScoreLBs[VM_CNT] &&
265              LastFlat[VM_CNT] <= ScoreUBs[VM_CNT]));
266   }
267 
268   void setPendingFlat() {
269     LastFlat[VM_CNT] = ScoreUBs[VM_CNT];
270     LastFlat[LGKM_CNT] = ScoreUBs[LGKM_CNT];
271   }
272 
273   // Return true if there might be pending writes to the specified vgpr by VMEM
274   // instructions with types different from V.
275   bool hasOtherPendingVmemTypes(int GprNo, VmemType V) const {
276     assert(GprNo < NUM_ALL_VGPRS);
277     return VgprVmemTypes[GprNo] & ~(1 << V);
278   }
279 
280   void clearVgprVmemTypes(int GprNo) {
281     assert(GprNo < NUM_ALL_VGPRS);
282     VgprVmemTypes[GprNo] = 0;
283   }
284 
285   void print(raw_ostream &);
286   void dump() { print(dbgs()); }
287 
288 private:
289   struct MergeInfo {
290     unsigned OldLB;
291     unsigned OtherLB;
292     unsigned MyShift;
293     unsigned OtherShift;
294   };
295   static bool mergeScore(const MergeInfo &M, unsigned &Score,
296                          unsigned OtherScore);
297 
298   void setScoreLB(InstCounterType T, unsigned Val) {
299     assert(T < NUM_INST_CNTS);
300     ScoreLBs[T] = Val;
301   }
302 
303   void setScoreUB(InstCounterType T, unsigned Val) {
304     assert(T < NUM_INST_CNTS);
305     ScoreUBs[T] = Val;
306     if (T == EXP_CNT) {
307       unsigned UB = ScoreUBs[T] - getWaitCountMax(EXP_CNT);
308       if (ScoreLBs[T] < UB && UB < ScoreUBs[T])
309         ScoreLBs[T] = UB;
310     }
311   }
312 
313   void setRegScore(int GprNo, InstCounterType T, unsigned Val) {
314     if (GprNo < NUM_ALL_VGPRS) {
315       VgprUB = std::max(VgprUB, GprNo);
316       VgprScores[T][GprNo] = Val;
317     } else {
318       assert(T == LGKM_CNT);
319       SgprUB = std::max(SgprUB, GprNo - NUM_ALL_VGPRS);
320       SgprScores[GprNo - NUM_ALL_VGPRS] = Val;
321     }
322   }
323 
324   void setExpScore(const MachineInstr *MI, const SIInstrInfo *TII,
325                    const SIRegisterInfo *TRI, const MachineRegisterInfo *MRI,
326                    unsigned OpNo, unsigned Val);
327 
328   const GCNSubtarget *ST = nullptr;
329   HardwareLimits Limits = {};
330   RegisterEncoding Encoding = {};
331   unsigned ScoreLBs[NUM_INST_CNTS] = {0};
332   unsigned ScoreUBs[NUM_INST_CNTS] = {0};
333   unsigned PendingEvents = 0;
334   // Remember the last flat memory operation.
335   unsigned LastFlat[NUM_INST_CNTS] = {0};
336   // wait_cnt scores for every vgpr.
337   // Keep track of the VgprUB and SgprUB to make merge at join efficient.
338   int VgprUB = -1;
339   int SgprUB = -1;
340   unsigned VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS] = {{0}};
341   // Wait cnt scores for every sgpr, only lgkmcnt is relevant.
342   unsigned SgprScores[SQ_MAX_PGM_SGPRS] = {0};
343   // Bitmask of the VmemTypes of VMEM instructions that might have a pending
344   // write to each vgpr.
345   unsigned char VgprVmemTypes[NUM_ALL_VGPRS] = {0};
346 };
347 
348 class SIInsertWaitcnts : public MachineFunctionPass {
349 private:
350   const GCNSubtarget *ST = nullptr;
351   const SIInstrInfo *TII = nullptr;
352   const SIRegisterInfo *TRI = nullptr;
353   const MachineRegisterInfo *MRI = nullptr;
354   AMDGPU::IsaVersion IV;
355 
356   DenseSet<MachineInstr *> TrackedWaitcntSet;
357   DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
358   MachinePostDominatorTree *PDT;
359 
360   struct BlockInfo {
361     MachineBasicBlock *MBB;
362     std::unique_ptr<WaitcntBrackets> Incoming;
363     bool Dirty = true;
364 
365     explicit BlockInfo(MachineBasicBlock *MBB) : MBB(MBB) {}
366   };
367 
368   MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
369 
370   // ForceEmitZeroWaitcnts: force all waitcnts insts to be s_waitcnt 0
371   // because of amdgpu-waitcnt-forcezero flag
372   bool ForceEmitZeroWaitcnts;
373   bool ForceEmitWaitcnt[NUM_INST_CNTS];
374 
375 public:
376   static char ID;
377 
378   SIInsertWaitcnts() : MachineFunctionPass(ID) {
379     (void)ForceExpCounter;
380     (void)ForceLgkmCounter;
381     (void)ForceVMCounter;
382   }
383 
384   bool runOnMachineFunction(MachineFunction &MF) override;
385 
386   StringRef getPassName() const override {
387     return "SI insert wait instructions";
388   }
389 
390   void getAnalysisUsage(AnalysisUsage &AU) const override {
391     AU.setPreservesCFG();
392     AU.addRequired<MachinePostDominatorTree>();
393     MachineFunctionPass::getAnalysisUsage(AU);
394   }
395 
396   bool isForceEmitWaitcnt() const {
397     for (auto T : inst_counter_types())
398       if (ForceEmitWaitcnt[T])
399         return true;
400     return false;
401   }
402 
403   void setForceEmitWaitcnt() {
404 // For non-debug builds, ForceEmitWaitcnt has been initialized to false;
405 // For debug builds, get the debug counter info and adjust if need be
406 #ifndef NDEBUG
407     if (DebugCounter::isCounterSet(ForceExpCounter) &&
408         DebugCounter::shouldExecute(ForceExpCounter)) {
409       ForceEmitWaitcnt[EXP_CNT] = true;
410     } else {
411       ForceEmitWaitcnt[EXP_CNT] = false;
412     }
413 
414     if (DebugCounter::isCounterSet(ForceLgkmCounter) &&
415         DebugCounter::shouldExecute(ForceLgkmCounter)) {
416       ForceEmitWaitcnt[LGKM_CNT] = true;
417     } else {
418       ForceEmitWaitcnt[LGKM_CNT] = false;
419     }
420 
421     if (DebugCounter::isCounterSet(ForceVMCounter) &&
422         DebugCounter::shouldExecute(ForceVMCounter)) {
423       ForceEmitWaitcnt[VM_CNT] = true;
424     } else {
425       ForceEmitWaitcnt[VM_CNT] = false;
426     }
427 #endif // NDEBUG
428   }
429 
430   bool mayAccessVMEMThroughFlat(const MachineInstr &MI) const;
431   bool mayAccessLDSThroughFlat(const MachineInstr &MI) const;
432   bool generateWaitcntInstBefore(MachineInstr &MI,
433                                  WaitcntBrackets &ScoreBrackets,
434                                  MachineInstr *OldWaitcntInstr);
435   void updateEventWaitcntAfter(MachineInstr &Inst,
436                                WaitcntBrackets *ScoreBrackets);
437   bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block,
438                             WaitcntBrackets &ScoreBrackets);
439   bool applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
440                                MachineInstr &OldWaitcntInstr,
441                                AMDGPU::Waitcnt &Wait, const MachineInstr *MI);
442 };
443 
444 } // end anonymous namespace
445 
446 RegInterval WaitcntBrackets::getRegInterval(const MachineInstr *MI,
447                                             const SIInstrInfo *TII,
448                                             const MachineRegisterInfo *MRI,
449                                             const SIRegisterInfo *TRI,
450                                             unsigned OpNo) const {
451   const MachineOperand &Op = MI->getOperand(OpNo);
452   if (!TRI->isInAllocatableClass(Op.getReg()))
453     return {-1, -1};
454 
455   // A use via a PW operand does not need a waitcnt.
456   // A partial write is not a WAW.
457   assert(!Op.getSubReg() || !Op.isUndef());
458 
459   RegInterval Result;
460 
461   unsigned Reg = TRI->getEncodingValue(AMDGPU::getMCReg(Op.getReg(), *ST));
462 
463   if (TRI->isVectorRegister(*MRI, Op.getReg())) {
464     assert(Reg >= Encoding.VGPR0 && Reg <= Encoding.VGPRL);
465     Result.first = Reg - Encoding.VGPR0;
466     if (TRI->isAGPR(*MRI, Op.getReg()))
467       Result.first += AGPR_OFFSET;
468     assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
469   } else if (TRI->isSGPRReg(*MRI, Op.getReg())) {
470     assert(Reg >= Encoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS);
471     Result.first = Reg - Encoding.SGPR0 + NUM_ALL_VGPRS;
472     assert(Result.first >= NUM_ALL_VGPRS &&
473            Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS);
474   }
475   // TODO: Handle TTMP
476   // else if (TRI->isTTMP(*MRI, Reg.getReg())) ...
477   else
478     return {-1, -1};
479 
480   const TargetRegisterClass *RC = TII->getOpRegClass(*MI, OpNo);
481   unsigned Size = TRI->getRegSizeInBits(*RC);
482   Result.second = Result.first + ((Size + 16) / 32);
483 
484   return Result;
485 }
486 
487 void WaitcntBrackets::setExpScore(const MachineInstr *MI,
488                                   const SIInstrInfo *TII,
489                                   const SIRegisterInfo *TRI,
490                                   const MachineRegisterInfo *MRI, unsigned OpNo,
491                                   unsigned Val) {
492   RegInterval Interval = getRegInterval(MI, TII, MRI, TRI, OpNo);
493   assert(TRI->isVectorRegister(*MRI, MI->getOperand(OpNo).getReg()));
494   for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
495     setRegScore(RegNo, EXP_CNT, Val);
496   }
497 }
498 
499 // MUBUF and FLAT LDS DMA operations need a wait on vmcnt before LDS written
500 // can be accessed. A load from LDS to VMEM does not need a wait.
501 static bool mayWriteLDSThroughDMA(const MachineInstr &MI) {
502   return SIInstrInfo::isVALU(MI) &&
503          (SIInstrInfo::isMUBUF(MI) || SIInstrInfo::isFLAT(MI)) &&
504          MI.getOpcode() != AMDGPU::BUFFER_STORE_LDS_DWORD;
505 }
506 
507 void WaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
508                                     const SIRegisterInfo *TRI,
509                                     const MachineRegisterInfo *MRI,
510                                     WaitEventType E, MachineInstr &Inst) {
511   InstCounterType T = eventCounter(E);
512   unsigned CurrScore = getScoreUB(T) + 1;
513   if (CurrScore == 0)
514     report_fatal_error("InsertWaitcnt score wraparound");
515   // PendingEvents and ScoreUB need to be update regardless if this event
516   // changes the score of a register or not.
517   // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
518   PendingEvents |= 1 << E;
519   setScoreUB(T, CurrScore);
520 
521   if (T == EXP_CNT) {
522     // Put score on the source vgprs. If this is a store, just use those
523     // specific register(s).
524     if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) {
525       int AddrOpIdx =
526           AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr);
527       // All GDS operations must protect their address register (same as
528       // export.)
529       if (AddrOpIdx != -1) {
530         setExpScore(&Inst, TII, TRI, MRI, AddrOpIdx, CurrScore);
531       }
532 
533       if (Inst.mayStore()) {
534         if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
535                                        AMDGPU::OpName::data0) != -1) {
536           setExpScore(
537               &Inst, TII, TRI, MRI,
538               AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0),
539               CurrScore);
540         }
541         if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
542                                        AMDGPU::OpName::data1) != -1) {
543           setExpScore(&Inst, TII, TRI, MRI,
544                       AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
545                                                  AMDGPU::OpName::data1),
546                       CurrScore);
547         }
548       } else if (SIInstrInfo::isAtomicRet(Inst) &&
549                  Inst.getOpcode() != AMDGPU::DS_GWS_INIT &&
550                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V &&
551                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR &&
552                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P &&
553                  Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER &&
554                  Inst.getOpcode() != AMDGPU::DS_APPEND &&
555                  Inst.getOpcode() != AMDGPU::DS_CONSUME &&
556                  Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
557         for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
558           const MachineOperand &Op = Inst.getOperand(I);
559           if (Op.isReg() && !Op.isDef() &&
560               TRI->isVectorRegister(*MRI, Op.getReg())) {
561             setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
562           }
563         }
564       }
565     } else if (TII->isFLAT(Inst)) {
566       if (Inst.mayStore()) {
567         setExpScore(
568             &Inst, TII, TRI, MRI,
569             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
570             CurrScore);
571       } else if (SIInstrInfo::isAtomicRet(Inst)) {
572         setExpScore(
573             &Inst, TII, TRI, MRI,
574             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
575             CurrScore);
576       }
577     } else if (TII->isMIMG(Inst)) {
578       if (Inst.mayStore()) {
579         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
580       } else if (SIInstrInfo::isAtomicRet(Inst)) {
581         setExpScore(
582             &Inst, TII, TRI, MRI,
583             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
584             CurrScore);
585       }
586     } else if (TII->isMTBUF(Inst)) {
587       if (Inst.mayStore()) {
588         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
589       }
590     } else if (TII->isMUBUF(Inst)) {
591       if (Inst.mayStore()) {
592         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
593       } else if (SIInstrInfo::isAtomicRet(Inst)) {
594         setExpScore(
595             &Inst, TII, TRI, MRI,
596             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
597             CurrScore);
598       }
599     } else {
600       if (TII->isEXP(Inst)) {
601         // For export the destination registers are really temps that
602         // can be used as the actual source after export patching, so
603         // we need to treat them like sources and set the EXP_CNT
604         // score.
605         for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
606           MachineOperand &DefMO = Inst.getOperand(I);
607           if (DefMO.isReg() && DefMO.isDef() &&
608               TRI->isVGPR(*MRI, DefMO.getReg())) {
609             setRegScore(
610                 TRI->getEncodingValue(AMDGPU::getMCReg(DefMO.getReg(), *ST)),
611                 EXP_CNT, CurrScore);
612           }
613         }
614       }
615       for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
616         MachineOperand &MO = Inst.getOperand(I);
617         if (MO.isReg() && !MO.isDef() &&
618             TRI->isVectorRegister(*MRI, MO.getReg())) {
619           setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
620         }
621       }
622     }
623 #if 0 // TODO: check if this is handled by MUBUF code above.
624   } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD ||
625        Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 ||
626        Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) {
627     MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data);
628     unsigned OpNo;//TODO: find the OpNo for this operand;
629     RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo);
630     for (int RegNo = Interval.first; RegNo < Interval.second;
631     ++RegNo) {
632       setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore);
633     }
634 #endif
635   } else {
636     // Match the score to the destination registers.
637     for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
638       auto &Op = Inst.getOperand(I);
639       if (!Op.isReg() || !Op.isDef())
640         continue;
641       RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I);
642       if (T == VM_CNT) {
643         if (Interval.first >= NUM_ALL_VGPRS)
644           continue;
645         if (SIInstrInfo::isVMEM(Inst)) {
646           VmemType V = getVmemType(Inst);
647           for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo)
648             VgprVmemTypes[RegNo] |= 1 << V;
649         }
650       }
651       for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
652         setRegScore(RegNo, T, CurrScore);
653       }
654     }
655     if (Inst.mayStore() && (TII->isDS(Inst) || mayWriteLDSThroughDMA(Inst))) {
656       setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore);
657     }
658   }
659 }
660 
661 void WaitcntBrackets::print(raw_ostream &OS) {
662   OS << '\n';
663   for (auto T : inst_counter_types()) {
664     unsigned LB = getScoreLB(T);
665     unsigned UB = getScoreUB(T);
666 
667     switch (T) {
668     case VM_CNT:
669       OS << "    VM_CNT(" << UB - LB << "): ";
670       break;
671     case LGKM_CNT:
672       OS << "    LGKM_CNT(" << UB - LB << "): ";
673       break;
674     case EXP_CNT:
675       OS << "    EXP_CNT(" << UB - LB << "): ";
676       break;
677     case VS_CNT:
678       OS << "    VS_CNT(" << UB - LB << "): ";
679       break;
680     default:
681       OS << "    UNKNOWN(" << UB - LB << "): ";
682       break;
683     }
684 
685     if (LB < UB) {
686       // Print vgpr scores.
687       for (int J = 0; J <= VgprUB; J++) {
688         unsigned RegScore = getRegScore(J, T);
689         if (RegScore <= LB)
690           continue;
691         unsigned RelScore = RegScore - LB - 1;
692         if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
693           OS << RelScore << ":v" << J << " ";
694         } else {
695           OS << RelScore << ":ds ";
696         }
697       }
698       // Also need to print sgpr scores for lgkm_cnt.
699       if (T == LGKM_CNT) {
700         for (int J = 0; J <= SgprUB; J++) {
701           unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
702           if (RegScore <= LB)
703             continue;
704           unsigned RelScore = RegScore - LB - 1;
705           OS << RelScore << ":s" << J << " ";
706         }
707       }
708     }
709     OS << '\n';
710   }
711   OS << '\n';
712 }
713 
714 /// Simplify the waitcnt, in the sense of removing redundant counts, and return
715 /// whether a waitcnt instruction is needed at all.
716 void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
717   simplifyWaitcnt(VM_CNT, Wait.VmCnt);
718   simplifyWaitcnt(EXP_CNT, Wait.ExpCnt);
719   simplifyWaitcnt(LGKM_CNT, Wait.LgkmCnt);
720   simplifyWaitcnt(VS_CNT, Wait.VsCnt);
721 }
722 
723 void WaitcntBrackets::simplifyWaitcnt(InstCounterType T,
724                                       unsigned &Count) const {
725   const unsigned LB = getScoreLB(T);
726   const unsigned UB = getScoreUB(T);
727 
728   // The number of outstanding events for this type, T, can be calculated
729   // as (UB - LB). If the current Count is greater than or equal to the number
730   // of outstanding events, then the wait for this counter is redundant.
731   if (Count >= UB - LB)
732     Count = ~0u;
733 }
734 
735 void WaitcntBrackets::determineWait(InstCounterType T, unsigned ScoreToWait,
736                                     AMDGPU::Waitcnt &Wait) const {
737   // If the score of src_operand falls within the bracket, we need an
738   // s_waitcnt instruction.
739   const unsigned LB = getScoreLB(T);
740   const unsigned UB = getScoreUB(T);
741   if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
742     if ((T == VM_CNT || T == LGKM_CNT) &&
743         hasPendingFlat() &&
744         !ST->hasFlatLgkmVMemCountInOrder()) {
745       // If there is a pending FLAT operation, and this is a VMem or LGKM
746       // waitcnt and the target can report early completion, then we need
747       // to force a waitcnt 0.
748       addWait(Wait, T, 0);
749     } else if (counterOutOfOrder(T)) {
750       // Counter can get decremented out-of-order when there
751       // are multiple types event in the bracket. Also emit an s_wait counter
752       // with a conservative value of 0 for the counter.
753       addWait(Wait, T, 0);
754     } else {
755       // If a counter has been maxed out avoid overflow by waiting for
756       // MAX(CounterType) - 1 instead.
757       unsigned NeededWait = std::min(UB - ScoreToWait, getWaitCountMax(T) - 1);
758       addWait(Wait, T, NeededWait);
759     }
760   }
761 }
762 
763 void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) {
764   applyWaitcnt(VM_CNT, Wait.VmCnt);
765   applyWaitcnt(EXP_CNT, Wait.ExpCnt);
766   applyWaitcnt(LGKM_CNT, Wait.LgkmCnt);
767   applyWaitcnt(VS_CNT, Wait.VsCnt);
768 }
769 
770 void WaitcntBrackets::applyWaitcnt(InstCounterType T, unsigned Count) {
771   const unsigned UB = getScoreUB(T);
772   if (Count >= UB)
773     return;
774   if (Count != 0) {
775     if (counterOutOfOrder(T))
776       return;
777     setScoreLB(T, std::max(getScoreLB(T), UB - Count));
778   } else {
779     setScoreLB(T, UB);
780     PendingEvents &= ~WaitEventMaskForInst[T];
781   }
782 }
783 
784 // Where there are multiple types of event in the bracket of a counter,
785 // the decrement may go out of order.
786 bool WaitcntBrackets::counterOutOfOrder(InstCounterType T) const {
787   // Scalar memory read always can go out of order.
788   if (T == LGKM_CNT && hasPendingEvent(SMEM_ACCESS))
789     return true;
790   return hasMixedPendingEvents(T);
791 }
792 
793 INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
794                       false)
795 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
796 INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
797                     false)
798 
799 char SIInsertWaitcnts::ID = 0;
800 
801 char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID;
802 
803 FunctionPass *llvm::createSIInsertWaitcntsPass() {
804   return new SIInsertWaitcnts();
805 }
806 
807 /// Combine consecutive waitcnt instructions that precede \p MI and follow
808 /// \p OldWaitcntInstr and apply any extra wait from waitcnt that were added
809 /// by previous passes. Currently this pass conservatively assumes that these
810 /// preexisting waitcnt are required for correctness.
811 bool SIInsertWaitcnts::applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
812                                                MachineInstr &OldWaitcntInstr,
813                                                AMDGPU::Waitcnt &Wait,
814                                                const MachineInstr *MI) {
815   bool Modified = false;
816   MachineInstr *WaitcntInstr = nullptr;
817   MachineInstr *WaitcntVsCntInstr = nullptr;
818   for (auto II = OldWaitcntInstr.getIterator(), NextI = std::next(II);
819        &*II != MI; II = NextI, ++NextI) {
820     if (II->isMetaInstruction())
821       continue;
822 
823     if (II->getOpcode() == AMDGPU::S_WAITCNT) {
824       // Conservatively update required wait if this waitcnt was added in an
825       // earlier pass. In this case it will not exist in the tracked waitcnt
826       // set.
827       if (!TrackedWaitcntSet.count(&*II)) {
828         unsigned IEnc = II->getOperand(0).getImm();
829         AMDGPU::Waitcnt OldWait = AMDGPU::decodeWaitcnt(IV, IEnc);
830         Wait = Wait.combined(OldWait);
831       }
832 
833       // Merge consecutive waitcnt of the same type by erasing multiples.
834       if (!WaitcntInstr) {
835         WaitcntInstr = &*II;
836       } else {
837         II->eraseFromParent();
838         Modified = true;
839       }
840 
841     } else {
842       assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT);
843       assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
844       if (!TrackedWaitcntSet.count(&*II)) {
845         unsigned OldVSCnt =
846             TII->getNamedOperand(*II, AMDGPU::OpName::simm16)->getImm();
847         Wait.VsCnt = std::min(Wait.VsCnt, OldVSCnt);
848       }
849 
850       if (!WaitcntVsCntInstr) {
851         WaitcntVsCntInstr = &*II;
852       } else {
853         II->eraseFromParent();
854         Modified = true;
855       }
856     }
857   }
858 
859   // Updated encoding of merged waitcnt with the required wait.
860   if (WaitcntInstr) {
861     if (Wait.hasWaitExceptVsCnt()) {
862       unsigned NewEnc = AMDGPU::encodeWaitcnt(IV, Wait);
863       unsigned OldEnc = WaitcntInstr->getOperand(0).getImm();
864       if (OldEnc != NewEnc) {
865         WaitcntInstr->getOperand(0).setImm(NewEnc);
866         Modified = true;
867       }
868       ScoreBrackets.applyWaitcnt(Wait);
869       Wait.VmCnt = ~0u;
870       Wait.LgkmCnt = ~0u;
871       Wait.ExpCnt = ~0u;
872 
873       LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
874                         << "Old Instr: " << *MI << "New Instr: " << *WaitcntInstr
875                         << '\n');
876     } else {
877       WaitcntInstr->eraseFromParent();
878       Modified = true;
879     }
880   }
881 
882   if (WaitcntVsCntInstr) {
883     if (Wait.hasWaitVsCnt()) {
884       assert(ST->hasVscnt());
885       unsigned OldVSCnt =
886           TII->getNamedOperand(*WaitcntVsCntInstr, AMDGPU::OpName::simm16)
887               ->getImm();
888       if (Wait.VsCnt != OldVSCnt) {
889         TII->getNamedOperand(*WaitcntVsCntInstr, AMDGPU::OpName::simm16)
890             ->setImm(Wait.VsCnt);
891         Modified = true;
892       }
893       ScoreBrackets.applyWaitcnt(Wait);
894       Wait.VsCnt = ~0u;
895 
896       LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
897                         << "Old Instr: " << *MI
898                         << "New Instr: " << *WaitcntVsCntInstr << '\n');
899     } else {
900       WaitcntVsCntInstr->eraseFromParent();
901       Modified = true;
902     }
903   }
904 
905   return Modified;
906 }
907 
908 static bool readsVCCZ(const MachineInstr &MI) {
909   unsigned Opc = MI.getOpcode();
910   return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
911          !MI.getOperand(1).isUndef();
912 }
913 
914 /// \returns true if the callee inserts an s_waitcnt 0 on function entry.
915 static bool callWaitsOnFunctionEntry(const MachineInstr &MI) {
916   // Currently all conventions wait, but this may not always be the case.
917   //
918   // TODO: If IPRA is enabled, and the callee is isSafeForNoCSROpt, it may make
919   // senses to omit the wait and do it in the caller.
920   return true;
921 }
922 
923 /// \returns true if the callee is expected to wait for any outstanding waits
924 /// before returning.
925 static bool callWaitsOnFunctionReturn(const MachineInstr &MI) {
926   return true;
927 }
928 
929 ///  Generate s_waitcnt instruction to be placed before cur_Inst.
930 ///  Instructions of a given type are returned in order,
931 ///  but instructions of different types can complete out of order.
932 ///  We rely on this in-order completion
933 ///  and simply assign a score to the memory access instructions.
934 ///  We keep track of the active "score bracket" to determine
935 ///  if an access of a memory read requires an s_waitcnt
936 ///  and if so what the value of each counter is.
937 ///  The "score bracket" is bound by the lower bound and upper bound
938 ///  scores (*_score_LB and *_score_ub respectively).
939 bool SIInsertWaitcnts::generateWaitcntInstBefore(
940     MachineInstr &MI, WaitcntBrackets &ScoreBrackets,
941     MachineInstr *OldWaitcntInstr) {
942   setForceEmitWaitcnt();
943 
944   if (MI.isMetaInstruction())
945     return false;
946 
947   AMDGPU::Waitcnt Wait;
948   bool Modified = false;
949 
950   // FIXME: This should have already been handled by the memory legalizer.
951   // Removing this currently doesn't affect any lit tests, but we need to
952   // verify that nothing was relying on this. The number of buffer invalidates
953   // being handled here should not be expanded.
954   if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
955       MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
956       MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL ||
957       MI.getOpcode() == AMDGPU::BUFFER_GL0_INV ||
958       MI.getOpcode() == AMDGPU::BUFFER_GL1_INV) {
959     Wait.VmCnt = 0;
960   }
961 
962   // All waits must be resolved at call return.
963   // NOTE: this could be improved with knowledge of all call sites or
964   //   with knowledge of the called routines.
965   if (MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
966       MI.getOpcode() == AMDGPU::SI_RETURN ||
967       MI.getOpcode() == AMDGPU::S_SETPC_B64_return ||
968       (MI.isReturn() && MI.isCall() && !callWaitsOnFunctionEntry(MI))) {
969     Wait = Wait.combined(AMDGPU::Waitcnt::allZero(ST->hasVscnt()));
970   }
971   // Resolve vm waits before gs-done.
972   else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
973             MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
974            ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) ==
975             AMDGPU::SendMsg::ID_GS_DONE)) {
976     Wait.VmCnt = 0;
977   }
978 #if 0 // TODO: the following blocks of logic when we have fence.
979   else if (MI.getOpcode() == SC_FENCE) {
980     const unsigned int group_size =
981       context->shader_info->GetMaxThreadGroupSize();
982     // group_size == 0 means thread group size is unknown at compile time
983     const bool group_is_multi_wave =
984       (group_size == 0 || group_size > target_info->GetWaveFrontSize());
985     const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
986 
987     for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
988       SCRegType src_type = Inst->GetSrcType(i);
989       switch (src_type) {
990         case SCMEM_LDS:
991           if (group_is_multi_wave ||
992             context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
993             EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
994                                ScoreBrackets->getScoreUB(LGKM_CNT));
995             // LDS may have to wait for VM_CNT after buffer load to LDS
996             if (target_info->HasBufferLoadToLDS()) {
997               EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
998                                  ScoreBrackets->getScoreUB(VM_CNT));
999             }
1000           }
1001           break;
1002 
1003         case SCMEM_GDS:
1004           if (group_is_multi_wave || fence_is_global) {
1005             EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
1006               ScoreBrackets->getScoreUB(EXP_CNT));
1007             EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
1008               ScoreBrackets->getScoreUB(LGKM_CNT));
1009           }
1010           break;
1011 
1012         case SCMEM_UAV:
1013         case SCMEM_TFBUF:
1014         case SCMEM_RING:
1015         case SCMEM_SCATTER:
1016           if (group_is_multi_wave || fence_is_global) {
1017             EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
1018               ScoreBrackets->getScoreUB(EXP_CNT));
1019             EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
1020               ScoreBrackets->getScoreUB(VM_CNT));
1021           }
1022           break;
1023 
1024         case SCMEM_SCRATCH:
1025         default:
1026           break;
1027       }
1028     }
1029   }
1030 #endif
1031 
1032   // Export & GDS instructions do not read the EXEC mask until after the export
1033   // is granted (which can occur well after the instruction is issued).
1034   // The shader program must flush all EXP operations on the export-count
1035   // before overwriting the EXEC mask.
1036   else {
1037     if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
1038       // Export and GDS are tracked individually, either may trigger a waitcnt
1039       // for EXEC.
1040       if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1041           ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1042           ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1043           ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1044         Wait.ExpCnt = 0;
1045       }
1046     }
1047 
1048     if (MI.isCall() && callWaitsOnFunctionEntry(MI)) {
1049       // The function is going to insert a wait on everything in its prolog.
1050       // This still needs to be careful if the call target is a load (e.g. a GOT
1051       // load). We also need to check WAW dependency with saved PC.
1052       Wait = AMDGPU::Waitcnt();
1053 
1054       int CallAddrOpIdx =
1055           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
1056 
1057       if (MI.getOperand(CallAddrOpIdx).isReg()) {
1058         RegInterval CallAddrOpInterval =
1059           ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, CallAddrOpIdx);
1060 
1061         for (int RegNo = CallAddrOpInterval.first;
1062              RegNo < CallAddrOpInterval.second; ++RegNo)
1063           ScoreBrackets.determineWait(
1064             LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1065 
1066         int RtnAddrOpIdx =
1067           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::dst);
1068         if (RtnAddrOpIdx != -1) {
1069           RegInterval RtnAddrOpInterval =
1070             ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, RtnAddrOpIdx);
1071 
1072           for (int RegNo = RtnAddrOpInterval.first;
1073                RegNo < RtnAddrOpInterval.second; ++RegNo)
1074             ScoreBrackets.determineWait(
1075               LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1076         }
1077       }
1078     } else {
1079       // FIXME: Should not be relying on memoperands.
1080       // Look at the source operands of every instruction to see if
1081       // any of them results from a previous memory operation that affects
1082       // its current usage. If so, an s_waitcnt instruction needs to be
1083       // emitted.
1084       // If the source operand was defined by a load, add the s_waitcnt
1085       // instruction.
1086       //
1087       // Two cases are handled for destination operands:
1088       // 1) If the destination operand was defined by a load, add the s_waitcnt
1089       // instruction to guarantee the right WAW order.
1090       // 2) If a destination operand that was used by a recent export/store ins,
1091       // add s_waitcnt on exp_cnt to guarantee the WAR order.
1092       for (const MachineMemOperand *Memop : MI.memoperands()) {
1093         const Value *Ptr = Memop->getValue();
1094         if (Memop->isStore() && SLoadAddresses.count(Ptr)) {
1095           addWait(Wait, LGKM_CNT, 0);
1096           if (PDT->dominates(MI.getParent(), SLoadAddresses.find(Ptr)->second))
1097             SLoadAddresses.erase(Ptr);
1098         }
1099         unsigned AS = Memop->getAddrSpace();
1100         if (AS != AMDGPUAS::LOCAL_ADDRESS && AS != AMDGPUAS::FLAT_ADDRESS)
1101           continue;
1102         unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
1103         // VM_CNT is only relevant to vgpr or LDS.
1104         ScoreBrackets.determineWait(
1105             VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1106         if (Memop->isStore()) {
1107           ScoreBrackets.determineWait(
1108               EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
1109         }
1110       }
1111 
1112       // Loop over use and def operands.
1113       for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1114         MachineOperand &Op = MI.getOperand(I);
1115         if (!Op.isReg())
1116           continue;
1117         RegInterval Interval =
1118             ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, I);
1119 
1120         const bool IsVGPR = TRI->isVectorRegister(*MRI, Op.getReg());
1121         for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1122           if (IsVGPR) {
1123             // RAW always needs an s_waitcnt. WAW needs an s_waitcnt unless the
1124             // previous write and this write are the same type of VMEM
1125             // instruction, in which case they're guaranteed to write their
1126             // results in order anyway.
1127             if (Op.isUse() || !SIInstrInfo::isVMEM(MI) ||
1128                 ScoreBrackets.hasOtherPendingVmemTypes(RegNo,
1129                                                        getVmemType(MI))) {
1130               ScoreBrackets.determineWait(
1131                   VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1132               ScoreBrackets.clearVgprVmemTypes(RegNo);
1133             }
1134             if (Op.isDef()) {
1135               ScoreBrackets.determineWait(
1136                   EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
1137             }
1138           }
1139           ScoreBrackets.determineWait(
1140               LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1141         }
1142       }
1143     }
1144   }
1145 
1146   // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1147   // occurs before the instruction. Doing it here prevents any additional
1148   // S_WAITCNTs from being emitted if the instruction was marked as
1149   // requiring a WAITCNT beforehand.
1150   if (MI.getOpcode() == AMDGPU::S_BARRIER &&
1151       !ST->hasAutoWaitcntBeforeBarrier()) {
1152     Wait = Wait.combined(AMDGPU::Waitcnt::allZero(ST->hasVscnt()));
1153   }
1154 
1155   // TODO: Remove this work-around, enable the assert for Bug 457939
1156   //       after fixing the scheduler. Also, the Shader Compiler code is
1157   //       independent of target.
1158   if (readsVCCZ(MI) && ST->hasReadVCCZBug()) {
1159     if (ScoreBrackets.getScoreLB(LGKM_CNT) <
1160             ScoreBrackets.getScoreUB(LGKM_CNT) &&
1161         ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
1162       Wait.LgkmCnt = 0;
1163     }
1164   }
1165 
1166   // Verify that the wait is actually needed.
1167   ScoreBrackets.simplifyWaitcnt(Wait);
1168 
1169   if (ForceEmitZeroWaitcnts)
1170     Wait = AMDGPU::Waitcnt::allZero(ST->hasVscnt());
1171 
1172   if (ForceEmitWaitcnt[VM_CNT])
1173     Wait.VmCnt = 0;
1174   if (ForceEmitWaitcnt[EXP_CNT])
1175     Wait.ExpCnt = 0;
1176   if (ForceEmitWaitcnt[LGKM_CNT])
1177     Wait.LgkmCnt = 0;
1178   if (ForceEmitWaitcnt[VS_CNT])
1179     Wait.VsCnt = 0;
1180 
1181   if (OldWaitcntInstr) {
1182     // Try to merge the required wait with preexisting waitcnt instructions.
1183     // Also erase redundant waitcnt.
1184     Modified =
1185         applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr, Wait, &MI);
1186   } else {
1187     // Update waitcnt brackets after determining the required wait.
1188     ScoreBrackets.applyWaitcnt(Wait);
1189   }
1190 
1191   // Build new waitcnt instructions unless no wait is needed or the old waitcnt
1192   // instruction was modified to handle the required wait.
1193   if (Wait.hasWaitExceptVsCnt()) {
1194     unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
1195     auto SWaitInst = BuildMI(*MI.getParent(), MI.getIterator(),
1196                              MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1197                          .addImm(Enc);
1198     TrackedWaitcntSet.insert(SWaitInst);
1199     Modified = true;
1200 
1201     LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
1202                       << "Old Instr: " << MI
1203                       << "New Instr: " << *SWaitInst << '\n');
1204   }
1205 
1206   if (Wait.hasWaitVsCnt()) {
1207     assert(ST->hasVscnt());
1208 
1209     auto SWaitInst =
1210         BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
1211                 TII->get(AMDGPU::S_WAITCNT_VSCNT))
1212             .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1213             .addImm(Wait.VsCnt);
1214     TrackedWaitcntSet.insert(SWaitInst);
1215     Modified = true;
1216 
1217     LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
1218                       << "Old Instr: " << MI
1219                       << "New Instr: " << *SWaitInst << '\n');
1220   }
1221 
1222   return Modified;
1223 }
1224 
1225 // This is a flat memory operation. Check to see if it has memory tokens other
1226 // than LDS. Other address spaces supported by flat memory operations involve
1227 // global memory.
1228 bool SIInsertWaitcnts::mayAccessVMEMThroughFlat(const MachineInstr &MI) const {
1229   assert(TII->isFLAT(MI));
1230 
1231   // All flat instructions use the VMEM counter.
1232   assert(TII->usesVM_CNT(MI));
1233 
1234   // If there are no memory operands then conservatively assume the flat
1235   // operation may access VMEM.
1236   if (MI.memoperands_empty())
1237     return true;
1238 
1239   // See if any memory operand specifies an address space that involves VMEM.
1240   // Flat operations only supported FLAT, LOCAL (LDS), or address spaces
1241   // involving VMEM such as GLOBAL, CONSTANT, PRIVATE (SCRATCH), etc. The REGION
1242   // (GDS) address space is not supported by flat operations. Therefore, simply
1243   // return true unless only the LDS address space is found.
1244   for (const MachineMemOperand *Memop : MI.memoperands()) {
1245     unsigned AS = Memop->getAddrSpace();
1246     assert(AS != AMDGPUAS::REGION_ADDRESS);
1247     if (AS != AMDGPUAS::LOCAL_ADDRESS)
1248       return true;
1249   }
1250 
1251   return false;
1252 }
1253 
1254 // This is a flat memory operation. Check to see if it has memory tokens for
1255 // either LDS or FLAT.
1256 bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
1257   assert(TII->isFLAT(MI));
1258 
1259   // Flat instruction such as SCRATCH and GLOBAL do not use the lgkm counter.
1260   if (!TII->usesLGKM_CNT(MI))
1261     return false;
1262 
1263   // If in tgsplit mode then there can be no use of LDS.
1264   if (ST->isTgSplitEnabled())
1265     return false;
1266 
1267   // If there are no memory operands then conservatively assume the flat
1268   // operation may access LDS.
1269   if (MI.memoperands_empty())
1270     return true;
1271 
1272   // See if any memory operand specifies an address space that involves LDS.
1273   for (const MachineMemOperand *Memop : MI.memoperands()) {
1274     unsigned AS = Memop->getAddrSpace();
1275     if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS)
1276       return true;
1277   }
1278 
1279   return false;
1280 }
1281 
1282 void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
1283                                                WaitcntBrackets *ScoreBrackets) {
1284   // Now look at the instruction opcode. If it is a memory access
1285   // instruction, update the upper-bound of the appropriate counter's
1286   // bracket and the destination operand scores.
1287   // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
1288   if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
1289     if (TII->isAlwaysGDS(Inst.getOpcode()) ||
1290         TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
1291       ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1292       ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1293     } else {
1294       ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1295     }
1296   } else if (TII->isFLAT(Inst)) {
1297     assert(Inst.mayLoadOrStore());
1298 
1299     int FlatASCount = 0;
1300 
1301     if (mayAccessVMEMThroughFlat(Inst)) {
1302       ++FlatASCount;
1303       if (!ST->hasVscnt())
1304         ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1305       else if (Inst.mayLoad() && !SIInstrInfo::isAtomicNoRet(Inst))
1306         ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1307       else
1308         ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1309     }
1310 
1311     if (mayAccessLDSThroughFlat(Inst)) {
1312       ++FlatASCount;
1313       ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1314     }
1315 
1316     // A Flat memory operation must access at least one address space.
1317     assert(FlatASCount);
1318 
1319     // This is a flat memory operation that access both VMEM and LDS, so note it
1320     // - it will require that both the VM and LGKM be flushed to zero if it is
1321     // pending when a VM or LGKM dependency occurs.
1322     if (FlatASCount > 1)
1323       ScoreBrackets->setPendingFlat();
1324   } else if (SIInstrInfo::isVMEM(Inst) &&
1325              !llvm::AMDGPU::getMUBUFIsBufferInv(Inst.getOpcode())) {
1326     if (!ST->hasVscnt())
1327       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1328     else if ((Inst.mayLoad() && !SIInstrInfo::isAtomicNoRet(Inst)) ||
1329              /* IMAGE_GET_RESINFO / IMAGE_GET_LOD */
1330              (TII->isMIMG(Inst) && !Inst.mayLoad() && !Inst.mayStore()))
1331       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1332     else if (Inst.mayStore())
1333       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1334 
1335     if (ST->vmemWriteNeedsExpWaitcnt() &&
1336         (Inst.mayStore() || SIInstrInfo::isAtomicRet(Inst))) {
1337       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1338     }
1339   } else if (TII->isSMRD(Inst)) {
1340     ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1341   } else if (Inst.isCall()) {
1342     if (callWaitsOnFunctionReturn(Inst)) {
1343       // Act as a wait on everything
1344       ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt::allZero(ST->hasVscnt()));
1345     } else {
1346       // May need to way wait for anything.
1347       ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
1348     }
1349   } else if (SIInstrInfo::isEXP(Inst)) {
1350     unsigned Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1351     if (Imm >= AMDGPU::Exp::ET_PARAM0 && Imm <= AMDGPU::Exp::ET_PARAM31)
1352       ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1353     else if (Imm >= AMDGPU::Exp::ET_POS0 && Imm <= AMDGPU::Exp::ET_POS_LAST)
1354       ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1355     else
1356       ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1357   } else {
1358     switch (Inst.getOpcode()) {
1359     case AMDGPU::S_SENDMSG:
1360     case AMDGPU::S_SENDMSGHALT:
1361       ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1362       break;
1363     case AMDGPU::S_MEMTIME:
1364     case AMDGPU::S_MEMREALTIME:
1365       ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1366       break;
1367     }
1368   }
1369 }
1370 
1371 bool WaitcntBrackets::mergeScore(const MergeInfo &M, unsigned &Score,
1372                                  unsigned OtherScore) {
1373   unsigned MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
1374   unsigned OtherShifted =
1375       OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
1376   Score = std::max(MyShifted, OtherShifted);
1377   return OtherShifted > MyShifted;
1378 }
1379 
1380 /// Merge the pending events and associater score brackets of \p Other into
1381 /// this brackets status.
1382 ///
1383 /// Returns whether the merge resulted in a change that requires tighter waits
1384 /// (i.e. the merged brackets strictly dominate the original brackets).
1385 bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
1386   bool StrictDom = false;
1387 
1388   VgprUB = std::max(VgprUB, Other.VgprUB);
1389   SgprUB = std::max(SgprUB, Other.SgprUB);
1390 
1391   for (auto T : inst_counter_types()) {
1392     // Merge event flags for this counter
1393     const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[T];
1394     const unsigned OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T];
1395     if (OtherEvents & ~OldEvents)
1396       StrictDom = true;
1397     PendingEvents |= OtherEvents;
1398 
1399     // Merge scores for this counter
1400     const unsigned MyPending = ScoreUBs[T] - ScoreLBs[T];
1401     const unsigned OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
1402     const unsigned NewUB = ScoreLBs[T] + std::max(MyPending, OtherPending);
1403     if (NewUB < ScoreLBs[T])
1404       report_fatal_error("waitcnt score overflow");
1405 
1406     MergeInfo M;
1407     M.OldLB = ScoreLBs[T];
1408     M.OtherLB = Other.ScoreLBs[T];
1409     M.MyShift = NewUB - ScoreUBs[T];
1410     M.OtherShift = NewUB - Other.ScoreUBs[T];
1411 
1412     ScoreUBs[T] = NewUB;
1413 
1414     StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
1415 
1416     bool RegStrictDom = false;
1417     for (int J = 0; J <= VgprUB; J++) {
1418       RegStrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]);
1419     }
1420 
1421     if (T == VM_CNT) {
1422       for (int J = 0; J <= VgprUB; J++) {
1423         unsigned char NewVmemTypes = VgprVmemTypes[J] | Other.VgprVmemTypes[J];
1424         RegStrictDom |= NewVmemTypes != VgprVmemTypes[J];
1425         VgprVmemTypes[J] = NewVmemTypes;
1426       }
1427     }
1428 
1429     if (T == LGKM_CNT) {
1430       for (int J = 0; J <= SgprUB; J++) {
1431         RegStrictDom |= mergeScore(M, SgprScores[J], Other.SgprScores[J]);
1432       }
1433     }
1434 
1435     if (RegStrictDom)
1436       StrictDom = true;
1437   }
1438 
1439   return StrictDom;
1440 }
1441 
1442 // Generate s_waitcnt instructions where needed.
1443 bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1444                                             MachineBasicBlock &Block,
1445                                             WaitcntBrackets &ScoreBrackets) {
1446   bool Modified = false;
1447 
1448   LLVM_DEBUG({
1449     dbgs() << "*** Block" << Block.getNumber() << " ***";
1450     ScoreBrackets.dump();
1451   });
1452 
1453   // Track the correctness of vccz through this basic block. There are two
1454   // reasons why it might be incorrect; see ST->hasReadVCCZBug() and
1455   // ST->partialVCCWritesUpdateVCCZ().
1456   bool VCCZCorrect = true;
1457   if (ST->hasReadVCCZBug()) {
1458     // vccz could be incorrect at a basic block boundary if a predecessor wrote
1459     // to vcc and then issued an smem load.
1460     VCCZCorrect = false;
1461   } else if (!ST->partialVCCWritesUpdateVCCZ()) {
1462     // vccz could be incorrect at a basic block boundary if a predecessor wrote
1463     // to vcc_lo or vcc_hi.
1464     VCCZCorrect = false;
1465   }
1466 
1467   // Walk over the instructions.
1468   MachineInstr *OldWaitcntInstr = nullptr;
1469 
1470   for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(),
1471                                          E = Block.instr_end();
1472        Iter != E;) {
1473     MachineInstr &Inst = *Iter;
1474 
1475     // Track pre-existing waitcnts that were added in earlier iterations or by
1476     // the memory legalizer.
1477     if (Inst.getOpcode() == AMDGPU::S_WAITCNT ||
1478         (Inst.getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1479          Inst.getOperand(0).isReg() &&
1480          Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL)) {
1481       if (!OldWaitcntInstr)
1482         OldWaitcntInstr = &Inst;
1483       ++Iter;
1484       continue;
1485     }
1486 
1487     // Generate an s_waitcnt instruction to be placed before Inst, if needed.
1488     Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr);
1489     OldWaitcntInstr = nullptr;
1490 
1491     // Restore vccz if it's not known to be correct already.
1492     bool RestoreVCCZ = !VCCZCorrect && readsVCCZ(Inst);
1493 
1494     // Don't examine operands unless we need to track vccz correctness.
1495     if (ST->hasReadVCCZBug() || !ST->partialVCCWritesUpdateVCCZ()) {
1496       if (Inst.definesRegister(AMDGPU::VCC_LO) ||
1497           Inst.definesRegister(AMDGPU::VCC_HI)) {
1498         // Up to gfx9, writes to vcc_lo and vcc_hi don't update vccz.
1499         if (!ST->partialVCCWritesUpdateVCCZ())
1500           VCCZCorrect = false;
1501       } else if (Inst.definesRegister(AMDGPU::VCC)) {
1502         // There is a hardware bug on CI/SI where SMRD instruction may corrupt
1503         // vccz bit, so when we detect that an instruction may read from a
1504         // corrupt vccz bit, we need to:
1505         // 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD
1506         //    operations to complete.
1507         // 2. Restore the correct value of vccz by writing the current value
1508         //    of vcc back to vcc.
1509         if (ST->hasReadVCCZBug() &&
1510             ScoreBrackets.getScoreLB(LGKM_CNT) <
1511                 ScoreBrackets.getScoreUB(LGKM_CNT) &&
1512             ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
1513           // Writes to vcc while there's an outstanding smem read may get
1514           // clobbered as soon as any read completes.
1515           VCCZCorrect = false;
1516         } else {
1517           // Writes to vcc will fix any incorrect value in vccz.
1518           VCCZCorrect = true;
1519         }
1520       }
1521     }
1522 
1523     if (TII->isSMRD(Inst)) {
1524       for (const MachineMemOperand *Memop : Inst.memoperands()) {
1525         // No need to handle invariant loads when avoiding WAR conflicts, as
1526         // there cannot be a vector store to the same memory location.
1527         if (!Memop->isInvariant()) {
1528           const Value *Ptr = Memop->getValue();
1529           SLoadAddresses.insert(std::make_pair(Ptr, Inst.getParent()));
1530         }
1531       }
1532       if (ST->hasReadVCCZBug()) {
1533         // This smem read could complete and clobber vccz at any time.
1534         VCCZCorrect = false;
1535       }
1536     }
1537 
1538     updateEventWaitcntAfter(Inst, &ScoreBrackets);
1539 
1540 #if 0 // TODO: implement resource type check controlled by options with ub = LB.
1541     // If this instruction generates a S_SETVSKIP because it is an
1542     // indexed resource, and we are on Tahiti, then it will also force
1543     // an S_WAITCNT vmcnt(0)
1544     if (RequireCheckResourceType(Inst, context)) {
1545       // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1546       ScoreBrackets->setScoreLB(VM_CNT,
1547       ScoreBrackets->getScoreUB(VM_CNT));
1548     }
1549 #endif
1550 
1551     LLVM_DEBUG({
1552       Inst.print(dbgs());
1553       ScoreBrackets.dump();
1554     });
1555 
1556     // TODO: Remove this work-around after fixing the scheduler and enable the
1557     // assert above.
1558     if (RestoreVCCZ) {
1559       // Restore the vccz bit.  Any time a value is written to vcc, the vcc
1560       // bit is updated, so we can restore the bit by reading the value of
1561       // vcc and then writing it back to the register.
1562       BuildMI(Block, Inst, Inst.getDebugLoc(),
1563               TII->get(ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
1564               TRI->getVCC())
1565           .addReg(TRI->getVCC());
1566       VCCZCorrect = true;
1567       Modified = true;
1568     }
1569 
1570     ++Iter;
1571   }
1572 
1573   return Modified;
1574 }
1575 
1576 bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
1577   ST = &MF.getSubtarget<GCNSubtarget>();
1578   TII = ST->getInstrInfo();
1579   TRI = &TII->getRegisterInfo();
1580   MRI = &MF.getRegInfo();
1581   IV = AMDGPU::getIsaVersion(ST->getCPU());
1582   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1583   PDT = &getAnalysis<MachinePostDominatorTree>();
1584 
1585   ForceEmitZeroWaitcnts = ForceEmitZeroFlag;
1586   for (auto T : inst_counter_types())
1587     ForceEmitWaitcnt[T] = false;
1588 
1589   HardwareLimits Limits = {};
1590   Limits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1591   Limits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1592   Limits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
1593   Limits.VscntMax = ST->hasVscnt() ? 63 : 0;
1594 
1595   unsigned NumVGPRsMax = ST->getAddressableNumVGPRs();
1596   unsigned NumSGPRsMax = ST->getAddressableNumSGPRs();
1597   assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1598   assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1599 
1600   RegisterEncoding Encoding = {};
1601   Encoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1602   Encoding.VGPRL = Encoding.VGPR0 + NumVGPRsMax - 1;
1603   Encoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1604   Encoding.SGPRL = Encoding.SGPR0 + NumSGPRsMax - 1;
1605 
1606   TrackedWaitcntSet.clear();
1607   BlockInfos.clear();
1608   bool Modified = false;
1609 
1610   if (!MFI->isEntryFunction()) {
1611     // Wait for any outstanding memory operations that the input registers may
1612     // depend on. We can't track them and it's better to do the wait after the
1613     // costly call sequence.
1614 
1615     // TODO: Could insert earlier and schedule more liberally with operations
1616     // that only use caller preserved registers.
1617     MachineBasicBlock &EntryBB = MF.front();
1618     MachineBasicBlock::iterator I = EntryBB.begin();
1619     for (MachineBasicBlock::iterator E = EntryBB.end();
1620          I != E && (I->isPHI() || I->isMetaInstruction()); ++I)
1621       ;
1622     BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT)).addImm(0);
1623     if (ST->hasVscnt())
1624       BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT_VSCNT))
1625           .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1626           .addImm(0);
1627 
1628     Modified = true;
1629   }
1630 
1631   // Keep iterating over the blocks in reverse post order, inserting and
1632   // updating s_waitcnt where needed, until a fix point is reached.
1633   for (auto *MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
1634     BlockInfos.insert({MBB, BlockInfo(MBB)});
1635 
1636   std::unique_ptr<WaitcntBrackets> Brackets;
1637   bool Repeat;
1638   do {
1639     Repeat = false;
1640 
1641     for (auto BII = BlockInfos.begin(), BIE = BlockInfos.end(); BII != BIE;
1642          ++BII) {
1643       BlockInfo &BI = BII->second;
1644       if (!BI.Dirty)
1645         continue;
1646 
1647       if (BI.Incoming) {
1648         if (!Brackets)
1649           Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
1650         else
1651           *Brackets = *BI.Incoming;
1652       } else {
1653         if (!Brackets)
1654           Brackets = std::make_unique<WaitcntBrackets>(ST, Limits, Encoding);
1655         else
1656           *Brackets = WaitcntBrackets(ST, Limits, Encoding);
1657       }
1658 
1659       Modified |= insertWaitcntInBlock(MF, *BI.MBB, *Brackets);
1660       BI.Dirty = false;
1661 
1662       if (Brackets->hasPending()) {
1663         BlockInfo *MoveBracketsToSucc = nullptr;
1664         for (MachineBasicBlock *Succ : BI.MBB->successors()) {
1665           auto SuccBII = BlockInfos.find(Succ);
1666           BlockInfo &SuccBI = SuccBII->second;
1667           if (!SuccBI.Incoming) {
1668             SuccBI.Dirty = true;
1669             if (SuccBII <= BII)
1670               Repeat = true;
1671             if (!MoveBracketsToSucc) {
1672               MoveBracketsToSucc = &SuccBI;
1673             } else {
1674               SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
1675             }
1676           } else if (SuccBI.Incoming->merge(*Brackets)) {
1677             SuccBI.Dirty = true;
1678             if (SuccBII <= BII)
1679               Repeat = true;
1680           }
1681         }
1682         if (MoveBracketsToSucc)
1683           MoveBracketsToSucc->Incoming = std::move(Brackets);
1684       }
1685     }
1686   } while (Repeat);
1687 
1688   if (ST->hasScalarStores()) {
1689     SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1690     bool HaveScalarStores = false;
1691 
1692     for (MachineBasicBlock &MBB : MF) {
1693       for (MachineInstr &MI : MBB) {
1694         if (!HaveScalarStores && TII->isScalarStore(MI))
1695           HaveScalarStores = true;
1696 
1697         if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
1698             MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1699           EndPgmBlocks.push_back(&MBB);
1700       }
1701     }
1702 
1703     if (HaveScalarStores) {
1704       // If scalar writes are used, the cache must be flushed or else the next
1705       // wave to reuse the same scratch memory can be clobbered.
1706       //
1707       // Insert s_dcache_wb at wave termination points if there were any scalar
1708       // stores, and only if the cache hasn't already been flushed. This could
1709       // be improved by looking across blocks for flushes in postdominating
1710       // blocks from the stores but an explicitly requested flush is probably
1711       // very rare.
1712       for (MachineBasicBlock *MBB : EndPgmBlocks) {
1713         bool SeenDCacheWB = false;
1714 
1715         for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
1716              I != E; ++I) {
1717           if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1718             SeenDCacheWB = true;
1719           else if (TII->isScalarStore(*I))
1720             SeenDCacheWB = false;
1721 
1722           // FIXME: It would be better to insert this before a waitcnt if any.
1723           if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1724                I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1725               !SeenDCacheWB) {
1726             Modified = true;
1727             BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
1728           }
1729         }
1730       }
1731     }
1732   }
1733 
1734   return Modified;
1735 }
1736