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