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