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 = 226, // 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,     // This is a placeholder the Shader algorithm uses.
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 void WaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
500                                     const SIRegisterInfo *TRI,
501                                     const MachineRegisterInfo *MRI,
502                                     WaitEventType E, MachineInstr &Inst) {
503   InstCounterType T = eventCounter(E);
504   unsigned CurrScore = getScoreUB(T) + 1;
505   if (CurrScore == 0)
506     report_fatal_error("InsertWaitcnt score wraparound");
507   // PendingEvents and ScoreUB need to be update regardless if this event
508   // changes the score of a register or not.
509   // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
510   PendingEvents |= 1 << E;
511   setScoreUB(T, CurrScore);
512 
513   if (T == EXP_CNT) {
514     // Put score on the source vgprs. If this is a store, just use those
515     // specific register(s).
516     if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) {
517       int AddrOpIdx =
518           AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr);
519       // All GDS operations must protect their address register (same as
520       // export.)
521       if (AddrOpIdx != -1) {
522         setExpScore(&Inst, TII, TRI, MRI, AddrOpIdx, CurrScore);
523       }
524 
525       if (Inst.mayStore()) {
526         if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
527                                        AMDGPU::OpName::data0) != -1) {
528           setExpScore(
529               &Inst, TII, TRI, MRI,
530               AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0),
531               CurrScore);
532         }
533         if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
534                                        AMDGPU::OpName::data1) != -1) {
535           setExpScore(&Inst, TII, TRI, MRI,
536                       AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
537                                                  AMDGPU::OpName::data1),
538                       CurrScore);
539         }
540       } else if (SIInstrInfo::isAtomicRet(Inst) &&
541                  Inst.getOpcode() != AMDGPU::DS_GWS_INIT &&
542                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V &&
543                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR &&
544                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P &&
545                  Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER &&
546                  Inst.getOpcode() != AMDGPU::DS_APPEND &&
547                  Inst.getOpcode() != AMDGPU::DS_CONSUME &&
548                  Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
549         for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
550           const MachineOperand &Op = Inst.getOperand(I);
551           if (Op.isReg() && !Op.isDef() &&
552               TRI->isVectorRegister(*MRI, Op.getReg())) {
553             setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
554           }
555         }
556       }
557     } else if (TII->isFLAT(Inst)) {
558       if (Inst.mayStore()) {
559         setExpScore(
560             &Inst, TII, TRI, MRI,
561             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
562             CurrScore);
563       } else if (SIInstrInfo::isAtomicRet(Inst)) {
564         setExpScore(
565             &Inst, TII, TRI, MRI,
566             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
567             CurrScore);
568       }
569     } else if (TII->isMIMG(Inst)) {
570       if (Inst.mayStore()) {
571         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
572       } else if (SIInstrInfo::isAtomicRet(Inst)) {
573         setExpScore(
574             &Inst, TII, TRI, MRI,
575             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
576             CurrScore);
577       }
578     } else if (TII->isMTBUF(Inst)) {
579       if (Inst.mayStore()) {
580         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
581       }
582     } else if (TII->isMUBUF(Inst)) {
583       if (Inst.mayStore()) {
584         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
585       } else if (SIInstrInfo::isAtomicRet(Inst)) {
586         setExpScore(
587             &Inst, TII, TRI, MRI,
588             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
589             CurrScore);
590       }
591     } else {
592       if (TII->isEXP(Inst)) {
593         // For export the destination registers are really temps that
594         // can be used as the actual source after export patching, so
595         // we need to treat them like sources and set the EXP_CNT
596         // score.
597         for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
598           MachineOperand &DefMO = Inst.getOperand(I);
599           if (DefMO.isReg() && DefMO.isDef() &&
600               TRI->isVGPR(*MRI, DefMO.getReg())) {
601             setRegScore(
602                 TRI->getEncodingValue(AMDGPU::getMCReg(DefMO.getReg(), *ST)),
603                 EXP_CNT, CurrScore);
604           }
605         }
606       }
607       for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
608         MachineOperand &MO = Inst.getOperand(I);
609         if (MO.isReg() && !MO.isDef() &&
610             TRI->isVectorRegister(*MRI, MO.getReg())) {
611           setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
612         }
613       }
614     }
615 #if 0 // TODO: check if this is handled by MUBUF code above.
616   } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD ||
617        Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 ||
618        Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) {
619     MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data);
620     unsigned OpNo;//TODO: find the OpNo for this operand;
621     RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo);
622     for (int RegNo = Interval.first; RegNo < Interval.second;
623     ++RegNo) {
624       setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore);
625     }
626 #endif
627   } else {
628     // Match the score to the destination registers.
629     for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
630       auto &Op = Inst.getOperand(I);
631       if (!Op.isReg() || !Op.isDef())
632         continue;
633       RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I);
634       if (T == VM_CNT) {
635         if (Interval.first >= NUM_ALL_VGPRS)
636           continue;
637         if (SIInstrInfo::isVMEM(Inst)) {
638           VmemType V = getVmemType(Inst);
639           for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo)
640             VgprVmemTypes[RegNo] |= 1 << V;
641         }
642       }
643       for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
644         setRegScore(RegNo, T, CurrScore);
645       }
646     }
647     if (TII->isDS(Inst) && Inst.mayStore()) {
648       setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore);
649     }
650   }
651 }
652 
653 void WaitcntBrackets::print(raw_ostream &OS) {
654   OS << '\n';
655   for (auto T : inst_counter_types()) {
656     unsigned LB = getScoreLB(T);
657     unsigned UB = getScoreUB(T);
658 
659     switch (T) {
660     case VM_CNT:
661       OS << "    VM_CNT(" << UB - LB << "): ";
662       break;
663     case LGKM_CNT:
664       OS << "    LGKM_CNT(" << UB - LB << "): ";
665       break;
666     case EXP_CNT:
667       OS << "    EXP_CNT(" << UB - LB << "): ";
668       break;
669     case VS_CNT:
670       OS << "    VS_CNT(" << UB - LB << "): ";
671       break;
672     default:
673       OS << "    UNKNOWN(" << UB - LB << "): ";
674       break;
675     }
676 
677     if (LB < UB) {
678       // Print vgpr scores.
679       for (int J = 0; J <= VgprUB; J++) {
680         unsigned RegScore = getRegScore(J, T);
681         if (RegScore <= LB)
682           continue;
683         unsigned RelScore = RegScore - LB - 1;
684         if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
685           OS << RelScore << ":v" << J << " ";
686         } else {
687           OS << RelScore << ":ds ";
688         }
689       }
690       // Also need to print sgpr scores for lgkm_cnt.
691       if (T == LGKM_CNT) {
692         for (int J = 0; J <= SgprUB; J++) {
693           unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
694           if (RegScore <= LB)
695             continue;
696           unsigned RelScore = RegScore - LB - 1;
697           OS << RelScore << ":s" << J << " ";
698         }
699       }
700     }
701     OS << '\n';
702   }
703   OS << '\n';
704 }
705 
706 /// Simplify the waitcnt, in the sense of removing redundant counts, and return
707 /// whether a waitcnt instruction is needed at all.
708 void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
709   simplifyWaitcnt(VM_CNT, Wait.VmCnt);
710   simplifyWaitcnt(EXP_CNT, Wait.ExpCnt);
711   simplifyWaitcnt(LGKM_CNT, Wait.LgkmCnt);
712   simplifyWaitcnt(VS_CNT, Wait.VsCnt);
713 }
714 
715 void WaitcntBrackets::simplifyWaitcnt(InstCounterType T,
716                                       unsigned &Count) const {
717   const unsigned LB = getScoreLB(T);
718   const unsigned UB = getScoreUB(T);
719 
720   // The number of outstanding events for this type, T, can be calculated
721   // as (UB - LB). If the current Count is greater than or equal to the number
722   // of outstanding events, then the wait for this counter is redundant.
723   if (Count >= UB - LB)
724     Count = ~0u;
725 }
726 
727 void WaitcntBrackets::determineWait(InstCounterType T, unsigned ScoreToWait,
728                                     AMDGPU::Waitcnt &Wait) const {
729   // If the score of src_operand falls within the bracket, we need an
730   // s_waitcnt instruction.
731   const unsigned LB = getScoreLB(T);
732   const unsigned UB = getScoreUB(T);
733   if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
734     if ((T == VM_CNT || T == LGKM_CNT) &&
735         hasPendingFlat() &&
736         !ST->hasFlatLgkmVMemCountInOrder()) {
737       // If there is a pending FLAT operation, and this is a VMem or LGKM
738       // waitcnt and the target can report early completion, then we need
739       // to force a waitcnt 0.
740       addWait(Wait, T, 0);
741     } else if (counterOutOfOrder(T)) {
742       // Counter can get decremented out-of-order when there
743       // are multiple types event in the bracket. Also emit an s_wait counter
744       // with a conservative value of 0 for the counter.
745       addWait(Wait, T, 0);
746     } else {
747       // If a counter has been maxed out avoid overflow by waiting for
748       // MAX(CounterType) - 1 instead.
749       unsigned NeededWait = std::min(UB - ScoreToWait, getWaitCountMax(T) - 1);
750       addWait(Wait, T, NeededWait);
751     }
752   }
753 }
754 
755 void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) {
756   applyWaitcnt(VM_CNT, Wait.VmCnt);
757   applyWaitcnt(EXP_CNT, Wait.ExpCnt);
758   applyWaitcnt(LGKM_CNT, Wait.LgkmCnt);
759   applyWaitcnt(VS_CNT, Wait.VsCnt);
760 }
761 
762 void WaitcntBrackets::applyWaitcnt(InstCounterType T, unsigned Count) {
763   const unsigned UB = getScoreUB(T);
764   if (Count >= UB)
765     return;
766   if (Count != 0) {
767     if (counterOutOfOrder(T))
768       return;
769     setScoreLB(T, std::max(getScoreLB(T), UB - Count));
770   } else {
771     setScoreLB(T, UB);
772     PendingEvents &= ~WaitEventMaskForInst[T];
773   }
774 }
775 
776 // Where there are multiple types of event in the bracket of a counter,
777 // the decrement may go out of order.
778 bool WaitcntBrackets::counterOutOfOrder(InstCounterType T) const {
779   // Scalar memory read always can go out of order.
780   if (T == LGKM_CNT && hasPendingEvent(SMEM_ACCESS))
781     return true;
782   return hasMixedPendingEvents(T);
783 }
784 
785 INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
786                       false)
787 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
788 INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
789                     false)
790 
791 char SIInsertWaitcnts::ID = 0;
792 
793 char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID;
794 
795 FunctionPass *llvm::createSIInsertWaitcntsPass() {
796   return new SIInsertWaitcnts();
797 }
798 
799 /// Combine consecutive waitcnt instructions that precede \p MI and follow
800 /// \p OldWaitcntInstr and apply any extra wait from waitcnt that were added
801 /// by previous passes. Currently this pass conservatively assumes that these
802 /// preexisting waitcnt are required for correctness.
803 bool SIInsertWaitcnts::applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
804                                                MachineInstr &OldWaitcntInstr,
805                                                AMDGPU::Waitcnt &Wait,
806                                                const MachineInstr *MI) {
807   bool Modified = false;
808   MachineInstr *WaitcntInstr = nullptr;
809   MachineInstr *WaitcntVsCntInstr = nullptr;
810   for (auto II = OldWaitcntInstr.getIterator(), NextI = std::next(II);
811        &*II != MI; II = NextI, ++NextI) {
812     if (II->isMetaInstruction())
813       continue;
814 
815     if (II->getOpcode() == AMDGPU::S_WAITCNT) {
816       // Conservatively update required wait if this waitcnt was added in an
817       // earlier pass. In this case it will not exist in the tracked waitcnt
818       // set.
819       if (!TrackedWaitcntSet.count(&*II)) {
820         unsigned IEnc = II->getOperand(0).getImm();
821         AMDGPU::Waitcnt OldWait = AMDGPU::decodeWaitcnt(IV, IEnc);
822         Wait = Wait.combined(OldWait);
823       }
824 
825       // Merge consecutive waitcnt of the same type by erasing multiples.
826       if (!WaitcntInstr) {
827         WaitcntInstr = &*II;
828       } else {
829         II->eraseFromParent();
830         Modified = true;
831       }
832 
833     } else {
834       assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT);
835       assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
836       if (!TrackedWaitcntSet.count(&*II)) {
837         unsigned OldVSCnt =
838             TII->getNamedOperand(*II, AMDGPU::OpName::simm16)->getImm();
839         Wait.VsCnt = std::min(Wait.VsCnt, OldVSCnt);
840       }
841 
842       if (!WaitcntVsCntInstr) {
843         WaitcntVsCntInstr = &*II;
844       } else {
845         II->eraseFromParent();
846         Modified = true;
847       }
848     }
849   }
850 
851   // Updated encoding of merged waitcnt with the required wait.
852   if (WaitcntInstr) {
853     if (Wait.hasWaitExceptVsCnt()) {
854       unsigned NewEnc = AMDGPU::encodeWaitcnt(IV, Wait);
855       unsigned OldEnc = WaitcntInstr->getOperand(0).getImm();
856       if (OldEnc != NewEnc) {
857         WaitcntInstr->getOperand(0).setImm(NewEnc);
858         Modified = true;
859       }
860       ScoreBrackets.applyWaitcnt(Wait);
861       Wait.VmCnt = ~0u;
862       Wait.LgkmCnt = ~0u;
863       Wait.ExpCnt = ~0u;
864 
865       LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
866                         << "Old Instr: " << *MI << "New Instr: " << *WaitcntInstr
867                         << '\n');
868     } else {
869       WaitcntInstr->eraseFromParent();
870       Modified = true;
871     }
872   }
873 
874   if (WaitcntVsCntInstr) {
875     if (Wait.hasWaitVsCnt()) {
876       assert(ST->hasVscnt());
877       unsigned OldVSCnt =
878           TII->getNamedOperand(*WaitcntVsCntInstr, AMDGPU::OpName::simm16)
879               ->getImm();
880       if (Wait.VsCnt != OldVSCnt) {
881         TII->getNamedOperand(*WaitcntVsCntInstr, AMDGPU::OpName::simm16)
882             ->setImm(Wait.VsCnt);
883         Modified = true;
884       }
885       ScoreBrackets.applyWaitcnt(Wait);
886       Wait.VsCnt = ~0u;
887 
888       LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
889                         << "Old Instr: " << *MI
890                         << "New Instr: " << *WaitcntVsCntInstr << '\n');
891     } else {
892       WaitcntVsCntInstr->eraseFromParent();
893       Modified = true;
894     }
895   }
896 
897   return Modified;
898 }
899 
900 static bool readsVCCZ(const MachineInstr &MI) {
901   unsigned Opc = MI.getOpcode();
902   return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
903          !MI.getOperand(1).isUndef();
904 }
905 
906 /// \returns true if the callee inserts an s_waitcnt 0 on function entry.
907 static bool callWaitsOnFunctionEntry(const MachineInstr &MI) {
908   // Currently all conventions wait, but this may not always be the case.
909   //
910   // TODO: If IPRA is enabled, and the callee is isSafeForNoCSROpt, it may make
911   // senses to omit the wait and do it in the caller.
912   return true;
913 }
914 
915 /// \returns true if the callee is expected to wait for any outstanding waits
916 /// before returning.
917 static bool callWaitsOnFunctionReturn(const MachineInstr &MI) {
918   return true;
919 }
920 
921 ///  Generate s_waitcnt instruction to be placed before cur_Inst.
922 ///  Instructions of a given type are returned in order,
923 ///  but instructions of different types can complete out of order.
924 ///  We rely on this in-order completion
925 ///  and simply assign a score to the memory access instructions.
926 ///  We keep track of the active "score bracket" to determine
927 ///  if an access of a memory read requires an s_waitcnt
928 ///  and if so what the value of each counter is.
929 ///  The "score bracket" is bound by the lower bound and upper bound
930 ///  scores (*_score_LB and *_score_ub respectively).
931 bool SIInsertWaitcnts::generateWaitcntInstBefore(
932     MachineInstr &MI, WaitcntBrackets &ScoreBrackets,
933     MachineInstr *OldWaitcntInstr) {
934   setForceEmitWaitcnt();
935 
936   if (MI.isMetaInstruction())
937     return false;
938 
939   AMDGPU::Waitcnt Wait;
940   bool Modified = false;
941 
942   // FIXME: This should have already been handled by the memory legalizer.
943   // Removing this currently doesn't affect any lit tests, but we need to
944   // verify that nothing was relying on this. The number of buffer invalidates
945   // being handled here should not be expanded.
946   if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
947       MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
948       MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL ||
949       MI.getOpcode() == AMDGPU::BUFFER_GL0_INV ||
950       MI.getOpcode() == AMDGPU::BUFFER_GL1_INV) {
951     Wait.VmCnt = 0;
952   }
953 
954   // All waits must be resolved at call return.
955   // NOTE: this could be improved with knowledge of all call sites or
956   //   with knowledge of the called routines.
957   if (MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
958       MI.getOpcode() == AMDGPU::S_SETPC_B64_return ||
959       MI.getOpcode() == AMDGPU::S_SETPC_B64_return_gfx ||
960       (MI.isReturn() && MI.isCall() && !callWaitsOnFunctionEntry(MI))) {
961     Wait = Wait.combined(AMDGPU::Waitcnt::allZero(ST->hasVscnt()));
962   }
963   // Resolve vm waits before gs-done.
964   else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
965             MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
966            ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) ==
967             AMDGPU::SendMsg::ID_GS_DONE)) {
968     Wait.VmCnt = 0;
969   }
970 #if 0 // TODO: the following blocks of logic when we have fence.
971   else if (MI.getOpcode() == SC_FENCE) {
972     const unsigned int group_size =
973       context->shader_info->GetMaxThreadGroupSize();
974     // group_size == 0 means thread group size is unknown at compile time
975     const bool group_is_multi_wave =
976       (group_size == 0 || group_size > target_info->GetWaveFrontSize());
977     const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
978 
979     for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
980       SCRegType src_type = Inst->GetSrcType(i);
981       switch (src_type) {
982         case SCMEM_LDS:
983           if (group_is_multi_wave ||
984             context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
985             EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
986                                ScoreBrackets->getScoreUB(LGKM_CNT));
987             // LDS may have to wait for VM_CNT after buffer load to LDS
988             if (target_info->HasBufferLoadToLDS()) {
989               EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
990                                  ScoreBrackets->getScoreUB(VM_CNT));
991             }
992           }
993           break;
994 
995         case SCMEM_GDS:
996           if (group_is_multi_wave || fence_is_global) {
997             EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
998               ScoreBrackets->getScoreUB(EXP_CNT));
999             EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
1000               ScoreBrackets->getScoreUB(LGKM_CNT));
1001           }
1002           break;
1003 
1004         case SCMEM_UAV:
1005         case SCMEM_TFBUF:
1006         case SCMEM_RING:
1007         case SCMEM_SCATTER:
1008           if (group_is_multi_wave || fence_is_global) {
1009             EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
1010               ScoreBrackets->getScoreUB(EXP_CNT));
1011             EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
1012               ScoreBrackets->getScoreUB(VM_CNT));
1013           }
1014           break;
1015 
1016         case SCMEM_SCRATCH:
1017         default:
1018           break;
1019       }
1020     }
1021   }
1022 #endif
1023 
1024   // Export & GDS instructions do not read the EXEC mask until after the export
1025   // is granted (which can occur well after the instruction is issued).
1026   // The shader program must flush all EXP operations on the export-count
1027   // before overwriting the EXEC mask.
1028   else {
1029     if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
1030       // Export and GDS are tracked individually, either may trigger a waitcnt
1031       // for EXEC.
1032       if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1033           ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1034           ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1035           ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1036         Wait.ExpCnt = 0;
1037       }
1038     }
1039 
1040     if (MI.isCall() && callWaitsOnFunctionEntry(MI)) {
1041       // The function is going to insert a wait on everything in its prolog.
1042       // This still needs to be careful if the call target is a load (e.g. a GOT
1043       // load). We also need to check WAW depenancy with saved PC.
1044       Wait = AMDGPU::Waitcnt();
1045 
1046       int CallAddrOpIdx =
1047           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
1048 
1049       if (MI.getOperand(CallAddrOpIdx).isReg()) {
1050         RegInterval CallAddrOpInterval =
1051           ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, CallAddrOpIdx);
1052 
1053         for (int RegNo = CallAddrOpInterval.first;
1054              RegNo < CallAddrOpInterval.second; ++RegNo)
1055           ScoreBrackets.determineWait(
1056             LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1057 
1058         int RtnAddrOpIdx =
1059           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::dst);
1060         if (RtnAddrOpIdx != -1) {
1061           RegInterval RtnAddrOpInterval =
1062             ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, RtnAddrOpIdx);
1063 
1064           for (int RegNo = RtnAddrOpInterval.first;
1065                RegNo < RtnAddrOpInterval.second; ++RegNo)
1066             ScoreBrackets.determineWait(
1067               LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1068         }
1069       }
1070     } else {
1071       // FIXME: Should not be relying on memoperands.
1072       // Look at the source operands of every instruction to see if
1073       // any of them results from a previous memory operation that affects
1074       // its current usage. If so, an s_waitcnt instruction needs to be
1075       // emitted.
1076       // If the source operand was defined by a load, add the s_waitcnt
1077       // instruction.
1078       //
1079       // Two cases are handled for destination operands:
1080       // 1) If the destination operand was defined by a load, add the s_waitcnt
1081       // instruction to guarantee the right WAW order.
1082       // 2) If a destination operand that was used by a recent export/store ins,
1083       // add s_waitcnt on exp_cnt to guarantee the WAR order.
1084       for (const MachineMemOperand *Memop : MI.memoperands()) {
1085         const Value *Ptr = Memop->getValue();
1086         if (Memop->isStore() && SLoadAddresses.count(Ptr)) {
1087           addWait(Wait, LGKM_CNT, 0);
1088           if (PDT->dominates(MI.getParent(), SLoadAddresses.find(Ptr)->second))
1089             SLoadAddresses.erase(Ptr);
1090         }
1091         unsigned AS = Memop->getAddrSpace();
1092         if (AS != AMDGPUAS::LOCAL_ADDRESS)
1093           continue;
1094         unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
1095         // VM_CNT is only relevant to vgpr or LDS.
1096         ScoreBrackets.determineWait(
1097             VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1098         if (Memop->isStore()) {
1099           ScoreBrackets.determineWait(
1100               EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
1101         }
1102       }
1103 
1104       // Loop over use and def operands.
1105       for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1106         MachineOperand &Op = MI.getOperand(I);
1107         if (!Op.isReg())
1108           continue;
1109         RegInterval Interval =
1110             ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, I);
1111 
1112         const bool IsVGPR = TRI->isVectorRegister(*MRI, Op.getReg());
1113         for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1114           if (IsVGPR) {
1115             // RAW always needs an s_waitcnt. WAW needs an s_waitcnt unless the
1116             // previous write and this write are the same type of VMEM
1117             // instruction, in which case they're guaranteed to write their
1118             // results in order anyway.
1119             if (Op.isUse() || !SIInstrInfo::isVMEM(MI) ||
1120                 ScoreBrackets.hasOtherPendingVmemTypes(RegNo,
1121                                                        getVmemType(MI))) {
1122               ScoreBrackets.determineWait(
1123                   VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1124               ScoreBrackets.clearVgprVmemTypes(RegNo);
1125             }
1126             if (Op.isDef()) {
1127               ScoreBrackets.determineWait(
1128                   EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
1129             }
1130           }
1131           ScoreBrackets.determineWait(
1132               LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1133         }
1134       }
1135     }
1136   }
1137 
1138   // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1139   // occurs before the instruction. Doing it here prevents any additional
1140   // S_WAITCNTs from being emitted if the instruction was marked as
1141   // requiring a WAITCNT beforehand.
1142   if (MI.getOpcode() == AMDGPU::S_BARRIER &&
1143       !ST->hasAutoWaitcntBeforeBarrier()) {
1144     Wait = Wait.combined(AMDGPU::Waitcnt::allZero(ST->hasVscnt()));
1145   }
1146 
1147   // TODO: Remove this work-around, enable the assert for Bug 457939
1148   //       after fixing the scheduler. Also, the Shader Compiler code is
1149   //       independent of target.
1150   if (readsVCCZ(MI) && ST->hasReadVCCZBug()) {
1151     if (ScoreBrackets.getScoreLB(LGKM_CNT) <
1152             ScoreBrackets.getScoreUB(LGKM_CNT) &&
1153         ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
1154       Wait.LgkmCnt = 0;
1155     }
1156   }
1157 
1158   // Verify that the wait is actually needed.
1159   ScoreBrackets.simplifyWaitcnt(Wait);
1160 
1161   if (ForceEmitZeroWaitcnts)
1162     Wait = AMDGPU::Waitcnt::allZero(ST->hasVscnt());
1163 
1164   if (ForceEmitWaitcnt[VM_CNT])
1165     Wait.VmCnt = 0;
1166   if (ForceEmitWaitcnt[EXP_CNT])
1167     Wait.ExpCnt = 0;
1168   if (ForceEmitWaitcnt[LGKM_CNT])
1169     Wait.LgkmCnt = 0;
1170   if (ForceEmitWaitcnt[VS_CNT])
1171     Wait.VsCnt = 0;
1172 
1173   if (OldWaitcntInstr) {
1174     // Try to merge the required wait with preexisting waitcnt instructions.
1175     // Also erase redundant waitcnt.
1176     Modified =
1177         applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr, Wait, &MI);
1178   } else {
1179     // Update waitcnt brackets after determining the required wait.
1180     ScoreBrackets.applyWaitcnt(Wait);
1181   }
1182 
1183   // Build new waitcnt instructions unless no wait is needed or the old waitcnt
1184   // instruction was modified to handle the required wait.
1185   if (Wait.hasWaitExceptVsCnt()) {
1186     unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
1187     auto SWaitInst = BuildMI(*MI.getParent(), MI.getIterator(),
1188                              MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1189                          .addImm(Enc);
1190     TrackedWaitcntSet.insert(SWaitInst);
1191     Modified = true;
1192 
1193     LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
1194                       << "Old Instr: " << MI
1195                       << "New Instr: " << *SWaitInst << '\n');
1196   }
1197 
1198   if (Wait.hasWaitVsCnt()) {
1199     assert(ST->hasVscnt());
1200 
1201     auto SWaitInst =
1202         BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
1203                 TII->get(AMDGPU::S_WAITCNT_VSCNT))
1204             .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1205             .addImm(Wait.VsCnt);
1206     TrackedWaitcntSet.insert(SWaitInst);
1207     Modified = true;
1208 
1209     LLVM_DEBUG(dbgs() << "generateWaitcntInstBefore\n"
1210                       << "Old Instr: " << MI
1211                       << "New Instr: " << *SWaitInst << '\n');
1212   }
1213 
1214   return Modified;
1215 }
1216 
1217 // This is a flat memory operation. Check to see if it has memory tokens other
1218 // than LDS. Other address spaces supported by flat memory operations involve
1219 // global memory.
1220 bool SIInsertWaitcnts::mayAccessVMEMThroughFlat(const MachineInstr &MI) const {
1221   assert(TII->isFLAT(MI));
1222 
1223   // All flat instructions use the VMEM counter.
1224   assert(TII->usesVM_CNT(MI));
1225 
1226   // If there are no memory operands then conservatively assume the flat
1227   // operation may access VMEM.
1228   if (MI.memoperands_empty())
1229     return true;
1230 
1231   // See if any memory operand specifies an address space that involves VMEM.
1232   // Flat operations only supported FLAT, LOCAL (LDS), or address spaces
1233   // involving VMEM such as GLOBAL, CONSTANT, PRIVATE (SCRATCH), etc. The REGION
1234   // (GDS) address space is not supported by flat operations. Therefore, simply
1235   // return true unless only the LDS address space is found.
1236   for (const MachineMemOperand *Memop : MI.memoperands()) {
1237     unsigned AS = Memop->getAddrSpace();
1238     assert(AS != AMDGPUAS::REGION_ADDRESS);
1239     if (AS != AMDGPUAS::LOCAL_ADDRESS)
1240       return true;
1241   }
1242 
1243   return false;
1244 }
1245 
1246 // This is a flat memory operation. Check to see if it has memory tokens for
1247 // either LDS or FLAT.
1248 bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
1249   assert(TII->isFLAT(MI));
1250 
1251   // Flat instruction such as SCRATCH and GLOBAL do not use the lgkm counter.
1252   if (!TII->usesLGKM_CNT(MI))
1253     return false;
1254 
1255   // If in tgsplit mode then there can be no use of LDS.
1256   if (ST->isTgSplitEnabled())
1257     return false;
1258 
1259   // If there are no memory operands then conservatively assume the flat
1260   // operation may access LDS.
1261   if (MI.memoperands_empty())
1262     return true;
1263 
1264   // See if any memory operand specifies an address space that involves LDS.
1265   for (const MachineMemOperand *Memop : MI.memoperands()) {
1266     unsigned AS = Memop->getAddrSpace();
1267     if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS)
1268       return true;
1269   }
1270 
1271   return false;
1272 }
1273 
1274 void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
1275                                                WaitcntBrackets *ScoreBrackets) {
1276   // Now look at the instruction opcode. If it is a memory access
1277   // instruction, update the upper-bound of the appropriate counter's
1278   // bracket and the destination operand scores.
1279   // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
1280   if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
1281     if (TII->isAlwaysGDS(Inst.getOpcode()) ||
1282         TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
1283       ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1284       ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1285     } else {
1286       ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1287     }
1288   } else if (TII->isFLAT(Inst)) {
1289     assert(Inst.mayLoadOrStore());
1290 
1291     int FlatASCount = 0;
1292 
1293     if (mayAccessVMEMThroughFlat(Inst)) {
1294       ++FlatASCount;
1295       if (!ST->hasVscnt())
1296         ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1297       else if (Inst.mayLoad() && !SIInstrInfo::isAtomicNoRet(Inst))
1298         ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1299       else
1300         ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1301     }
1302 
1303     if (mayAccessLDSThroughFlat(Inst)) {
1304       ++FlatASCount;
1305       ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1306     }
1307 
1308     // A Flat memory operation must access at least one address space.
1309     assert(FlatASCount);
1310 
1311     // This is a flat memory operation that access both VMEM and LDS, so note it
1312     // - it will require that both the VM and LGKM be flushed to zero if it is
1313     // pending when a VM or LGKM dependency occurs.
1314     if (FlatASCount > 1)
1315       ScoreBrackets->setPendingFlat();
1316   } else if (SIInstrInfo::isVMEM(Inst) &&
1317              !llvm::AMDGPU::getMUBUFIsBufferInv(Inst.getOpcode())) {
1318     if (!ST->hasVscnt())
1319       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1320     else if ((Inst.mayLoad() && !SIInstrInfo::isAtomicNoRet(Inst)) ||
1321              /* IMAGE_GET_RESINFO / IMAGE_GET_LOD */
1322              (TII->isMIMG(Inst) && !Inst.mayLoad() && !Inst.mayStore()))
1323       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1324     else if (Inst.mayStore())
1325       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1326 
1327     if (ST->vmemWriteNeedsExpWaitcnt() &&
1328         (Inst.mayStore() || SIInstrInfo::isAtomicRet(Inst))) {
1329       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1330     }
1331   } else if (TII->isSMRD(Inst)) {
1332     ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1333   } else if (Inst.isCall()) {
1334     if (callWaitsOnFunctionReturn(Inst)) {
1335       // Act as a wait on everything
1336       ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt::allZero(ST->hasVscnt()));
1337     } else {
1338       // May need to way wait for anything.
1339       ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
1340     }
1341   } else if (SIInstrInfo::isEXP(Inst)) {
1342     unsigned Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1343     if (Imm >= AMDGPU::Exp::ET_PARAM0 && Imm <= AMDGPU::Exp::ET_PARAM31)
1344       ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1345     else if (Imm >= AMDGPU::Exp::ET_POS0 && Imm <= AMDGPU::Exp::ET_POS_LAST)
1346       ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1347     else
1348       ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1349   } else {
1350     switch (Inst.getOpcode()) {
1351     case AMDGPU::S_SENDMSG:
1352     case AMDGPU::S_SENDMSGHALT:
1353       ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1354       break;
1355     case AMDGPU::S_MEMTIME:
1356     case AMDGPU::S_MEMREALTIME:
1357       ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1358       break;
1359     }
1360   }
1361 }
1362 
1363 bool WaitcntBrackets::mergeScore(const MergeInfo &M, unsigned &Score,
1364                                  unsigned OtherScore) {
1365   unsigned MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
1366   unsigned OtherShifted =
1367       OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
1368   Score = std::max(MyShifted, OtherShifted);
1369   return OtherShifted > MyShifted;
1370 }
1371 
1372 /// Merge the pending events and associater score brackets of \p Other into
1373 /// this brackets status.
1374 ///
1375 /// Returns whether the merge resulted in a change that requires tighter waits
1376 /// (i.e. the merged brackets strictly dominate the original brackets).
1377 bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
1378   bool StrictDom = false;
1379 
1380   VgprUB = std::max(VgprUB, Other.VgprUB);
1381   SgprUB = std::max(SgprUB, Other.SgprUB);
1382 
1383   for (auto T : inst_counter_types()) {
1384     // Merge event flags for this counter
1385     const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[T];
1386     const unsigned OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T];
1387     if (OtherEvents & ~OldEvents)
1388       StrictDom = true;
1389     PendingEvents |= OtherEvents;
1390 
1391     // Merge scores for this counter
1392     const unsigned MyPending = ScoreUBs[T] - ScoreLBs[T];
1393     const unsigned OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
1394     const unsigned NewUB = ScoreLBs[T] + std::max(MyPending, OtherPending);
1395     if (NewUB < ScoreLBs[T])
1396       report_fatal_error("waitcnt score overflow");
1397 
1398     MergeInfo M;
1399     M.OldLB = ScoreLBs[T];
1400     M.OtherLB = Other.ScoreLBs[T];
1401     M.MyShift = NewUB - ScoreUBs[T];
1402     M.OtherShift = NewUB - Other.ScoreUBs[T];
1403 
1404     ScoreUBs[T] = NewUB;
1405 
1406     StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
1407 
1408     bool RegStrictDom = false;
1409     for (int J = 0; J <= VgprUB; J++) {
1410       RegStrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]);
1411     }
1412 
1413     if (T == VM_CNT) {
1414       for (int J = 0; J <= VgprUB; J++) {
1415         unsigned char NewVmemTypes = VgprVmemTypes[J] | Other.VgprVmemTypes[J];
1416         RegStrictDom |= NewVmemTypes != VgprVmemTypes[J];
1417         VgprVmemTypes[J] = NewVmemTypes;
1418       }
1419     }
1420 
1421     if (T == LGKM_CNT) {
1422       for (int J = 0; J <= SgprUB; J++) {
1423         RegStrictDom |= mergeScore(M, SgprScores[J], Other.SgprScores[J]);
1424       }
1425     }
1426 
1427     if (RegStrictDom)
1428       StrictDom = true;
1429   }
1430 
1431   return StrictDom;
1432 }
1433 
1434 // Generate s_waitcnt instructions where needed.
1435 bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1436                                             MachineBasicBlock &Block,
1437                                             WaitcntBrackets &ScoreBrackets) {
1438   bool Modified = false;
1439 
1440   LLVM_DEBUG({
1441     dbgs() << "*** Block" << Block.getNumber() << " ***";
1442     ScoreBrackets.dump();
1443   });
1444 
1445   // Track the correctness of vccz through this basic block. There are two
1446   // reasons why it might be incorrect; see ST->hasReadVCCZBug() and
1447   // ST->partialVCCWritesUpdateVCCZ().
1448   bool VCCZCorrect = true;
1449   if (ST->hasReadVCCZBug()) {
1450     // vccz could be incorrect at a basic block boundary if a predecessor wrote
1451     // to vcc and then issued an smem load.
1452     VCCZCorrect = false;
1453   } else if (!ST->partialVCCWritesUpdateVCCZ()) {
1454     // vccz could be incorrect at a basic block boundary if a predecessor wrote
1455     // to vcc_lo or vcc_hi.
1456     VCCZCorrect = false;
1457   }
1458 
1459   // Walk over the instructions.
1460   MachineInstr *OldWaitcntInstr = nullptr;
1461 
1462   for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(),
1463                                          E = Block.instr_end();
1464        Iter != E;) {
1465     MachineInstr &Inst = *Iter;
1466 
1467     // Track pre-existing waitcnts that were added in earlier iterations or by
1468     // the memory legalizer.
1469     if (Inst.getOpcode() == AMDGPU::S_WAITCNT ||
1470         (Inst.getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1471          Inst.getOperand(0).isReg() &&
1472          Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL)) {
1473       if (!OldWaitcntInstr)
1474         OldWaitcntInstr = &Inst;
1475       ++Iter;
1476       continue;
1477     }
1478 
1479     // Generate an s_waitcnt instruction to be placed before Inst, if needed.
1480     Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr);
1481     OldWaitcntInstr = nullptr;
1482 
1483     // Restore vccz if it's not known to be correct already.
1484     bool RestoreVCCZ = !VCCZCorrect && readsVCCZ(Inst);
1485 
1486     // Don't examine operands unless we need to track vccz correctness.
1487     if (ST->hasReadVCCZBug() || !ST->partialVCCWritesUpdateVCCZ()) {
1488       if (Inst.definesRegister(AMDGPU::VCC_LO) ||
1489           Inst.definesRegister(AMDGPU::VCC_HI)) {
1490         // Up to gfx9, writes to vcc_lo and vcc_hi don't update vccz.
1491         if (!ST->partialVCCWritesUpdateVCCZ())
1492           VCCZCorrect = false;
1493       } else if (Inst.definesRegister(AMDGPU::VCC)) {
1494         // There is a hardware bug on CI/SI where SMRD instruction may corrupt
1495         // vccz bit, so when we detect that an instruction may read from a
1496         // corrupt vccz bit, we need to:
1497         // 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD
1498         //    operations to complete.
1499         // 2. Restore the correct value of vccz by writing the current value
1500         //    of vcc back to vcc.
1501         if (ST->hasReadVCCZBug() &&
1502             ScoreBrackets.getScoreLB(LGKM_CNT) <
1503                 ScoreBrackets.getScoreUB(LGKM_CNT) &&
1504             ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
1505           // Writes to vcc while there's an outstanding smem read may get
1506           // clobbered as soon as any read completes.
1507           VCCZCorrect = false;
1508         } else {
1509           // Writes to vcc will fix any incorrect value in vccz.
1510           VCCZCorrect = true;
1511         }
1512       }
1513     }
1514 
1515     if (TII->isSMRD(Inst)) {
1516       for (const MachineMemOperand *Memop : Inst.memoperands()) {
1517         // No need to handle invariant loads when avoiding WAR conflicts, as
1518         // there cannot be a vector store to the same memory location.
1519         if (!Memop->isInvariant()) {
1520           const Value *Ptr = Memop->getValue();
1521           SLoadAddresses.insert(std::make_pair(Ptr, Inst.getParent()));
1522         }
1523       }
1524       if (ST->hasReadVCCZBug()) {
1525         // This smem read could complete and clobber vccz at any time.
1526         VCCZCorrect = false;
1527       }
1528     }
1529 
1530     updateEventWaitcntAfter(Inst, &ScoreBrackets);
1531 
1532 #if 0 // TODO: implement resource type check controlled by options with ub = LB.
1533     // If this instruction generates a S_SETVSKIP because it is an
1534     // indexed resource, and we are on Tahiti, then it will also force
1535     // an S_WAITCNT vmcnt(0)
1536     if (RequireCheckResourceType(Inst, context)) {
1537       // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1538       ScoreBrackets->setScoreLB(VM_CNT,
1539       ScoreBrackets->getScoreUB(VM_CNT));
1540     }
1541 #endif
1542 
1543     LLVM_DEBUG({
1544       Inst.print(dbgs());
1545       ScoreBrackets.dump();
1546     });
1547 
1548     // TODO: Remove this work-around after fixing the scheduler and enable the
1549     // assert above.
1550     if (RestoreVCCZ) {
1551       // Restore the vccz bit.  Any time a value is written to vcc, the vcc
1552       // bit is updated, so we can restore the bit by reading the value of
1553       // vcc and then writing it back to the register.
1554       BuildMI(Block, Inst, Inst.getDebugLoc(),
1555               TII->get(ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
1556               TRI->getVCC())
1557           .addReg(TRI->getVCC());
1558       VCCZCorrect = true;
1559       Modified = true;
1560     }
1561 
1562     ++Iter;
1563   }
1564 
1565   return Modified;
1566 }
1567 
1568 bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
1569   ST = &MF.getSubtarget<GCNSubtarget>();
1570   TII = ST->getInstrInfo();
1571   TRI = &TII->getRegisterInfo();
1572   MRI = &MF.getRegInfo();
1573   IV = AMDGPU::getIsaVersion(ST->getCPU());
1574   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1575   PDT = &getAnalysis<MachinePostDominatorTree>();
1576 
1577   ForceEmitZeroWaitcnts = ForceEmitZeroFlag;
1578   for (auto T : inst_counter_types())
1579     ForceEmitWaitcnt[T] = false;
1580 
1581   HardwareLimits Limits = {};
1582   Limits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1583   Limits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1584   Limits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
1585   Limits.VscntMax = ST->hasVscnt() ? 63 : 0;
1586 
1587   unsigned NumVGPRsMax = ST->getAddressableNumVGPRs();
1588   unsigned NumSGPRsMax = ST->getAddressableNumSGPRs();
1589   assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1590   assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1591 
1592   RegisterEncoding Encoding = {};
1593   Encoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1594   Encoding.VGPRL = Encoding.VGPR0 + NumVGPRsMax - 1;
1595   Encoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1596   Encoding.SGPRL = Encoding.SGPR0 + NumSGPRsMax - 1;
1597 
1598   TrackedWaitcntSet.clear();
1599   BlockInfos.clear();
1600   bool Modified = false;
1601 
1602   if (!MFI->isEntryFunction()) {
1603     // Wait for any outstanding memory operations that the input registers may
1604     // depend on. We can't track them and it's better to do the wait after the
1605     // costly call sequence.
1606 
1607     // TODO: Could insert earlier and schedule more liberally with operations
1608     // that only use caller preserved registers.
1609     MachineBasicBlock &EntryBB = MF.front();
1610     MachineBasicBlock::iterator I = EntryBB.begin();
1611     for (MachineBasicBlock::iterator E = EntryBB.end();
1612          I != E && (I->isPHI() || I->isMetaInstruction()); ++I)
1613       ;
1614     BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT)).addImm(0);
1615     if (ST->hasVscnt())
1616       BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT_VSCNT))
1617           .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1618           .addImm(0);
1619 
1620     Modified = true;
1621   }
1622 
1623   // Keep iterating over the blocks in reverse post order, inserting and
1624   // updating s_waitcnt where needed, until a fix point is reached.
1625   for (auto *MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
1626     BlockInfos.insert({MBB, BlockInfo(MBB)});
1627 
1628   std::unique_ptr<WaitcntBrackets> Brackets;
1629   bool Repeat;
1630   do {
1631     Repeat = false;
1632 
1633     for (auto BII = BlockInfos.begin(), BIE = BlockInfos.end(); BII != BIE;
1634          ++BII) {
1635       BlockInfo &BI = BII->second;
1636       if (!BI.Dirty)
1637         continue;
1638 
1639       if (BI.Incoming) {
1640         if (!Brackets)
1641           Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
1642         else
1643           *Brackets = *BI.Incoming;
1644       } else {
1645         if (!Brackets)
1646           Brackets = std::make_unique<WaitcntBrackets>(ST, Limits, Encoding);
1647         else
1648           *Brackets = WaitcntBrackets(ST, Limits, Encoding);
1649       }
1650 
1651       Modified |= insertWaitcntInBlock(MF, *BI.MBB, *Brackets);
1652       BI.Dirty = false;
1653 
1654       if (Brackets->hasPending()) {
1655         BlockInfo *MoveBracketsToSucc = nullptr;
1656         for (MachineBasicBlock *Succ : BI.MBB->successors()) {
1657           auto SuccBII = BlockInfos.find(Succ);
1658           BlockInfo &SuccBI = SuccBII->second;
1659           if (!SuccBI.Incoming) {
1660             SuccBI.Dirty = true;
1661             if (SuccBII <= BII)
1662               Repeat = true;
1663             if (!MoveBracketsToSucc) {
1664               MoveBracketsToSucc = &SuccBI;
1665             } else {
1666               SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
1667             }
1668           } else if (SuccBI.Incoming->merge(*Brackets)) {
1669             SuccBI.Dirty = true;
1670             if (SuccBII <= BII)
1671               Repeat = true;
1672           }
1673         }
1674         if (MoveBracketsToSucc)
1675           MoveBracketsToSucc->Incoming = std::move(Brackets);
1676       }
1677     }
1678   } while (Repeat);
1679 
1680   if (ST->hasScalarStores()) {
1681     SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1682     bool HaveScalarStores = false;
1683 
1684     for (MachineBasicBlock &MBB : MF) {
1685       for (MachineInstr &MI : MBB) {
1686         if (!HaveScalarStores && TII->isScalarStore(MI))
1687           HaveScalarStores = true;
1688 
1689         if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
1690             MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1691           EndPgmBlocks.push_back(&MBB);
1692       }
1693     }
1694 
1695     if (HaveScalarStores) {
1696       // If scalar writes are used, the cache must be flushed or else the next
1697       // wave to reuse the same scratch memory can be clobbered.
1698       //
1699       // Insert s_dcache_wb at wave termination points if there were any scalar
1700       // stores, and only if the cache hasn't already been flushed. This could
1701       // be improved by looking across blocks for flushes in postdominating
1702       // blocks from the stores but an explicitly requested flush is probably
1703       // very rare.
1704       for (MachineBasicBlock *MBB : EndPgmBlocks) {
1705         bool SeenDCacheWB = false;
1706 
1707         for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
1708              I != E; ++I) {
1709           if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1710             SeenDCacheWB = true;
1711           else if (TII->isScalarStore(*I))
1712             SeenDCacheWB = false;
1713 
1714           // FIXME: It would be better to insert this before a waitcnt if any.
1715           if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1716                I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1717               !SeenDCacheWB) {
1718             Modified = true;
1719             BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
1720           }
1721         }
1722       }
1723     }
1724   }
1725 
1726   return Modified;
1727 }
1728