1 //===- SIInsertWaitcnts.cpp - Insert Wait Instructions --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief Insert wait instructions for memory reads and writes.
12 ///
13 /// Memory reads and writes are issued asynchronously, so we need to insert
14 /// S_WAITCNT instructions when we want to access any of their results or
15 /// overwrite any register that's used asynchronously.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "AMDGPU.h"
20 #include "AMDGPUSubtarget.h"
21 #include "SIDefines.h"
22 #include "SIInstrInfo.h"
23 #include "SIMachineFunctionInfo.h"
24 #include "SIRegisterInfo.h"
25 #include "Utils/AMDGPUBaseInfo.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/PostOrderIterator.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineLoopInfo.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineOperand.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/IR/DebugLoc.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstdint>
48 #include <cstring>
49 #include <memory>
50 #include <utility>
51 #include <vector>
52 
53 #define DEBUG_TYPE "si-insert-waitcnts"
54 
55 using namespace llvm;
56 
57 namespace {
58 
59 // Class of object that encapsulates latest instruction counter score
60 // associated with the operand.  Used for determining whether
61 // s_waitcnt instruction needs to be emited.
62 
63 #define CNT_MASK(t) (1u << (t))
64 
65 enum InstCounterType { VM_CNT = 0, LGKM_CNT, EXP_CNT, NUM_INST_CNTS };
66 
67 using RegInterval = std::pair<signed, signed>;
68 
69 struct {
70   int32_t VmcntMax;
71   int32_t ExpcntMax;
72   int32_t LgkmcntMax;
73   int32_t NumVGPRsMax;
74   int32_t NumSGPRsMax;
75 } HardwareLimits;
76 
77 struct {
78   unsigned VGPR0;
79   unsigned VGPRL;
80   unsigned SGPR0;
81   unsigned SGPRL;
82 } RegisterEncoding;
83 
84 enum WaitEventType {
85   VMEM_ACCESS,      // vector-memory read & write
86   LDS_ACCESS,       // lds read & write
87   GDS_ACCESS,       // gds read & write
88   SQ_MESSAGE,       // send message
89   SMEM_ACCESS,      // scalar-memory read & write
90   EXP_GPR_LOCK,     // export holding on its data src
91   GDS_GPR_LOCK,     // GDS holding on its data and addr src
92   EXP_POS_ACCESS,   // write to export position
93   EXP_PARAM_ACCESS, // write to export parameter
94   VMW_GPR_LOCK,     // vector-memory write holding on its data src
95   NUM_WAIT_EVENTS,
96 };
97 
98 // The mapping is:
99 //  0                .. SQ_MAX_PGM_VGPRS-1               real VGPRs
100 //  SQ_MAX_PGM_VGPRS .. NUM_ALL_VGPRS-1                  extra VGPR-like slots
101 //  NUM_ALL_VGPRS    .. NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS-1 real SGPRs
102 // We reserve a fixed number of VGPR slots in the scoring tables for
103 // special tokens like SCMEM_LDS (needed for buffer load to LDS).
104 enum RegisterMapping {
105   SQ_MAX_PGM_VGPRS = 256, // Maximum programmable VGPRs across all targets.
106   SQ_MAX_PGM_SGPRS = 256, // Maximum programmable SGPRs across all targets.
107   NUM_EXTRA_VGPRS = 1,    // A reserved slot for DS.
108   EXTRA_VGPR_LDS = 0,     // This is a placeholder the Shader algorithm uses.
109   NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_EXTRA_VGPRS, // Where SGPR starts.
110 };
111 
112 #define ForAllWaitEventType(w)                                                 \
113   for (enum WaitEventType w = (enum WaitEventType)0;                           \
114        (w) < (enum WaitEventType)NUM_WAIT_EVENTS;                              \
115        (w) = (enum WaitEventType)((w) + 1))
116 
117 // This is a per-basic-block object that maintains current score brackets
118 // of each wait counter, and a per-register scoreboard for each wait counter.
119 // We also maintain the latest score for every event type that can change the
120 // waitcnt in order to know if there are multiple types of events within
121 // the brackets. When multiple types of event happen in the bracket,
122 // wait count may get decreased out of order, therefore we need to put in
123 // "s_waitcnt 0" before use.
124 class BlockWaitcntBrackets {
125 public:
126   BlockWaitcntBrackets() {
127     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
128          T = (enum InstCounterType)(T + 1)) {
129       memset(VgprScores[T], 0, sizeof(VgprScores[T]));
130     }
131   }
132 
133   ~BlockWaitcntBrackets() = default;
134 
135   static int32_t getWaitCountMax(InstCounterType T) {
136     switch (T) {
137     case VM_CNT:
138       return HardwareLimits.VmcntMax;
139     case LGKM_CNT:
140       return HardwareLimits.LgkmcntMax;
141     case EXP_CNT:
142       return HardwareLimits.ExpcntMax;
143     default:
144       break;
145     }
146     return 0;
147   }
148 
149   void setScoreLB(InstCounterType T, int32_t Val) {
150     assert(T < NUM_INST_CNTS);
151     if (T >= NUM_INST_CNTS)
152       return;
153     ScoreLBs[T] = Val;
154   }
155 
156   void setScoreUB(InstCounterType T, int32_t Val) {
157     assert(T < NUM_INST_CNTS);
158     if (T >= NUM_INST_CNTS)
159       return;
160     ScoreUBs[T] = Val;
161     if (T == EXP_CNT) {
162       int32_t UB = (int)(ScoreUBs[T] - getWaitCountMax(EXP_CNT));
163       if (ScoreLBs[T] < UB)
164         ScoreLBs[T] = UB;
165     }
166   }
167 
168   int32_t getScoreLB(InstCounterType T) {
169     assert(T < NUM_INST_CNTS);
170     if (T >= NUM_INST_CNTS)
171       return 0;
172     return ScoreLBs[T];
173   }
174 
175   int32_t getScoreUB(InstCounterType T) {
176     assert(T < NUM_INST_CNTS);
177     if (T >= NUM_INST_CNTS)
178       return 0;
179     return ScoreUBs[T];
180   }
181 
182   // Mapping from event to counter.
183   InstCounterType eventCounter(WaitEventType E) {
184     switch (E) {
185     case VMEM_ACCESS:
186       return VM_CNT;
187     case LDS_ACCESS:
188     case GDS_ACCESS:
189     case SQ_MESSAGE:
190     case SMEM_ACCESS:
191       return LGKM_CNT;
192     case EXP_GPR_LOCK:
193     case GDS_GPR_LOCK:
194     case VMW_GPR_LOCK:
195     case EXP_POS_ACCESS:
196     case EXP_PARAM_ACCESS:
197       return EXP_CNT;
198     default:
199       llvm_unreachable("unhandled event type");
200     }
201     return NUM_INST_CNTS;
202   }
203 
204   void setRegScore(int GprNo, InstCounterType T, int32_t Val) {
205     if (GprNo < NUM_ALL_VGPRS) {
206       if (GprNo > VgprUB) {
207         VgprUB = GprNo;
208       }
209       VgprScores[T][GprNo] = Val;
210     } else {
211       assert(T == LGKM_CNT);
212       if (GprNo - NUM_ALL_VGPRS > SgprUB) {
213         SgprUB = GprNo - NUM_ALL_VGPRS;
214       }
215       SgprScores[GprNo - NUM_ALL_VGPRS] = Val;
216     }
217   }
218 
219   int32_t getRegScore(int GprNo, InstCounterType T) {
220     if (GprNo < NUM_ALL_VGPRS) {
221       return VgprScores[T][GprNo];
222     }
223     return SgprScores[GprNo - NUM_ALL_VGPRS];
224   }
225 
226   void clear() {
227     memset(ScoreLBs, 0, sizeof(ScoreLBs));
228     memset(ScoreUBs, 0, sizeof(ScoreUBs));
229     memset(EventUBs, 0, sizeof(EventUBs));
230     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
231          T = (enum InstCounterType)(T + 1)) {
232       memset(VgprScores[T], 0, sizeof(VgprScores[T]));
233     }
234     memset(SgprScores, 0, sizeof(SgprScores));
235   }
236 
237   RegInterval getRegInterval(const MachineInstr *MI, const SIInstrInfo *TII,
238                              const MachineRegisterInfo *MRI,
239                              const SIRegisterInfo *TRI, unsigned OpNo,
240                              bool Def) const;
241 
242   void setExpScore(const MachineInstr *MI, const SIInstrInfo *TII,
243                    const SIRegisterInfo *TRI, const MachineRegisterInfo *MRI,
244                    unsigned OpNo, int32_t Val);
245 
246   void setWaitAtBeginning() { WaitAtBeginning = true; }
247   void clearWaitAtBeginning() { WaitAtBeginning = false; }
248   bool getWaitAtBeginning() const { return WaitAtBeginning; }
249   void setEventUB(enum WaitEventType W, int32_t Val) { EventUBs[W] = Val; }
250   int32_t getMaxVGPR() const { return VgprUB; }
251   int32_t getMaxSGPR() const { return SgprUB; }
252 
253   int32_t getEventUB(enum WaitEventType W) const {
254     assert(W < NUM_WAIT_EVENTS);
255     return EventUBs[W];
256   }
257 
258   bool counterOutOfOrder(InstCounterType T);
259   unsigned int updateByWait(InstCounterType T, int ScoreToWait);
260   void updateByEvent(const SIInstrInfo *TII, const SIRegisterInfo *TRI,
261                      const MachineRegisterInfo *MRI, WaitEventType E,
262                      MachineInstr &MI);
263 
264   bool hasPendingSMEM() const {
265     return (EventUBs[SMEM_ACCESS] > ScoreLBs[LGKM_CNT] &&
266             EventUBs[SMEM_ACCESS] <= ScoreUBs[LGKM_CNT]);
267   }
268 
269   bool hasPendingFlat() const {
270     return ((LastFlat[LGKM_CNT] > ScoreLBs[LGKM_CNT] &&
271              LastFlat[LGKM_CNT] <= ScoreUBs[LGKM_CNT]) ||
272             (LastFlat[VM_CNT] > ScoreLBs[VM_CNT] &&
273              LastFlat[VM_CNT] <= ScoreUBs[VM_CNT]));
274   }
275 
276   void setPendingFlat() {
277     LastFlat[VM_CNT] = ScoreUBs[VM_CNT];
278     LastFlat[LGKM_CNT] = ScoreUBs[LGKM_CNT];
279   }
280 
281   int pendingFlat(InstCounterType Ct) const { return LastFlat[Ct]; }
282 
283   void setLastFlat(InstCounterType Ct, int Val) { LastFlat[Ct] = Val; }
284 
285   bool getRevisitLoop() const { return RevisitLoop; }
286   void setRevisitLoop(bool RevisitLoopIn) { RevisitLoop = RevisitLoopIn; }
287 
288   void setPostOrder(int32_t PostOrderIn) { PostOrder = PostOrderIn; }
289   int32_t getPostOrder() const { return PostOrder; }
290 
291   void setWaitcnt(MachineInstr *WaitcntIn) { Waitcnt = WaitcntIn; }
292   void clearWaitcnt() { Waitcnt = nullptr; }
293   MachineInstr *getWaitcnt() const { return Waitcnt; }
294 
295   bool mixedExpTypes() const { return MixedExpTypes; }
296   void setMixedExpTypes(bool MixedExpTypesIn) {
297     MixedExpTypes = MixedExpTypesIn;
298   }
299 
300   void print(raw_ostream &);
301   void dump() { print(dbgs()); }
302 
303 private:
304   bool WaitAtBeginning = false;
305   bool RevisitLoop = false;
306   bool MixedExpTypes = false;
307   int32_t PostOrder = 0;
308   MachineInstr *Waitcnt = nullptr;
309   int32_t ScoreLBs[NUM_INST_CNTS] = {0};
310   int32_t ScoreUBs[NUM_INST_CNTS] = {0};
311   int32_t EventUBs[NUM_WAIT_EVENTS] = {0};
312   // Remember the last flat memory operation.
313   int32_t LastFlat[NUM_INST_CNTS] = {0};
314   // wait_cnt scores for every vgpr.
315   // Keep track of the VgprUB and SgprUB to make merge at join efficient.
316   int32_t VgprUB = 0;
317   int32_t SgprUB = 0;
318   int32_t VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS];
319   // Wait cnt scores for every sgpr, only lgkmcnt is relevant.
320   int32_t SgprScores[SQ_MAX_PGM_SGPRS] = {0};
321 };
322 
323 // This is a per-loop-region object that records waitcnt status at the end of
324 // loop footer from the previous iteration. We also maintain an iteration
325 // count to track the number of times the loop has been visited. When it
326 // doesn't converge naturally, we force convergence by inserting s_waitcnt 0
327 // at the end of the loop footer.
328 class LoopWaitcntData {
329 public:
330   LoopWaitcntData() = default;
331   ~LoopWaitcntData() = default;
332 
333   void incIterCnt() { IterCnt++; }
334   void resetIterCnt() { IterCnt = 0; }
335   int32_t getIterCnt() { return IterCnt; }
336 
337   void setWaitcnt(MachineInstr *WaitcntIn) { LfWaitcnt = WaitcntIn; }
338   MachineInstr *getWaitcnt() const { return LfWaitcnt; }
339 
340   void print() {
341     DEBUG(dbgs() << "  iteration " << IterCnt << '\n';);
342   }
343 
344 private:
345   // s_waitcnt added at the end of loop footer to stablize wait scores
346   // at the end of the loop footer.
347   MachineInstr *LfWaitcnt = nullptr;
348   // Number of iterations the loop has been visited, not including the initial
349   // walk over.
350   int32_t IterCnt = 0;
351 };
352 
353 class SIInsertWaitcnts : public MachineFunctionPass {
354 private:
355   const SISubtarget *ST = nullptr;
356   const SIInstrInfo *TII = nullptr;
357   const SIRegisterInfo *TRI = nullptr;
358   const MachineRegisterInfo *MRI = nullptr;
359   const MachineLoopInfo *MLI = nullptr;
360   AMDGPU::IsaInfo::IsaVersion IV;
361   AMDGPUAS AMDGPUASI;
362 
363   DenseSet<MachineBasicBlock *> BlockVisitedSet;
364   DenseSet<MachineInstr *> TrackedWaitcntSet;
365   DenseSet<MachineInstr *> VCCZBugHandledSet;
366 
367   DenseMap<MachineBasicBlock *, std::unique_ptr<BlockWaitcntBrackets>>
368       BlockWaitcntBracketsMap;
369 
370   DenseSet<MachineBasicBlock *> BlockWaitcntProcessedSet;
371 
372   DenseMap<MachineLoop *, std::unique_ptr<LoopWaitcntData>> LoopWaitcntDataMap;
373 
374   std::vector<std::unique_ptr<BlockWaitcntBrackets>> KillWaitBrackets;
375 
376 public:
377   static char ID;
378 
379   SIInsertWaitcnts() : MachineFunctionPass(ID) {}
380 
381   bool runOnMachineFunction(MachineFunction &MF) override;
382 
383   StringRef getPassName() const override {
384     return "SI insert wait instructions";
385   }
386 
387   void getAnalysisUsage(AnalysisUsage &AU) const override {
388     AU.setPreservesCFG();
389     AU.addRequired<MachineLoopInfo>();
390     MachineFunctionPass::getAnalysisUsage(AU);
391   }
392 
393   void addKillWaitBracket(BlockWaitcntBrackets *Bracket) {
394     // The waitcnt information is copied because it changes as the block is
395     // traversed.
396     KillWaitBrackets.push_back(
397         llvm::make_unique<BlockWaitcntBrackets>(*Bracket));
398   }
399 
400   bool mayAccessLDSThroughFlat(const MachineInstr &MI) const;
401   void generateSWaitCntInstBefore(MachineInstr &MI,
402                                   BlockWaitcntBrackets *ScoreBrackets);
403   void updateEventWaitCntAfter(MachineInstr &Inst,
404                                BlockWaitcntBrackets *ScoreBrackets);
405   void mergeInputScoreBrackets(MachineBasicBlock &Block);
406   MachineBasicBlock *loopBottom(const MachineLoop *Loop);
407   void insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block);
408   void insertWaitcntBeforeCF(MachineBasicBlock &Block, MachineInstr *Inst);
409   bool isWaitcntStronger(unsigned LHS, unsigned RHS);
410   unsigned combineWaitcnt(unsigned LHS, unsigned RHS);
411 };
412 
413 } // end anonymous namespace
414 
415 RegInterval BlockWaitcntBrackets::getRegInterval(const MachineInstr *MI,
416                                                  const SIInstrInfo *TII,
417                                                  const MachineRegisterInfo *MRI,
418                                                  const SIRegisterInfo *TRI,
419                                                  unsigned OpNo,
420                                                  bool Def) const {
421   const MachineOperand &Op = MI->getOperand(OpNo);
422   if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()) ||
423       (Def && !Op.isDef()))
424     return {-1, -1};
425 
426   // A use via a PW operand does not need a waitcnt.
427   // A partial write is not a WAW.
428   assert(!Op.getSubReg() || !Op.isUndef());
429 
430   RegInterval Result;
431   const MachineRegisterInfo &MRIA = *MRI;
432 
433   unsigned Reg = TRI->getEncodingValue(Op.getReg());
434 
435   if (TRI->isVGPR(MRIA, Op.getReg())) {
436     assert(Reg >= RegisterEncoding.VGPR0 && Reg <= RegisterEncoding.VGPRL);
437     Result.first = Reg - RegisterEncoding.VGPR0;
438     assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
439   } else if (TRI->isSGPRReg(MRIA, Op.getReg())) {
440     assert(Reg >= RegisterEncoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS);
441     Result.first = Reg - RegisterEncoding.SGPR0 + NUM_ALL_VGPRS;
442     assert(Result.first >= NUM_ALL_VGPRS &&
443            Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS);
444   }
445   // TODO: Handle TTMP
446   // else if (TRI->isTTMP(MRIA, Reg.getReg())) ...
447   else
448     return {-1, -1};
449 
450   const MachineInstr &MIA = *MI;
451   const TargetRegisterClass *RC = TII->getOpRegClass(MIA, OpNo);
452   unsigned Size = TRI->getRegSizeInBits(*RC);
453   Result.second = Result.first + (Size / 32);
454 
455   return Result;
456 }
457 
458 void BlockWaitcntBrackets::setExpScore(const MachineInstr *MI,
459                                        const SIInstrInfo *TII,
460                                        const SIRegisterInfo *TRI,
461                                        const MachineRegisterInfo *MRI,
462                                        unsigned OpNo, int32_t Val) {
463   RegInterval Interval = getRegInterval(MI, TII, MRI, TRI, OpNo, false);
464   DEBUG({
465     const MachineOperand &Opnd = MI->getOperand(OpNo);
466     assert(TRI->isVGPR(*MRI, Opnd.getReg()));
467   });
468   for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
469     setRegScore(RegNo, EXP_CNT, Val);
470   }
471 }
472 
473 void BlockWaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
474                                          const SIRegisterInfo *TRI,
475                                          const MachineRegisterInfo *MRI,
476                                          WaitEventType E, MachineInstr &Inst) {
477   const MachineRegisterInfo &MRIA = *MRI;
478   InstCounterType T = eventCounter(E);
479   int32_t CurrScore = getScoreUB(T) + 1;
480   // EventUB and ScoreUB need to be update regardless if this event changes
481   // the score of a register or not.
482   // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
483   EventUBs[E] = CurrScore;
484   setScoreUB(T, CurrScore);
485 
486   if (T == EXP_CNT) {
487     // Check for mixed export types. If they are mixed, then a waitcnt exp(0)
488     // is required.
489     if (!MixedExpTypes) {
490       MixedExpTypes = counterOutOfOrder(EXP_CNT);
491     }
492 
493     // Put score on the source vgprs. If this is a store, just use those
494     // specific register(s).
495     if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) {
496       // All GDS operations must protect their address register (same as
497       // export.)
498       if (Inst.getOpcode() != AMDGPU::DS_APPEND &&
499           Inst.getOpcode() != AMDGPU::DS_CONSUME) {
500         setExpScore(
501             &Inst, TII, TRI, MRI,
502             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr),
503             CurrScore);
504       }
505       if (Inst.mayStore()) {
506         setExpScore(
507             &Inst, TII, TRI, MRI,
508             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0),
509             CurrScore);
510         if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
511                                        AMDGPU::OpName::data1) != -1) {
512           setExpScore(&Inst, TII, TRI, MRI,
513                       AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
514                                                  AMDGPU::OpName::data1),
515                       CurrScore);
516         }
517       } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1 &&
518                  Inst.getOpcode() != AMDGPU::DS_GWS_INIT &&
519                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V &&
520                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR &&
521                  Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P &&
522                  Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER &&
523                  Inst.getOpcode() != AMDGPU::DS_APPEND &&
524                  Inst.getOpcode() != AMDGPU::DS_CONSUME &&
525                  Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
526         for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
527           const MachineOperand &Op = Inst.getOperand(I);
528           if (Op.isReg() && !Op.isDef() && TRI->isVGPR(MRIA, Op.getReg())) {
529             setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
530           }
531         }
532       }
533     } else if (TII->isFLAT(Inst)) {
534       if (Inst.mayStore()) {
535         setExpScore(
536             &Inst, TII, TRI, MRI,
537             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
538             CurrScore);
539       } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
540         setExpScore(
541             &Inst, TII, TRI, MRI,
542             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
543             CurrScore);
544       }
545     } else if (TII->isMIMG(Inst)) {
546       if (Inst.mayStore()) {
547         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
548       } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
549         setExpScore(
550             &Inst, TII, TRI, MRI,
551             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
552             CurrScore);
553       }
554     } else if (TII->isMTBUF(Inst)) {
555       if (Inst.mayStore()) {
556         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
557       }
558     } else if (TII->isMUBUF(Inst)) {
559       if (Inst.mayStore()) {
560         setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
561       } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
562         setExpScore(
563             &Inst, TII, TRI, MRI,
564             AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
565             CurrScore);
566       }
567     } else {
568       if (TII->isEXP(Inst)) {
569         // For export the destination registers are really temps that
570         // can be used as the actual source after export patching, so
571         // we need to treat them like sources and set the EXP_CNT
572         // score.
573         for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
574           MachineOperand &DefMO = Inst.getOperand(I);
575           if (DefMO.isReg() && DefMO.isDef() &&
576               TRI->isVGPR(MRIA, DefMO.getReg())) {
577             setRegScore(TRI->getEncodingValue(DefMO.getReg()), EXP_CNT,
578                         CurrScore);
579           }
580         }
581       }
582       for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
583         MachineOperand &MO = Inst.getOperand(I);
584         if (MO.isReg() && !MO.isDef() && TRI->isVGPR(MRIA, MO.getReg())) {
585           setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
586         }
587       }
588     }
589 #if 0 // TODO: check if this is handled by MUBUF code above.
590   } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD ||
591        Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 ||
592        Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) {
593     MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data);
594     unsigned OpNo;//TODO: find the OpNo for this operand;
595     RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo, false);
596     for (signed RegNo = Interval.first; RegNo < Interval.second;
597     ++RegNo) {
598       setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore);
599     }
600 #endif
601   } else {
602     // Match the score to the destination registers.
603     for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
604       RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I, true);
605       if (T == VM_CNT && Interval.first >= NUM_ALL_VGPRS)
606         continue;
607       for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
608         setRegScore(RegNo, T, CurrScore);
609       }
610     }
611     if (TII->isDS(Inst) && Inst.mayStore()) {
612       setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore);
613     }
614   }
615 }
616 
617 void BlockWaitcntBrackets::print(raw_ostream &OS) {
618   OS << '\n';
619   for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
620        T = (enum InstCounterType)(T + 1)) {
621     int LB = getScoreLB(T);
622     int UB = getScoreUB(T);
623 
624     switch (T) {
625     case VM_CNT:
626       OS << "    VM_CNT(" << UB - LB << "): ";
627       break;
628     case LGKM_CNT:
629       OS << "    LGKM_CNT(" << UB - LB << "): ";
630       break;
631     case EXP_CNT:
632       OS << "    EXP_CNT(" << UB - LB << "): ";
633       break;
634     default:
635       OS << "    UNKNOWN(" << UB - LB << "): ";
636       break;
637     }
638 
639     if (LB < UB) {
640       // Print vgpr scores.
641       for (int J = 0; J <= getMaxVGPR(); J++) {
642         int RegScore = getRegScore(J, T);
643         if (RegScore <= LB)
644           continue;
645         int RelScore = RegScore - LB - 1;
646         if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
647           OS << RelScore << ":v" << J << " ";
648         } else {
649           OS << RelScore << ":ds ";
650         }
651       }
652       // Also need to print sgpr scores for lgkm_cnt.
653       if (T == LGKM_CNT) {
654         for (int J = 0; J <= getMaxSGPR(); J++) {
655           int RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
656           if (RegScore <= LB)
657             continue;
658           int RelScore = RegScore - LB - 1;
659           OS << RelScore << ":s" << J << " ";
660         }
661       }
662     }
663     OS << '\n';
664   }
665   OS << '\n';
666 }
667 
668 unsigned int BlockWaitcntBrackets::updateByWait(InstCounterType T,
669                                                 int ScoreToWait) {
670   unsigned int NeedWait = 0;
671   if (ScoreToWait == -1) {
672     // The score to wait is unknown. This implies that it was not encountered
673     // during the path of the CFG walk done during the current traversal but
674     // may be seen on a different path. Emit an s_wait counter with a
675     // conservative value of 0 for the counter.
676     NeedWait = CNT_MASK(T);
677     setScoreLB(T, getScoreUB(T));
678     return NeedWait;
679   }
680 
681   // If the score of src_operand falls within the bracket, we need an
682   // s_waitcnt instruction.
683   const int32_t LB = getScoreLB(T);
684   const int32_t UB = getScoreUB(T);
685   if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
686     if (T == VM_CNT && hasPendingFlat()) {
687       // If there is a pending FLAT operation, and this is a VM waitcnt,
688       // then we need to force a waitcnt 0 for VM.
689       NeedWait = CNT_MASK(T);
690       setScoreLB(T, getScoreUB(T));
691     } else if (counterOutOfOrder(T)) {
692       // Counter can get decremented out-of-order when there
693       // are multiple types event in the bracket. Also emit an s_wait counter
694       // with a conservative value of 0 for the counter.
695       NeedWait = CNT_MASK(T);
696       setScoreLB(T, getScoreUB(T));
697     } else {
698       NeedWait = CNT_MASK(T);
699       setScoreLB(T, ScoreToWait);
700     }
701   }
702 
703   return NeedWait;
704 }
705 
706 // Where there are multiple types of event in the bracket of a counter,
707 // the decrement may go out of order.
708 bool BlockWaitcntBrackets::counterOutOfOrder(InstCounterType T) {
709   switch (T) {
710   case VM_CNT:
711     return false;
712   case LGKM_CNT: {
713     if (EventUBs[SMEM_ACCESS] > ScoreLBs[LGKM_CNT] &&
714         EventUBs[SMEM_ACCESS] <= ScoreUBs[LGKM_CNT]) {
715       // Scalar memory read always can go out of order.
716       return true;
717     }
718     int NumEventTypes = 0;
719     if (EventUBs[LDS_ACCESS] > ScoreLBs[LGKM_CNT] &&
720         EventUBs[LDS_ACCESS] <= ScoreUBs[LGKM_CNT]) {
721       NumEventTypes++;
722     }
723     if (EventUBs[GDS_ACCESS] > ScoreLBs[LGKM_CNT] &&
724         EventUBs[GDS_ACCESS] <= ScoreUBs[LGKM_CNT]) {
725       NumEventTypes++;
726     }
727     if (EventUBs[SQ_MESSAGE] > ScoreLBs[LGKM_CNT] &&
728         EventUBs[SQ_MESSAGE] <= ScoreUBs[LGKM_CNT]) {
729       NumEventTypes++;
730     }
731     if (NumEventTypes <= 1) {
732       return false;
733     }
734     break;
735   }
736   case EXP_CNT: {
737     // If there has been a mixture of export types, then a waitcnt exp(0) is
738     // required.
739     if (MixedExpTypes)
740       return true;
741     int NumEventTypes = 0;
742     if (EventUBs[EXP_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
743         EventUBs[EXP_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
744       NumEventTypes++;
745     }
746     if (EventUBs[GDS_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
747         EventUBs[GDS_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
748       NumEventTypes++;
749     }
750     if (EventUBs[VMW_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
751         EventUBs[VMW_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
752       NumEventTypes++;
753     }
754     if (EventUBs[EXP_PARAM_ACCESS] > ScoreLBs[EXP_CNT] &&
755         EventUBs[EXP_PARAM_ACCESS] <= ScoreUBs[EXP_CNT]) {
756       NumEventTypes++;
757     }
758 
759     if (EventUBs[EXP_POS_ACCESS] > ScoreLBs[EXP_CNT] &&
760         EventUBs[EXP_POS_ACCESS] <= ScoreUBs[EXP_CNT]) {
761       NumEventTypes++;
762     }
763 
764     if (NumEventTypes <= 1) {
765       return false;
766     }
767     break;
768   }
769   default:
770     break;
771   }
772   return true;
773 }
774 
775 INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
776                       false)
777 INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
778                     false)
779 
780 char SIInsertWaitcnts::ID = 0;
781 
782 char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID;
783 
784 FunctionPass *llvm::createSIInsertWaitcntsPass() {
785   return new SIInsertWaitcnts();
786 }
787 
788 static bool readsVCCZ(const MachineInstr &MI) {
789   unsigned Opc = MI.getOpcode();
790   return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
791          !MI.getOperand(1).isUndef();
792 }
793 
794 /// \brief Given wait count encodings checks if LHS is stronger than RHS.
795 bool SIInsertWaitcnts::isWaitcntStronger(unsigned LHS, unsigned RHS) {
796   if (AMDGPU::decodeVmcnt(IV, LHS) > AMDGPU::decodeVmcnt(IV, RHS))
797     return false;
798   if (AMDGPU::decodeLgkmcnt(IV, LHS) > AMDGPU::decodeLgkmcnt(IV, RHS))
799     return false;
800   if (AMDGPU::decodeExpcnt(IV, LHS) > AMDGPU::decodeExpcnt(IV, RHS))
801     return false;
802   return true;
803 }
804 
805 /// \brief Given wait count encodings create a new encoding which is stronger
806 /// or equal to both.
807 unsigned SIInsertWaitcnts::combineWaitcnt(unsigned LHS, unsigned RHS) {
808   unsigned VmCnt = std::min(AMDGPU::decodeVmcnt(IV, LHS),
809                             AMDGPU::decodeVmcnt(IV, RHS));
810   unsigned LgkmCnt = std::min(AMDGPU::decodeLgkmcnt(IV, LHS),
811                               AMDGPU::decodeLgkmcnt(IV, RHS));
812   unsigned ExpCnt = std::min(AMDGPU::decodeExpcnt(IV, LHS),
813                              AMDGPU::decodeExpcnt(IV, RHS));
814   return AMDGPU::encodeWaitcnt(IV, VmCnt, ExpCnt, LgkmCnt);
815 }
816 
817 ///  \brief Generate s_waitcnt instruction to be placed before cur_Inst.
818 ///  Instructions of a given type are returned in order,
819 ///  but instructions of different types can complete out of order.
820 ///  We rely on this in-order completion
821 ///  and simply assign a score to the memory access instructions.
822 ///  We keep track of the active "score bracket" to determine
823 ///  if an access of a memory read requires an s_waitcnt
824 ///  and if so what the value of each counter is.
825 ///  The "score bracket" is bound by the lower bound and upper bound
826 ///  scores (*_score_LB and *_score_ub respectively).
827 void SIInsertWaitcnts::generateSWaitCntInstBefore(
828     MachineInstr &MI, BlockWaitcntBrackets *ScoreBrackets) {
829   // To emit, or not to emit - that's the question!
830   // Start with an assumption that there is no need to emit.
831   unsigned int EmitSwaitcnt = 0;
832   // No need to wait before phi. If a phi-move exists, then the wait should
833   // has been inserted before the move. If a phi-move does not exist, then
834   // wait should be inserted before the real use. The same is true for
835   // sc-merge. It is not a coincident that all these cases correspond to the
836   // instructions that are skipped in the assembling loop.
837   bool NeedLineMapping = false; // TODO: Check on this.
838   if (MI.isDebugValue() &&
839       // TODO: any other opcode?
840       !NeedLineMapping) {
841     return;
842   }
843 
844   // See if an s_waitcnt is forced at block entry, or is needed at
845   // program end.
846   if (ScoreBrackets->getWaitAtBeginning()) {
847     // Note that we have already cleared the state, so we don't need to update
848     // it.
849     ScoreBrackets->clearWaitAtBeginning();
850     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
851          T = (enum InstCounterType)(T + 1)) {
852       EmitSwaitcnt |= CNT_MASK(T);
853       ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
854     }
855   }
856 
857   // See if this instruction has a forced S_WAITCNT VM.
858   // TODO: Handle other cases of NeedsWaitcntVmBefore()
859   else if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
860            MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
861            MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL) {
862     EmitSwaitcnt |=
863         ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
864   }
865 
866   // All waits must be resolved at call return.
867   // NOTE: this could be improved with knowledge of all call sites or
868   //   with knowledge of the called routines.
869   if (MI.getOpcode() == AMDGPU::RETURN ||
870       MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
871       MI.getOpcode() == AMDGPU::S_SETPC_B64_return) {
872     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
873          T = (enum InstCounterType)(T + 1)) {
874       if (ScoreBrackets->getScoreUB(T) > ScoreBrackets->getScoreLB(T)) {
875         ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
876         EmitSwaitcnt |= CNT_MASK(T);
877       }
878     }
879   }
880   // Resolve vm waits before gs-done.
881   else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
882             MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
883            ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) ==
884             AMDGPU::SendMsg::ID_GS_DONE)) {
885     if (ScoreBrackets->getScoreUB(VM_CNT) > ScoreBrackets->getScoreLB(VM_CNT)) {
886       ScoreBrackets->setScoreLB(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
887       EmitSwaitcnt |= CNT_MASK(VM_CNT);
888     }
889   }
890 #if 0 // TODO: the following blocks of logic when we have fence.
891   else if (MI.getOpcode() == SC_FENCE) {
892     const unsigned int group_size =
893       context->shader_info->GetMaxThreadGroupSize();
894     // group_size == 0 means thread group size is unknown at compile time
895     const bool group_is_multi_wave =
896       (group_size == 0 || group_size > target_info->GetWaveFrontSize());
897     const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
898 
899     for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
900       SCRegType src_type = Inst->GetSrcType(i);
901       switch (src_type) {
902         case SCMEM_LDS:
903           if (group_is_multi_wave ||
904             context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
905             EmitSwaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
906                                ScoreBrackets->getScoreUB(LGKM_CNT));
907             // LDS may have to wait for VM_CNT after buffer load to LDS
908             if (target_info->HasBufferLoadToLDS()) {
909               EmitSwaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
910                                  ScoreBrackets->getScoreUB(VM_CNT));
911             }
912           }
913           break;
914 
915         case SCMEM_GDS:
916           if (group_is_multi_wave || fence_is_global) {
917             EmitSwaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
918               ScoreBrackets->getScoreUB(EXP_CNT));
919             EmitSwaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
920               ScoreBrackets->getScoreUB(LGKM_CNT));
921           }
922           break;
923 
924         case SCMEM_UAV:
925         case SCMEM_TFBUF:
926         case SCMEM_RING:
927         case SCMEM_SCATTER:
928           if (group_is_multi_wave || fence_is_global) {
929             EmitSwaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
930               ScoreBrackets->getScoreUB(EXP_CNT));
931             EmitSwaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
932               ScoreBrackets->getScoreUB(VM_CNT));
933           }
934           break;
935 
936         case SCMEM_SCRATCH:
937         default:
938           break;
939       }
940     }
941   }
942 #endif
943 
944   // Export & GDS instructions do not read the EXEC mask until after the export
945   // is granted (which can occur well after the instruction is issued).
946   // The shader program must flush all EXP operations on the export-count
947   // before overwriting the EXEC mask.
948   else {
949     if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
950       // Export and GDS are tracked individually, either may trigger a waitcnt
951       // for EXEC.
952       EmitSwaitcnt |= ScoreBrackets->updateByWait(
953           EXP_CNT, ScoreBrackets->getEventUB(EXP_GPR_LOCK));
954       EmitSwaitcnt |= ScoreBrackets->updateByWait(
955           EXP_CNT, ScoreBrackets->getEventUB(EXP_PARAM_ACCESS));
956       EmitSwaitcnt |= ScoreBrackets->updateByWait(
957           EXP_CNT, ScoreBrackets->getEventUB(EXP_POS_ACCESS));
958       EmitSwaitcnt |= ScoreBrackets->updateByWait(
959           EXP_CNT, ScoreBrackets->getEventUB(GDS_GPR_LOCK));
960     }
961 
962 #if 0 // TODO: the following code to handle CALL.
963     // The argument passing for CALLs should suffice for VM_CNT and LGKM_CNT.
964     // However, there is a problem with EXP_CNT, because the call cannot
965     // easily tell if a register is used in the function, and if it did, then
966     // the referring instruction would have to have an S_WAITCNT, which is
967     // dependent on all call sites. So Instead, force S_WAITCNT for EXP_CNTs
968     // before the call.
969     if (MI.getOpcode() == SC_CALL) {
970       if (ScoreBrackets->getScoreUB(EXP_CNT) >
971         ScoreBrackets->getScoreLB(EXP_CNT)) {
972         ScoreBrackets->setScoreLB(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
973         EmitSwaitcnt |= CNT_MASK(EXP_CNT);
974       }
975     }
976 #endif
977 
978     // FIXME: Should not be relying on memoperands.
979     // Look at the source operands of every instruction to see if
980     // any of them results from a previous memory operation that affects
981     // its current usage. If so, an s_waitcnt instruction needs to be
982     // emitted.
983     // If the source operand was defined by a load, add the s_waitcnt
984     // instruction.
985     for (const MachineMemOperand *Memop : MI.memoperands()) {
986       unsigned AS = Memop->getAddrSpace();
987       if (AS != AMDGPUASI.LOCAL_ADDRESS)
988         continue;
989       unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
990       // VM_CNT is only relevant to vgpr or LDS.
991       EmitSwaitcnt |= ScoreBrackets->updateByWait(
992           VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
993     }
994 
995     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
996       const MachineOperand &Op = MI.getOperand(I);
997       const MachineRegisterInfo &MRIA = *MRI;
998       RegInterval Interval =
999           ScoreBrackets->getRegInterval(&MI, TII, MRI, TRI, I, false);
1000       for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1001         if (TRI->isVGPR(MRIA, Op.getReg())) {
1002           // VM_CNT is only relevant to vgpr or LDS.
1003           EmitSwaitcnt |= ScoreBrackets->updateByWait(
1004               VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1005         }
1006         EmitSwaitcnt |= ScoreBrackets->updateByWait(
1007             LGKM_CNT, ScoreBrackets->getRegScore(RegNo, LGKM_CNT));
1008       }
1009     }
1010     // End of for loop that looks at all source operands to decide vm_wait_cnt
1011     // and lgk_wait_cnt.
1012 
1013     // Two cases are handled for destination operands:
1014     // 1) If the destination operand was defined by a load, add the s_waitcnt
1015     // instruction to guarantee the right WAW order.
1016     // 2) If a destination operand that was used by a recent export/store ins,
1017     // add s_waitcnt on exp_cnt to guarantee the WAR order.
1018     if (MI.mayStore()) {
1019       // FIXME: Should not be relying on memoperands.
1020       for (const MachineMemOperand *Memop : MI.memoperands()) {
1021         unsigned AS = Memop->getAddrSpace();
1022         if (AS != AMDGPUASI.LOCAL_ADDRESS)
1023           continue;
1024         unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
1025         EmitSwaitcnt |= ScoreBrackets->updateByWait(
1026             VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1027         EmitSwaitcnt |= ScoreBrackets->updateByWait(
1028             EXP_CNT, ScoreBrackets->getRegScore(RegNo, EXP_CNT));
1029       }
1030     }
1031     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1032       MachineOperand &Def = MI.getOperand(I);
1033       const MachineRegisterInfo &MRIA = *MRI;
1034       RegInterval Interval =
1035           ScoreBrackets->getRegInterval(&MI, TII, MRI, TRI, I, true);
1036       for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1037         if (TRI->isVGPR(MRIA, Def.getReg())) {
1038           EmitSwaitcnt |= ScoreBrackets->updateByWait(
1039               VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1040           EmitSwaitcnt |= ScoreBrackets->updateByWait(
1041               EXP_CNT, ScoreBrackets->getRegScore(RegNo, EXP_CNT));
1042         }
1043         EmitSwaitcnt |= ScoreBrackets->updateByWait(
1044             LGKM_CNT, ScoreBrackets->getRegScore(RegNo, LGKM_CNT));
1045       }
1046     } // End of for loop that looks at all dest operands.
1047   }
1048 
1049   // TODO: Tie force zero to a compiler triage option.
1050   bool ForceZero = false;
1051 
1052   // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1053   // occurs before the instruction. Doing it here prevents any additional
1054   // S_WAITCNTs from being emitted if the instruction was marked as
1055   // requiring a WAITCNT beforehand.
1056   if (MI.getOpcode() == AMDGPU::S_BARRIER &&
1057       !ST->hasAutoWaitcntBeforeBarrier()) {
1058     EmitSwaitcnt |=
1059         ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
1060     EmitSwaitcnt |= ScoreBrackets->updateByWait(
1061         EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
1062     EmitSwaitcnt |= ScoreBrackets->updateByWait(
1063         LGKM_CNT, ScoreBrackets->getScoreUB(LGKM_CNT));
1064   }
1065 
1066   // TODO: Remove this work-around, enable the assert for Bug 457939
1067   //       after fixing the scheduler. Also, the Shader Compiler code is
1068   //       independent of target.
1069   if (readsVCCZ(MI) && ST->getGeneration() <= SISubtarget::SEA_ISLANDS) {
1070     if (ScoreBrackets->getScoreLB(LGKM_CNT) <
1071             ScoreBrackets->getScoreUB(LGKM_CNT) &&
1072         ScoreBrackets->hasPendingSMEM()) {
1073       // Wait on everything, not just LGKM.  vccz reads usually come from
1074       // terminators, and we always wait on everything at the end of the
1075       // block, so if we only wait on LGKM here, we might end up with
1076       // another s_waitcnt inserted right after this if there are non-LGKM
1077       // instructions still outstanding.
1078       ForceZero = true;
1079       EmitSwaitcnt = true;
1080     }
1081   }
1082 
1083   // Does this operand processing indicate s_wait counter update?
1084   if (EmitSwaitcnt) {
1085     int CntVal[NUM_INST_CNTS];
1086 
1087     bool UseDefaultWaitcntStrategy = true;
1088     if (ForceZero) {
1089       // Force all waitcnts to 0.
1090       for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1091            T = (enum InstCounterType)(T + 1)) {
1092         ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
1093       }
1094       CntVal[VM_CNT] = 0;
1095       CntVal[EXP_CNT] = 0;
1096       CntVal[LGKM_CNT] = 0;
1097       UseDefaultWaitcntStrategy = false;
1098     }
1099 
1100     if (UseDefaultWaitcntStrategy) {
1101       for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1102            T = (enum InstCounterType)(T + 1)) {
1103         if (EmitSwaitcnt & CNT_MASK(T)) {
1104           int Delta =
1105               ScoreBrackets->getScoreUB(T) - ScoreBrackets->getScoreLB(T);
1106           int MaxDelta = ScoreBrackets->getWaitCountMax(T);
1107           if (Delta >= MaxDelta) {
1108             Delta = -1;
1109             if (T != EXP_CNT) {
1110               ScoreBrackets->setScoreLB(
1111                   T, ScoreBrackets->getScoreUB(T) - MaxDelta);
1112             }
1113             EmitSwaitcnt &= ~CNT_MASK(T);
1114           }
1115           CntVal[T] = Delta;
1116         } else {
1117           // If we are not waiting for a particular counter then encode
1118           // it as -1 which means "don't care."
1119           CntVal[T] = -1;
1120         }
1121       }
1122     }
1123 
1124     // If we are not waiting on any counter we can skip the wait altogether.
1125     if (EmitSwaitcnt != 0) {
1126       MachineInstr *OldWaitcnt = ScoreBrackets->getWaitcnt();
1127       int Imm = (!OldWaitcnt) ? 0 : OldWaitcnt->getOperand(0).getImm();
1128       if (!OldWaitcnt ||
1129           (AMDGPU::decodeVmcnt(IV, Imm) !=
1130                           (CntVal[VM_CNT] & AMDGPU::getVmcntBitMask(IV))) ||
1131           (AMDGPU::decodeExpcnt(IV, Imm) !=
1132            (CntVal[EXP_CNT] & AMDGPU::getExpcntBitMask(IV))) ||
1133           (AMDGPU::decodeLgkmcnt(IV, Imm) !=
1134            (CntVal[LGKM_CNT] & AMDGPU::getLgkmcntBitMask(IV)))) {
1135         MachineLoop *ContainingLoop = MLI->getLoopFor(MI.getParent());
1136         if (ContainingLoop) {
1137           MachineBasicBlock *TBB = ContainingLoop->getHeader();
1138           BlockWaitcntBrackets *ScoreBracket =
1139               BlockWaitcntBracketsMap[TBB].get();
1140           if (!ScoreBracket) {
1141             assert(!BlockVisitedSet.count(TBB));
1142             BlockWaitcntBracketsMap[TBB] =
1143                 llvm::make_unique<BlockWaitcntBrackets>();
1144             ScoreBracket = BlockWaitcntBracketsMap[TBB].get();
1145           }
1146           ScoreBracket->setRevisitLoop(true);
1147           DEBUG(dbgs() << "set-revisit: Block"
1148                        << ContainingLoop->getHeader()->getNumber() << '\n';);
1149         }
1150       }
1151 
1152       // Update an existing waitcount, or make a new one.
1153       unsigned Enc = AMDGPU::encodeWaitcnt(IV, CntVal[VM_CNT],
1154                                            CntVal[EXP_CNT], CntVal[LGKM_CNT]);
1155       // We don't remove waitcnts that existed prior to the waitcnt
1156       // pass. Check if the waitcnt to-be-inserted can be avoided
1157       // or if the prev waitcnt can be updated.
1158       bool insertSWaitInst = true;
1159       for (MachineBasicBlock::iterator I = MI.getIterator(),
1160                                        B = MI.getParent()->begin();
1161            insertSWaitInst && I != B; --I) {
1162         if (I == MI.getIterator())
1163           continue;
1164 
1165         switch (I->getOpcode()) {
1166         case AMDGPU::S_WAITCNT:
1167           if (isWaitcntStronger(I->getOperand(0).getImm(), Enc))
1168             insertSWaitInst = false;
1169           else if (!OldWaitcnt) {
1170             OldWaitcnt = &*I;
1171             Enc = combineWaitcnt(I->getOperand(0).getImm(), Enc);
1172           }
1173           break;
1174         // TODO: skip over instructions which never require wait.
1175         }
1176         break;
1177       }
1178       if (insertSWaitInst) {
1179         if (OldWaitcnt && OldWaitcnt->getOpcode() == AMDGPU::S_WAITCNT) {
1180           OldWaitcnt->getOperand(0).setImm(Enc);
1181           if (!OldWaitcnt->getParent())
1182             MI.getParent()->insert(MI, OldWaitcnt);
1183 
1184           DEBUG(dbgs() << "updateWaitcntInBlock\n"
1185                        << "Old Instr: " << MI << '\n'
1186                        << "New Instr: " << *OldWaitcnt << '\n');
1187         } else {
1188             auto SWaitInst = BuildMI(*MI.getParent(), MI.getIterator(),
1189                                MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1190                              .addImm(Enc);
1191             TrackedWaitcntSet.insert(SWaitInst);
1192 
1193             DEBUG(dbgs() << "insertWaitcntInBlock\n"
1194                          << "Old Instr: " << MI << '\n'
1195                          << "New Instr: " << *SWaitInst << '\n');
1196         }
1197       }
1198 
1199       if (CntVal[EXP_CNT] == 0) {
1200         ScoreBrackets->setMixedExpTypes(false);
1201       }
1202     }
1203   }
1204 }
1205 
1206 void SIInsertWaitcnts::insertWaitcntBeforeCF(MachineBasicBlock &MBB,
1207                                              MachineInstr *Waitcnt) {
1208   if (MBB.empty()) {
1209     MBB.push_back(Waitcnt);
1210     return;
1211   }
1212 
1213   MachineBasicBlock::iterator It = MBB.end();
1214   MachineInstr *MI = &*(--It);
1215   if (MI->isBranch()) {
1216     MBB.insert(It, Waitcnt);
1217   } else {
1218     MBB.push_back(Waitcnt);
1219   }
1220 }
1221 
1222 // This is a flat memory operation. Check to see if it has memory
1223 // tokens for both LDS and Memory, and if so mark it as a flat.
1224 bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
1225   if (MI.memoperands_empty())
1226     return true;
1227 
1228   for (const MachineMemOperand *Memop : MI.memoperands()) {
1229     unsigned AS = Memop->getAddrSpace();
1230     if (AS == AMDGPUASI.LOCAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS)
1231       return true;
1232   }
1233 
1234   return false;
1235 }
1236 
1237 void SIInsertWaitcnts::updateEventWaitCntAfter(
1238     MachineInstr &Inst, BlockWaitcntBrackets *ScoreBrackets) {
1239   // Now look at the instruction opcode. If it is a memory access
1240   // instruction, update the upper-bound of the appropriate counter's
1241   // bracket and the destination operand scores.
1242   // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
1243   if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
1244     if (TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
1245       ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1246       ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1247     } else {
1248       ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1249     }
1250   } else if (TII->isFLAT(Inst)) {
1251     assert(Inst.mayLoad() || Inst.mayStore());
1252 
1253     if (TII->usesVM_CNT(Inst))
1254       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1255 
1256     if (TII->usesLGKM_CNT(Inst)) {
1257       ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1258 
1259       // This is a flat memory operation, so note it - it will require
1260       // that both the VM and LGKM be flushed to zero if it is pending when
1261       // a VM or LGKM dependency occurs.
1262       if (mayAccessLDSThroughFlat(Inst))
1263         ScoreBrackets->setPendingFlat();
1264     }
1265   } else if (SIInstrInfo::isVMEM(Inst) &&
1266              // TODO: get a better carve out.
1267              Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1 &&
1268              Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_SC &&
1269              Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_VOL) {
1270     ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1271     if ( // TODO: assumed yes -- target_info->MemWriteNeedsExpWait() &&
1272         (Inst.mayStore() || AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1)) {
1273       ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1274     }
1275   } else if (TII->isSMRD(Inst)) {
1276     ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1277   } else {
1278     switch (Inst.getOpcode()) {
1279     case AMDGPU::S_SENDMSG:
1280     case AMDGPU::S_SENDMSGHALT:
1281       ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1282       break;
1283     case AMDGPU::EXP:
1284     case AMDGPU::EXP_DONE: {
1285       int Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1286       if (Imm >= 32 && Imm <= 63)
1287         ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1288       else if (Imm >= 12 && Imm <= 15)
1289         ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1290       else
1291         ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1292       break;
1293     }
1294     case AMDGPU::S_MEMTIME:
1295     case AMDGPU::S_MEMREALTIME:
1296       ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1297       break;
1298     default:
1299       break;
1300     }
1301   }
1302 }
1303 
1304 // Merge the score brackets of the Block's predecessors;
1305 // this merged score bracket is used when adding waitcnts to the Block
1306 void SIInsertWaitcnts::mergeInputScoreBrackets(MachineBasicBlock &Block) {
1307   BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&Block].get();
1308   int32_t MaxPending[NUM_INST_CNTS] = {0};
1309   int32_t MaxFlat[NUM_INST_CNTS] = {0};
1310   bool MixedExpTypes = false;
1311 
1312   // For single basic block loops, we need to retain the Block's
1313   // score bracket to have accurate Pred info. So, make a copy of Block's
1314   // score bracket, clear() it (which retains several important bits of info),
1315   // populate, and then replace en masse. For non-single basic block loops,
1316   // just clear Block's current score bracket and repopulate in-place.
1317   bool IsSelfPred;
1318   std::unique_ptr<BlockWaitcntBrackets> S;
1319 
1320   IsSelfPred = (std::find(Block.pred_begin(), Block.pred_end(), &Block))
1321     != Block.pred_end();
1322   if (IsSelfPred) {
1323     S = llvm::make_unique<BlockWaitcntBrackets>(*ScoreBrackets);
1324     ScoreBrackets = S.get();
1325   }
1326 
1327   ScoreBrackets->clear();
1328 
1329   // See if there are any uninitialized predecessors. If so, emit an
1330   // s_waitcnt 0 at the beginning of the block.
1331   for (MachineBasicBlock *Pred : Block.predecessors()) {
1332     BlockWaitcntBrackets *PredScoreBrackets =
1333         BlockWaitcntBracketsMap[Pred].get();
1334     bool Visited = BlockVisitedSet.count(Pred);
1335     if (!Visited || PredScoreBrackets->getWaitAtBeginning()) {
1336       continue;
1337     }
1338     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1339          T = (enum InstCounterType)(T + 1)) {
1340       int span =
1341           PredScoreBrackets->getScoreUB(T) - PredScoreBrackets->getScoreLB(T);
1342       MaxPending[T] = std::max(MaxPending[T], span);
1343       span =
1344           PredScoreBrackets->pendingFlat(T) - PredScoreBrackets->getScoreLB(T);
1345       MaxFlat[T] = std::max(MaxFlat[T], span);
1346     }
1347 
1348     MixedExpTypes |= PredScoreBrackets->mixedExpTypes();
1349   }
1350 
1351   // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1352   // Also handle kills for exit block.
1353   if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1354     for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1355       for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1356            T = (enum InstCounterType)(T + 1)) {
1357         int Span = KillWaitBrackets[I]->getScoreUB(T) -
1358                    KillWaitBrackets[I]->getScoreLB(T);
1359         MaxPending[T] = std::max(MaxPending[T], Span);
1360         Span = KillWaitBrackets[I]->pendingFlat(T) -
1361                KillWaitBrackets[I]->getScoreLB(T);
1362         MaxFlat[T] = std::max(MaxFlat[T], Span);
1363       }
1364 
1365       MixedExpTypes |= KillWaitBrackets[I]->mixedExpTypes();
1366     }
1367   }
1368 
1369   // Special handling for GDS_GPR_LOCK and EXP_GPR_LOCK.
1370   for (MachineBasicBlock *Pred : Block.predecessors()) {
1371     BlockWaitcntBrackets *PredScoreBrackets =
1372         BlockWaitcntBracketsMap[Pred].get();
1373     bool Visited = BlockVisitedSet.count(Pred);
1374     if (!Visited || PredScoreBrackets->getWaitAtBeginning()) {
1375       continue;
1376     }
1377 
1378     int GDSSpan = PredScoreBrackets->getEventUB(GDS_GPR_LOCK) -
1379                   PredScoreBrackets->getScoreLB(EXP_CNT);
1380     MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], GDSSpan);
1381     int EXPSpan = PredScoreBrackets->getEventUB(EXP_GPR_LOCK) -
1382                   PredScoreBrackets->getScoreLB(EXP_CNT);
1383     MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], EXPSpan);
1384   }
1385 
1386   // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1387   if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1388     for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1389       int GDSSpan = KillWaitBrackets[I]->getEventUB(GDS_GPR_LOCK) -
1390                     KillWaitBrackets[I]->getScoreLB(EXP_CNT);
1391       MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], GDSSpan);
1392       int EXPSpan = KillWaitBrackets[I]->getEventUB(EXP_GPR_LOCK) -
1393                     KillWaitBrackets[I]->getScoreLB(EXP_CNT);
1394       MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], EXPSpan);
1395     }
1396   }
1397 
1398 #if 0
1399   // LC does not (unlike) add a waitcnt at beginning. Leaving it as marker.
1400   // TODO: how does LC distinguish between function entry and main entry?
1401   // If this is the entry to a function, force a wait.
1402   MachineBasicBlock &Entry = Block.getParent()->front();
1403   if (Entry.getNumber() == Block.getNumber()) {
1404     ScoreBrackets->setWaitAtBeginning();
1405     return;
1406   }
1407 #endif
1408 
1409   // Now set the current Block's brackets to the largest ending bracket.
1410   for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1411        T = (enum InstCounterType)(T + 1)) {
1412     ScoreBrackets->setScoreUB(T, MaxPending[T]);
1413     ScoreBrackets->setScoreLB(T, 0);
1414     ScoreBrackets->setLastFlat(T, MaxFlat[T]);
1415   }
1416 
1417   ScoreBrackets->setMixedExpTypes(MixedExpTypes);
1418 
1419   // Set the register scoreboard.
1420   for (MachineBasicBlock *Pred : Block.predecessors()) {
1421     if (!BlockVisitedSet.count(Pred)) {
1422       continue;
1423     }
1424 
1425     BlockWaitcntBrackets *PredScoreBrackets =
1426         BlockWaitcntBracketsMap[Pred].get();
1427 
1428     // Now merge the gpr_reg_score information
1429     for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1430          T = (enum InstCounterType)(T + 1)) {
1431       int PredLB = PredScoreBrackets->getScoreLB(T);
1432       int PredUB = PredScoreBrackets->getScoreUB(T);
1433       if (PredLB < PredUB) {
1434         int PredScale = MaxPending[T] - PredUB;
1435         // Merge vgpr scores.
1436         for (int J = 0; J <= PredScoreBrackets->getMaxVGPR(); J++) {
1437           int PredRegScore = PredScoreBrackets->getRegScore(J, T);
1438           if (PredRegScore <= PredLB)
1439             continue;
1440           int NewRegScore = PredScale + PredRegScore;
1441           ScoreBrackets->setRegScore(
1442               J, T, std::max(ScoreBrackets->getRegScore(J, T), NewRegScore));
1443         }
1444         // Also need to merge sgpr scores for lgkm_cnt.
1445         if (T == LGKM_CNT) {
1446           for (int J = 0; J <= PredScoreBrackets->getMaxSGPR(); J++) {
1447             int PredRegScore =
1448                 PredScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
1449             if (PredRegScore <= PredLB)
1450               continue;
1451             int NewRegScore = PredScale + PredRegScore;
1452             ScoreBrackets->setRegScore(
1453                 J + NUM_ALL_VGPRS, LGKM_CNT,
1454                 std::max(
1455                     ScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT),
1456                     NewRegScore));
1457           }
1458         }
1459       }
1460     }
1461 
1462     // Also merge the WaitEvent information.
1463     ForAllWaitEventType(W) {
1464       enum InstCounterType T = PredScoreBrackets->eventCounter(W);
1465       int PredEventUB = PredScoreBrackets->getEventUB(W);
1466       if (PredEventUB > PredScoreBrackets->getScoreLB(T)) {
1467         int NewEventUB =
1468             MaxPending[T] + PredEventUB - PredScoreBrackets->getScoreUB(T);
1469         if (NewEventUB > 0) {
1470           ScoreBrackets->setEventUB(
1471               W, std::max(ScoreBrackets->getEventUB(W), NewEventUB));
1472         }
1473       }
1474     }
1475   }
1476 
1477   // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1478   // Set the register scoreboard.
1479   if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1480     for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1481       // Now merge the gpr_reg_score information.
1482       for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1483            T = (enum InstCounterType)(T + 1)) {
1484         int PredLB = KillWaitBrackets[I]->getScoreLB(T);
1485         int PredUB = KillWaitBrackets[I]->getScoreUB(T);
1486         if (PredLB < PredUB) {
1487           int PredScale = MaxPending[T] - PredUB;
1488           // Merge vgpr scores.
1489           for (int J = 0; J <= KillWaitBrackets[I]->getMaxVGPR(); J++) {
1490             int PredRegScore = KillWaitBrackets[I]->getRegScore(J, T);
1491             if (PredRegScore <= PredLB)
1492               continue;
1493             int NewRegScore = PredScale + PredRegScore;
1494             ScoreBrackets->setRegScore(
1495                 J, T, std::max(ScoreBrackets->getRegScore(J, T), NewRegScore));
1496           }
1497           // Also need to merge sgpr scores for lgkm_cnt.
1498           if (T == LGKM_CNT) {
1499             for (int J = 0; J <= KillWaitBrackets[I]->getMaxSGPR(); J++) {
1500               int PredRegScore =
1501                   KillWaitBrackets[I]->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
1502               if (PredRegScore <= PredLB)
1503                 continue;
1504               int NewRegScore = PredScale + PredRegScore;
1505               ScoreBrackets->setRegScore(
1506                   J + NUM_ALL_VGPRS, LGKM_CNT,
1507                   std::max(
1508                       ScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT),
1509                       NewRegScore));
1510             }
1511           }
1512         }
1513       }
1514 
1515       // Also merge the WaitEvent information.
1516       ForAllWaitEventType(W) {
1517         enum InstCounterType T = KillWaitBrackets[I]->eventCounter(W);
1518         int PredEventUB = KillWaitBrackets[I]->getEventUB(W);
1519         if (PredEventUB > KillWaitBrackets[I]->getScoreLB(T)) {
1520           int NewEventUB =
1521               MaxPending[T] + PredEventUB - KillWaitBrackets[I]->getScoreUB(T);
1522           if (NewEventUB > 0) {
1523             ScoreBrackets->setEventUB(
1524                 W, std::max(ScoreBrackets->getEventUB(W), NewEventUB));
1525           }
1526         }
1527       }
1528     }
1529   }
1530 
1531   // Special case handling of GDS_GPR_LOCK and EXP_GPR_LOCK. Merge this for the
1532   // sequencing predecessors, because changes to EXEC require waitcnts due to
1533   // the delayed nature of these operations.
1534   for (MachineBasicBlock *Pred : Block.predecessors()) {
1535     if (!BlockVisitedSet.count(Pred)) {
1536       continue;
1537     }
1538 
1539     BlockWaitcntBrackets *PredScoreBrackets =
1540         BlockWaitcntBracketsMap[Pred].get();
1541 
1542     int pred_gds_ub = PredScoreBrackets->getEventUB(GDS_GPR_LOCK);
1543     if (pred_gds_ub > PredScoreBrackets->getScoreLB(EXP_CNT)) {
1544       int new_gds_ub = MaxPending[EXP_CNT] + pred_gds_ub -
1545                        PredScoreBrackets->getScoreUB(EXP_CNT);
1546       if (new_gds_ub > 0) {
1547         ScoreBrackets->setEventUB(
1548             GDS_GPR_LOCK,
1549             std::max(ScoreBrackets->getEventUB(GDS_GPR_LOCK), new_gds_ub));
1550       }
1551     }
1552     int pred_exp_ub = PredScoreBrackets->getEventUB(EXP_GPR_LOCK);
1553     if (pred_exp_ub > PredScoreBrackets->getScoreLB(EXP_CNT)) {
1554       int new_exp_ub = MaxPending[EXP_CNT] + pred_exp_ub -
1555                        PredScoreBrackets->getScoreUB(EXP_CNT);
1556       if (new_exp_ub > 0) {
1557         ScoreBrackets->setEventUB(
1558             EXP_GPR_LOCK,
1559             std::max(ScoreBrackets->getEventUB(EXP_GPR_LOCK), new_exp_ub));
1560       }
1561     }
1562   }
1563 
1564   // if a single block loop, update the score brackets. Not needed for other
1565   // blocks, as we did this in-place
1566   if (IsSelfPred) {
1567     BlockWaitcntBracketsMap[&Block] = llvm::make_unique<BlockWaitcntBrackets>(*ScoreBrackets);
1568   }
1569 }
1570 
1571 /// Return the "bottom" block of a loop. This differs from
1572 /// MachineLoop::getBottomBlock in that it works even if the loop is
1573 /// discontiguous.
1574 MachineBasicBlock *SIInsertWaitcnts::loopBottom(const MachineLoop *Loop) {
1575   MachineBasicBlock *Bottom = Loop->getHeader();
1576   for (MachineBasicBlock *MBB : Loop->blocks())
1577     if (MBB->getNumber() > Bottom->getNumber())
1578       Bottom = MBB;
1579   return Bottom;
1580 }
1581 
1582 // Generate s_waitcnt instructions where needed.
1583 void SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1584                                             MachineBasicBlock &Block) {
1585   // Initialize the state information.
1586   mergeInputScoreBrackets(Block);
1587 
1588   BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&Block].get();
1589 
1590   DEBUG({
1591     dbgs() << "Block" << Block.getNumber();
1592     ScoreBrackets->dump();
1593   });
1594 
1595   // Walk over the instructions.
1596   for (MachineBasicBlock::iterator Iter = Block.begin(), E = Block.end();
1597        Iter != E;) {
1598     MachineInstr &Inst = *Iter;
1599     // Remove any previously existing waitcnts.
1600     if (Inst.getOpcode() == AMDGPU::S_WAITCNT) {
1601       // Leave pre-existing waitcnts, but note their existence via setWaitcnt.
1602       // Remove the waitcnt-pass-generated waitcnts; the pass will add them back
1603       // as needed.
1604       if (!TrackedWaitcntSet.count(&Inst))
1605         ++Iter;
1606       else {
1607         ++Iter;
1608         Inst.removeFromParent();
1609       }
1610       ScoreBrackets->setWaitcnt(&Inst);
1611       continue;
1612     }
1613 
1614     // Kill instructions generate a conditional branch to the endmain block.
1615     // Merge the current waitcnt state into the endmain block information.
1616     // TODO: Are there other flavors of KILL instruction?
1617     if (Inst.getOpcode() == AMDGPU::KILL) {
1618       addKillWaitBracket(ScoreBrackets);
1619     }
1620 
1621     bool VCCZBugWorkAround = false;
1622     if (readsVCCZ(Inst) &&
1623         (!VCCZBugHandledSet.count(&Inst))) {
1624       if (ScoreBrackets->getScoreLB(LGKM_CNT) <
1625               ScoreBrackets->getScoreUB(LGKM_CNT) &&
1626           ScoreBrackets->hasPendingSMEM()) {
1627         if (ST->getGeneration() <= SISubtarget::SEA_ISLANDS)
1628           VCCZBugWorkAround = true;
1629       }
1630     }
1631 
1632     // Generate an s_waitcnt instruction to be placed before
1633     // cur_Inst, if needed.
1634     generateSWaitCntInstBefore(Inst, ScoreBrackets);
1635 
1636     updateEventWaitCntAfter(Inst, ScoreBrackets);
1637 
1638 #if 0 // TODO: implement resource type check controlled by options with ub = LB.
1639     // If this instruction generates a S_SETVSKIP because it is an
1640     // indexed resource, and we are on Tahiti, then it will also force
1641     // an S_WAITCNT vmcnt(0)
1642     if (RequireCheckResourceType(Inst, context)) {
1643       // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1644       ScoreBrackets->setScoreLB(VM_CNT,
1645       ScoreBrackets->getScoreUB(VM_CNT));
1646     }
1647 #endif
1648 
1649     ScoreBrackets->clearWaitcnt();
1650 
1651     DEBUG({
1652       Inst.print(dbgs());
1653       ScoreBrackets->dump();
1654     });
1655 
1656     // Check to see if this is a GWS instruction. If so, and if this is CI or
1657     // VI, then the generated code sequence will include an S_WAITCNT 0.
1658     // TODO: Are these the only GWS instructions?
1659     if (Inst.getOpcode() == AMDGPU::DS_GWS_INIT ||
1660         Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_V ||
1661         Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_BR ||
1662         Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_P ||
1663         Inst.getOpcode() == AMDGPU::DS_GWS_BARRIER) {
1664       // TODO: && context->target_info->GwsRequiresMemViolTest() ) {
1665       ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
1666       ScoreBrackets->updateByWait(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
1667       ScoreBrackets->updateByWait(LGKM_CNT,
1668                                   ScoreBrackets->getScoreUB(LGKM_CNT));
1669     }
1670 
1671     // TODO: Remove this work-around after fixing the scheduler and enable the
1672     // assert above.
1673     if (VCCZBugWorkAround) {
1674       // Restore the vccz bit.  Any time a value is written to vcc, the vcc
1675       // bit is updated, so we can restore the bit by reading the value of
1676       // vcc and then writing it back to the register.
1677       BuildMI(Block, Inst, Inst.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
1678               AMDGPU::VCC)
1679           .addReg(AMDGPU::VCC);
1680       VCCZBugHandledSet.insert(&Inst);
1681     }
1682 
1683     ++Iter;
1684   }
1685 
1686   // Check if we need to force convergence at loop footer.
1687   MachineLoop *ContainingLoop = MLI->getLoopFor(&Block);
1688   if (ContainingLoop && loopBottom(ContainingLoop) == &Block) {
1689     LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1690     WaitcntData->print();
1691     DEBUG(dbgs() << '\n';);
1692 
1693     // The iterative waitcnt insertion algorithm aims for optimal waitcnt
1694     // placement and doesn't always guarantee convergence for a loop. Each
1695     // loop should take at most 2 iterations for it to converge naturally.
1696     // When this max is reached and result doesn't converge, we force
1697     // convergence by inserting a s_waitcnt at the end of loop footer.
1698     if (WaitcntData->getIterCnt() > 2) {
1699       // To ensure convergence, need to make wait events at loop footer be no
1700       // more than those from the previous iteration.
1701       // As a simplification, instead of tracking individual scores and
1702       // generating the precise wait count, just wait on 0.
1703       bool HasPending = false;
1704       MachineInstr *SWaitInst = WaitcntData->getWaitcnt();
1705       for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1706            T = (enum InstCounterType)(T + 1)) {
1707         if (ScoreBrackets->getScoreUB(T) > ScoreBrackets->getScoreLB(T)) {
1708           ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
1709           HasPending = true;
1710         }
1711       }
1712 
1713       if (HasPending) {
1714         if (!SWaitInst) {
1715           SWaitInst = Block.getParent()->CreateMachineInstr(
1716               TII->get(AMDGPU::S_WAITCNT), DebugLoc());
1717           TrackedWaitcntSet.insert(SWaitInst);
1718           const MachineOperand &Op = MachineOperand::CreateImm(0);
1719           SWaitInst->addOperand(MF, Op);
1720 #if 0 // TODO: Format the debug output
1721           OutputTransformBanner("insertWaitcntInBlock",0,"Create:",context);
1722           OutputTransformAdd(SWaitInst, context);
1723 #endif
1724         }
1725 #if 0 // TODO: ??
1726         _DEV( REPORTED_STATS->force_waitcnt_converge = 1; )
1727 #endif
1728       }
1729 
1730       if (SWaitInst) {
1731         DEBUG({
1732           SWaitInst->print(dbgs());
1733           dbgs() << "\nAdjusted score board:";
1734           ScoreBrackets->dump();
1735         });
1736 
1737         // Add this waitcnt to the block. It is either newly created or
1738         // created in previous iterations and added back since block traversal
1739         // always removes waitcnts.
1740         insertWaitcntBeforeCF(Block, SWaitInst);
1741         WaitcntData->setWaitcnt(SWaitInst);
1742       }
1743     }
1744   }
1745 }
1746 
1747 bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
1748   ST = &MF.getSubtarget<SISubtarget>();
1749   TII = ST->getInstrInfo();
1750   TRI = &TII->getRegisterInfo();
1751   MRI = &MF.getRegInfo();
1752   MLI = &getAnalysis<MachineLoopInfo>();
1753   IV = AMDGPU::IsaInfo::getIsaVersion(ST->getFeatureBits());
1754   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1755   AMDGPUASI = ST->getAMDGPUAS();
1756 
1757   HardwareLimits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1758   HardwareLimits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1759   HardwareLimits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
1760 
1761   HardwareLimits.NumVGPRsMax = ST->getAddressableNumVGPRs();
1762   HardwareLimits.NumSGPRsMax = ST->getAddressableNumSGPRs();
1763   assert(HardwareLimits.NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1764   assert(HardwareLimits.NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1765 
1766   RegisterEncoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1767   RegisterEncoding.VGPRL =
1768       RegisterEncoding.VGPR0 + HardwareLimits.NumVGPRsMax - 1;
1769   RegisterEncoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1770   RegisterEncoding.SGPRL =
1771       RegisterEncoding.SGPR0 + HardwareLimits.NumSGPRsMax - 1;
1772 
1773   TrackedWaitcntSet.clear();
1774   BlockVisitedSet.clear();
1775   VCCZBugHandledSet.clear();
1776 
1777   // Walk over the blocks in reverse post-dominator order, inserting
1778   // s_waitcnt where needed.
1779   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1780   bool Modified = false;
1781   for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1782            I = RPOT.begin(),
1783            E = RPOT.end(), J = RPOT.begin();
1784        I != E;) {
1785     MachineBasicBlock &MBB = **I;
1786 
1787     BlockVisitedSet.insert(&MBB);
1788 
1789     BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&MBB].get();
1790     if (!ScoreBrackets) {
1791       BlockWaitcntBracketsMap[&MBB] = llvm::make_unique<BlockWaitcntBrackets>();
1792       ScoreBrackets = BlockWaitcntBracketsMap[&MBB].get();
1793     }
1794     ScoreBrackets->setPostOrder(MBB.getNumber());
1795     MachineLoop *ContainingLoop = MLI->getLoopFor(&MBB);
1796     if (ContainingLoop && LoopWaitcntDataMap[ContainingLoop] == nullptr)
1797       LoopWaitcntDataMap[ContainingLoop] = llvm::make_unique<LoopWaitcntData>();
1798 
1799     // If we are walking into the block from before the loop, then guarantee
1800     // at least 1 re-walk over the loop to propagate the information, even if
1801     // no S_WAITCNT instructions were generated.
1802     if (ContainingLoop && ContainingLoop->getHeader() == &MBB && J < I &&
1803         (!BlockWaitcntProcessedSet.count(&MBB))) {
1804       BlockWaitcntBracketsMap[&MBB]->setRevisitLoop(true);
1805       DEBUG(dbgs() << "set-revisit: Block"
1806                    << ContainingLoop->getHeader()->getNumber() << '\n';);
1807     }
1808 
1809     // Walk over the instructions.
1810     insertWaitcntInBlock(MF, MBB);
1811 
1812     // Flag that waitcnts have been processed at least once.
1813     BlockWaitcntProcessedSet.insert(&MBB);
1814 
1815     // See if we want to revisit the loop.
1816     if (ContainingLoop && loopBottom(ContainingLoop) == &MBB) {
1817       MachineBasicBlock *EntryBB = ContainingLoop->getHeader();
1818       BlockWaitcntBrackets *EntrySB = BlockWaitcntBracketsMap[EntryBB].get();
1819       if (EntrySB && EntrySB->getRevisitLoop()) {
1820         EntrySB->setRevisitLoop(false);
1821         J = I;
1822         int32_t PostOrder = EntrySB->getPostOrder();
1823         // TODO: Avoid this loop. Find another way to set I.
1824         for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1825                  X = RPOT.begin(),
1826                  Y = RPOT.end();
1827              X != Y; ++X) {
1828           MachineBasicBlock &MBBX = **X;
1829           if (MBBX.getNumber() == PostOrder) {
1830             I = X;
1831             break;
1832           }
1833         }
1834         LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1835         WaitcntData->incIterCnt();
1836         DEBUG(dbgs() << "revisit: Block" << EntryBB->getNumber() << '\n';);
1837         continue;
1838       } else {
1839         LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1840         // Loop converged, reset iteration count. If this loop gets revisited,
1841         // it must be from an outer loop, the counter will restart, this will
1842         // ensure we don't force convergence on such revisits.
1843         WaitcntData->resetIterCnt();
1844       }
1845     }
1846 
1847     J = I;
1848     ++I;
1849   }
1850 
1851   SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1852 
1853   bool HaveScalarStores = false;
1854 
1855   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE;
1856        ++BI) {
1857     MachineBasicBlock &MBB = *BI;
1858 
1859     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1860          ++I) {
1861       if (!HaveScalarStores && TII->isScalarStore(*I))
1862         HaveScalarStores = true;
1863 
1864       if (I->getOpcode() == AMDGPU::S_ENDPGM ||
1865           I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1866         EndPgmBlocks.push_back(&MBB);
1867     }
1868   }
1869 
1870   if (HaveScalarStores) {
1871     // If scalar writes are used, the cache must be flushed or else the next
1872     // wave to reuse the same scratch memory can be clobbered.
1873     //
1874     // Insert s_dcache_wb at wave termination points if there were any scalar
1875     // stores, and only if the cache hasn't already been flushed. This could be
1876     // improved by looking across blocks for flushes in postdominating blocks
1877     // from the stores but an explicitly requested flush is probably very rare.
1878     for (MachineBasicBlock *MBB : EndPgmBlocks) {
1879       bool SeenDCacheWB = false;
1880 
1881       for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
1882            ++I) {
1883         if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1884           SeenDCacheWB = true;
1885         else if (TII->isScalarStore(*I))
1886           SeenDCacheWB = false;
1887 
1888         // FIXME: It would be better to insert this before a waitcnt if any.
1889         if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1890              I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1891             !SeenDCacheWB) {
1892           Modified = true;
1893           BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
1894         }
1895       }
1896     }
1897   }
1898 
1899   if (!MFI->isEntryFunction()) {
1900     // Wait for any outstanding memory operations that the input registers may
1901     // depend on. We can't track them and it's better to the wait after the
1902     // costly call sequence.
1903 
1904     // TODO: Could insert earlier and schedule more liberally with operations
1905     // that only use caller preserved registers.
1906     MachineBasicBlock &EntryBB = MF.front();
1907     BuildMI(EntryBB, EntryBB.getFirstNonPHI(), DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1908       .addImm(0);
1909 
1910     Modified = true;
1911   }
1912 
1913   return Modified;
1914 }
1915