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