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