blob: ea6391a31f84352ec71ff185ca12b8c72876f0bb [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 Searlesa84d2342017-12-07 20:36:39 +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 Searlesa84d2342017-12-07 20:36:39 +0000396 int32_t InstCnt = 0;
397 bool ForceZero = false;
398 int32_t ForceSwaitcnt[NUM_INST_CNTS];
399
Kannan Narayananacb089e2017-04-12 03:25:12 +0000400public:
401 static char ID;
402
Eugene Zelenko59e12822017-08-08 00:47:13 +0000403 SIInsertWaitcnts() : MachineFunctionPass(ID) {}
Kannan Narayananacb089e2017-04-12 03:25:12 +0000404
405 bool runOnMachineFunction(MachineFunction &MF) override;
406
407 StringRef getPassName() const override {
408 return "SI insert wait instructions";
409 }
410
411 void getAnalysisUsage(AnalysisUsage &AU) const override {
412 AU.setPreservesCFG();
413 AU.addRequired<MachineLoopInfo>();
414 MachineFunctionPass::getAnalysisUsage(AU);
415 }
416
417 void addKillWaitBracket(BlockWaitcntBrackets *Bracket) {
418 // The waitcnt information is copied because it changes as the block is
419 // traversed.
Eugene Zelenko59e12822017-08-08 00:47:13 +0000420 KillWaitBrackets.push_back(
421 llvm::make_unique<BlockWaitcntBrackets>(*Bracket));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000422 }
423
Mark Searlesa84d2342017-12-07 20:36:39 +0000424 bool ForceEmit() const {
425 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
426 T = (enum InstCounterType)(T + 1))
427 if (ForceSwaitcnt[T] > 0)
428 return true;
429 return false;
430 }
431
Matt Arsenault0ed39d32017-07-21 18:54:54 +0000432 bool mayAccessLDSThroughFlat(const MachineInstr &MI) const;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000433 MachineInstr *generateSWaitCntInstBefore(MachineInstr &MI,
434 BlockWaitcntBrackets *ScoreBrackets);
435 void updateEventWaitCntAfter(MachineInstr &Inst,
436 BlockWaitcntBrackets *ScoreBrackets);
437 void mergeInputScoreBrackets(MachineBasicBlock &Block);
438 MachineBasicBlock *loopBottom(const MachineLoop *Loop);
439 void insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block);
440 void insertWaitcntBeforeCF(MachineBasicBlock &Block, MachineInstr *Inst);
441};
442
Eugene Zelenko59e12822017-08-08 00:47:13 +0000443} // end anonymous namespace
Kannan Narayananacb089e2017-04-12 03:25:12 +0000444
445RegInterval BlockWaitcntBrackets::getRegInterval(const MachineInstr *MI,
446 const SIInstrInfo *TII,
447 const MachineRegisterInfo *MRI,
448 const SIRegisterInfo *TRI,
449 unsigned OpNo,
450 bool Def) const {
451 const MachineOperand &Op = MI->getOperand(OpNo);
452 if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()) ||
453 (Def && !Op.isDef()))
454 return {-1, -1};
455
456 // A use via a PW operand does not need a waitcnt.
457 // A partial write is not a WAW.
458 assert(!Op.getSubReg() || !Op.isUndef());
459
460 RegInterval Result;
461 const MachineRegisterInfo &MRIA = *MRI;
462
463 unsigned Reg = TRI->getEncodingValue(Op.getReg());
464
465 if (TRI->isVGPR(MRIA, Op.getReg())) {
466 assert(Reg >= RegisterEncoding.VGPR0 && Reg <= RegisterEncoding.VGPRL);
467 Result.first = Reg - RegisterEncoding.VGPR0;
468 assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
469 } else if (TRI->isSGPRReg(MRIA, Op.getReg())) {
470 assert(Reg >= RegisterEncoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS);
471 Result.first = Reg - RegisterEncoding.SGPR0 + NUM_ALL_VGPRS;
472 assert(Result.first >= NUM_ALL_VGPRS &&
473 Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS);
474 }
475 // TODO: Handle TTMP
476 // else if (TRI->isTTMP(MRIA, Reg.getReg())) ...
477 else
478 return {-1, -1};
479
480 const MachineInstr &MIA = *MI;
481 const TargetRegisterClass *RC = TII->getOpRegClass(MIA, OpNo);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +0000482 unsigned Size = TRI->getRegSizeInBits(*RC);
483 Result.second = Result.first + (Size / 32);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000484
485 return Result;
486}
487
488void BlockWaitcntBrackets::setExpScore(const MachineInstr *MI,
489 const SIInstrInfo *TII,
490 const SIRegisterInfo *TRI,
491 const MachineRegisterInfo *MRI,
492 unsigned OpNo, int32_t Val) {
493 RegInterval Interval = getRegInterval(MI, TII, MRI, TRI, OpNo, false);
494 DEBUG({
495 const MachineOperand &Opnd = MI->getOperand(OpNo);
496 assert(TRI->isVGPR(*MRI, Opnd.getReg()));
497 });
498 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
499 setRegScore(RegNo, EXP_CNT, Val);
500 }
501}
502
503void BlockWaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
504 const SIRegisterInfo *TRI,
505 const MachineRegisterInfo *MRI,
506 WaitEventType E, MachineInstr &Inst) {
507 const MachineRegisterInfo &MRIA = *MRI;
508 InstCounterType T = eventCounter(E);
509 int32_t CurrScore = getScoreUB(T) + 1;
510 // EventUB and ScoreUB need to be update regardless if this event changes
511 // the score of a register or not.
512 // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
513 EventUBs[E] = CurrScore;
514 setScoreUB(T, CurrScore);
515
516 if (T == EXP_CNT) {
517 // Check for mixed export types. If they are mixed, then a waitcnt exp(0)
518 // is required.
519 if (!MixedExpTypes) {
520 MixedExpTypes = counterOutOfOrder(EXP_CNT);
521 }
522
523 // Put score on the source vgprs. If this is a store, just use those
524 // specific register(s).
525 if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) {
526 // All GDS operations must protect their address register (same as
527 // export.)
528 if (Inst.getOpcode() != AMDGPU::DS_APPEND &&
529 Inst.getOpcode() != AMDGPU::DS_CONSUME) {
530 setExpScore(
531 &Inst, TII, TRI, MRI,
532 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr),
533 CurrScore);
534 }
535 if (Inst.mayStore()) {
536 setExpScore(
537 &Inst, TII, TRI, MRI,
538 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0),
539 CurrScore);
540 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
541 AMDGPU::OpName::data1) != -1) {
542 setExpScore(&Inst, TII, TRI, MRI,
543 AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
544 AMDGPU::OpName::data1),
545 CurrScore);
546 }
547 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1 &&
548 Inst.getOpcode() != AMDGPU::DS_GWS_INIT &&
549 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V &&
550 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR &&
551 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P &&
552 Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER &&
553 Inst.getOpcode() != AMDGPU::DS_APPEND &&
554 Inst.getOpcode() != AMDGPU::DS_CONSUME &&
555 Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
556 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
557 const MachineOperand &Op = Inst.getOperand(I);
558 if (Op.isReg() && !Op.isDef() && TRI->isVGPR(MRIA, Op.getReg())) {
559 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
560 }
561 }
562 }
563 } else if (TII->isFLAT(Inst)) {
564 if (Inst.mayStore()) {
565 setExpScore(
566 &Inst, TII, TRI, MRI,
567 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
568 CurrScore);
569 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
570 setExpScore(
571 &Inst, TII, TRI, MRI,
572 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
573 CurrScore);
574 }
575 } else if (TII->isMIMG(Inst)) {
576 if (Inst.mayStore()) {
577 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
578 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
579 setExpScore(
580 &Inst, TII, TRI, MRI,
581 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
582 CurrScore);
583 }
584 } else if (TII->isMTBUF(Inst)) {
585 if (Inst.mayStore()) {
586 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
587 }
588 } else if (TII->isMUBUF(Inst)) {
589 if (Inst.mayStore()) {
590 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
591 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
592 setExpScore(
593 &Inst, TII, TRI, MRI,
594 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
595 CurrScore);
596 }
597 } else {
598 if (TII->isEXP(Inst)) {
599 // For export the destination registers are really temps that
600 // can be used as the actual source after export patching, so
601 // we need to treat them like sources and set the EXP_CNT
602 // score.
603 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
604 MachineOperand &DefMO = Inst.getOperand(I);
605 if (DefMO.isReg() && DefMO.isDef() &&
606 TRI->isVGPR(MRIA, DefMO.getReg())) {
607 setRegScore(TRI->getEncodingValue(DefMO.getReg()), EXP_CNT,
608 CurrScore);
609 }
610 }
611 }
612 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
613 MachineOperand &MO = Inst.getOperand(I);
614 if (MO.isReg() && !MO.isDef() && TRI->isVGPR(MRIA, MO.getReg())) {
615 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
616 }
617 }
618 }
619#if 0 // TODO: check if this is handled by MUBUF code above.
620 } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD ||
Evgeny Mankovbf975172017-08-16 16:47:29 +0000621 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 ||
622 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000623 MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data);
624 unsigned OpNo;//TODO: find the OpNo for this operand;
625 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo, false);
626 for (signed RegNo = Interval.first; RegNo < Interval.second;
Evgeny Mankovbf975172017-08-16 16:47:29 +0000627 ++RegNo) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000628 setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore);
629 }
630#endif
631 } else {
632 // Match the score to the destination registers.
633 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
634 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I, true);
635 if (T == VM_CNT && Interval.first >= NUM_ALL_VGPRS)
636 continue;
637 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
638 setRegScore(RegNo, T, CurrScore);
639 }
640 }
641 if (TII->isDS(Inst) && Inst.mayStore()) {
642 setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore);
643 }
644 }
645}
646
647void BlockWaitcntBrackets::print(raw_ostream &OS) {
648 OS << '\n';
649 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
650 T = (enum InstCounterType)(T + 1)) {
651 int LB = getScoreLB(T);
652 int UB = getScoreUB(T);
653
654 switch (T) {
655 case VM_CNT:
656 OS << " VM_CNT(" << UB - LB << "): ";
657 break;
658 case LGKM_CNT:
659 OS << " LGKM_CNT(" << UB - LB << "): ";
660 break;
661 case EXP_CNT:
662 OS << " EXP_CNT(" << UB - LB << "): ";
663 break;
664 default:
665 OS << " UNKNOWN(" << UB - LB << "): ";
666 break;
667 }
668
669 if (LB < UB) {
670 // Print vgpr scores.
671 for (int J = 0; J <= getMaxVGPR(); J++) {
672 int RegScore = getRegScore(J, T);
673 if (RegScore <= LB)
674 continue;
675 int RelScore = RegScore - LB - 1;
676 if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
677 OS << RelScore << ":v" << J << " ";
678 } else {
679 OS << RelScore << ":ds ";
680 }
681 }
682 // Also need to print sgpr scores for lgkm_cnt.
683 if (T == LGKM_CNT) {
684 for (int J = 0; J <= getMaxSGPR(); J++) {
685 int RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
686 if (RegScore <= LB)
687 continue;
688 int RelScore = RegScore - LB - 1;
689 OS << RelScore << ":s" << J << " ";
690 }
691 }
692 }
693 OS << '\n';
694 }
695 OS << '\n';
Kannan Narayananacb089e2017-04-12 03:25:12 +0000696}
697
698unsigned int BlockWaitcntBrackets::updateByWait(InstCounterType T,
699 int ScoreToWait) {
700 unsigned int NeedWait = 0;
701 if (ScoreToWait == -1) {
702 // The score to wait is unknown. This implies that it was not encountered
703 // during the path of the CFG walk done during the current traversal but
704 // may be seen on a different path. Emit an s_wait counter with a
705 // conservative value of 0 for the counter.
706 NeedWait = CNT_MASK(T);
707 setScoreLB(T, getScoreUB(T));
708 return NeedWait;
709 }
710
711 // If the score of src_operand falls within the bracket, we need an
712 // s_waitcnt instruction.
713 const int32_t LB = getScoreLB(T);
714 const int32_t UB = getScoreUB(T);
715 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
716 if (T == VM_CNT && hasPendingFlat()) {
717 // If there is a pending FLAT operation, and this is a VM waitcnt,
718 // then we need to force a waitcnt 0 for VM.
719 NeedWait = CNT_MASK(T);
720 setScoreLB(T, getScoreUB(T));
721 } else if (counterOutOfOrder(T)) {
722 // Counter can get decremented out-of-order when there
723 // are multiple types event in the brack. Also emit an s_wait counter
724 // with a conservative value of 0 for the counter.
725 NeedWait = CNT_MASK(T);
726 setScoreLB(T, getScoreUB(T));
727 } else {
728 NeedWait = CNT_MASK(T);
729 setScoreLB(T, ScoreToWait);
730 }
731 }
732
733 return NeedWait;
734}
735
736// Where there are multiple types of event in the bracket of a counter,
737// the decrement may go out of order.
738bool BlockWaitcntBrackets::counterOutOfOrder(InstCounterType T) {
739 switch (T) {
740 case VM_CNT:
741 return false;
742 case LGKM_CNT: {
743 if (EventUBs[SMEM_ACCESS] > ScoreLBs[LGKM_CNT] &&
744 EventUBs[SMEM_ACCESS] <= ScoreUBs[LGKM_CNT]) {
745 // Scalar memory read always can go out of order.
746 return true;
747 }
748 int NumEventTypes = 0;
749 if (EventUBs[LDS_ACCESS] > ScoreLBs[LGKM_CNT] &&
750 EventUBs[LDS_ACCESS] <= ScoreUBs[LGKM_CNT]) {
751 NumEventTypes++;
752 }
753 if (EventUBs[GDS_ACCESS] > ScoreLBs[LGKM_CNT] &&
754 EventUBs[GDS_ACCESS] <= ScoreUBs[LGKM_CNT]) {
755 NumEventTypes++;
756 }
757 if (EventUBs[SQ_MESSAGE] > ScoreLBs[LGKM_CNT] &&
758 EventUBs[SQ_MESSAGE] <= ScoreUBs[LGKM_CNT]) {
759 NumEventTypes++;
760 }
761 if (NumEventTypes <= 1) {
762 return false;
763 }
764 break;
765 }
766 case EXP_CNT: {
767 // If there has been a mixture of export types, then a waitcnt exp(0) is
768 // required.
769 if (MixedExpTypes)
770 return true;
771 int NumEventTypes = 0;
772 if (EventUBs[EXP_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
773 EventUBs[EXP_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
774 NumEventTypes++;
775 }
776 if (EventUBs[GDS_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
777 EventUBs[GDS_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
778 NumEventTypes++;
779 }
780 if (EventUBs[VMW_GPR_LOCK] > ScoreLBs[EXP_CNT] &&
781 EventUBs[VMW_GPR_LOCK] <= ScoreUBs[EXP_CNT]) {
782 NumEventTypes++;
783 }
784 if (EventUBs[EXP_PARAM_ACCESS] > ScoreLBs[EXP_CNT] &&
785 EventUBs[EXP_PARAM_ACCESS] <= ScoreUBs[EXP_CNT]) {
786 NumEventTypes++;
787 }
788
789 if (EventUBs[EXP_POS_ACCESS] > ScoreLBs[EXP_CNT] &&
790 EventUBs[EXP_POS_ACCESS] <= ScoreUBs[EXP_CNT]) {
791 NumEventTypes++;
792 }
793
794 if (NumEventTypes <= 1) {
795 return false;
796 }
797 break;
798 }
799 default:
800 break;
801 }
802 return true;
803}
804
805INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
806 false)
807INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
808 false)
809
810char SIInsertWaitcnts::ID = 0;
811
812char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID;
813
814FunctionPass *llvm::createSIInsertWaitcntsPass() {
815 return new SIInsertWaitcnts();
816}
817
818static bool readsVCCZ(const MachineInstr &MI) {
819 unsigned Opc = MI.getOpcode();
820 return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
821 !MI.getOperand(1).isUndef();
822}
823
824/// \brief Generate s_waitcnt instruction to be placed before cur_Inst.
825/// Instructions of a given type are returned in order,
826/// but instructions of different types can complete out of order.
827/// We rely on this in-order completion
828/// and simply assign a score to the memory access instructions.
829/// We keep track of the active "score bracket" to determine
830/// if an access of a memory read requires an s_waitcnt
831/// and if so what the value of each counter is.
832/// The "score bracket" is bound by the lower bound and upper bound
833/// scores (*_score_LB and *_score_ub respectively).
834MachineInstr *SIInsertWaitcnts::generateSWaitCntInstBefore(
835 MachineInstr &MI, BlockWaitcntBrackets *ScoreBrackets) {
836 // To emit, or not to emit - that's the question!
837 // Start with an assumption that there is no need to emit.
838 unsigned int EmitSwaitcnt = 0;
839 // s_waitcnt instruction to return; default is NULL.
840 MachineInstr *SWaitInst = nullptr;
841 // No need to wait before phi. If a phi-move exists, then the wait should
842 // has been inserted before the move. If a phi-move does not exist, then
843 // wait should be inserted before the real use. The same is true for
844 // sc-merge. It is not a coincident that all these cases correspond to the
845 // instructions that are skipped in the assembling loop.
846 bool NeedLineMapping = false; // TODO: Check on this.
847 if (MI.isDebugValue() &&
848 // TODO: any other opcode?
849 !NeedLineMapping) {
850 return SWaitInst;
851 }
852
853 // See if an s_waitcnt is forced at block entry, or is needed at
854 // program end.
855 if (ScoreBrackets->getWaitAtBeginning()) {
856 // Note that we have already cleared the state, so we don't need to update
857 // it.
858 ScoreBrackets->clearWaitAtBeginning();
859 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
860 T = (enum InstCounterType)(T + 1)) {
861 EmitSwaitcnt |= CNT_MASK(T);
862 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
863 }
864 }
865
866 // See if this instruction has a forced S_WAITCNT VM.
867 // TODO: Handle other cases of NeedsWaitcntVmBefore()
868 else if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
869 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
870 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL) {
871 EmitSwaitcnt |=
872 ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
873 }
874
875 // All waits must be resolved at call return.
876 // NOTE: this could be improved with knowledge of all call sites or
877 // with knowledge of the called routines.
878 if (MI.getOpcode() == AMDGPU::RETURN ||
Mark Searles11d0a042017-05-31 16:44:23 +0000879 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
880 MI.getOpcode() == AMDGPU::S_SETPC_B64_return) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000881 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
882 T = (enum InstCounterType)(T + 1)) {
883 if (ScoreBrackets->getScoreUB(T) > ScoreBrackets->getScoreLB(T)) {
884 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
885 EmitSwaitcnt |= CNT_MASK(T);
886 }
887 }
888 }
889 // Resolve vm waits before gs-done.
890 else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
891 MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
892 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) ==
893 AMDGPU::SendMsg::ID_GS_DONE)) {
894 if (ScoreBrackets->getScoreUB(VM_CNT) > ScoreBrackets->getScoreLB(VM_CNT)) {
895 ScoreBrackets->setScoreLB(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
896 EmitSwaitcnt |= CNT_MASK(VM_CNT);
897 }
898 }
899#if 0 // TODO: the following blocks of logic when we have fence.
900 else if (MI.getOpcode() == SC_FENCE) {
901 const unsigned int group_size =
902 context->shader_info->GetMaxThreadGroupSize();
903 // group_size == 0 means thread group size is unknown at compile time
904 const bool group_is_multi_wave =
905 (group_size == 0 || group_size > target_info->GetWaveFrontSize());
906 const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
907
908 for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
909 SCRegType src_type = Inst->GetSrcType(i);
910 switch (src_type) {
911 case SCMEM_LDS:
912 if (group_is_multi_wave ||
Evgeny Mankovbf975172017-08-16 16:47:29 +0000913 context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000914 EmitSwaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
915 ScoreBrackets->getScoreUB(LGKM_CNT));
916 // LDS may have to wait for VM_CNT after buffer load to LDS
917 if (target_info->HasBufferLoadToLDS()) {
918 EmitSwaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
919 ScoreBrackets->getScoreUB(VM_CNT));
920 }
921 }
922 break;
923
924 case SCMEM_GDS:
925 if (group_is_multi_wave || fence_is_global) {
926 EmitSwaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000927 ScoreBrackets->getScoreUB(EXP_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000928 EmitSwaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000929 ScoreBrackets->getScoreUB(LGKM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000930 }
931 break;
932
933 case SCMEM_UAV:
934 case SCMEM_TFBUF:
935 case SCMEM_RING:
936 case SCMEM_SCATTER:
937 if (group_is_multi_wave || fence_is_global) {
938 EmitSwaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000939 ScoreBrackets->getScoreUB(EXP_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000940 EmitSwaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000941 ScoreBrackets->getScoreUB(VM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000942 }
943 break;
944
945 case SCMEM_SCRATCH:
946 default:
947 break;
948 }
949 }
950 }
951#endif
952
953 // Export & GDS instructions do not read the EXEC mask until after the export
954 // is granted (which can occur well after the instruction is issued).
955 // The shader program must flush all EXP operations on the export-count
956 // before overwriting the EXEC mask.
957 else {
958 if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
959 // Export and GDS are tracked individually, either may trigger a waitcnt
960 // for EXEC.
961 EmitSwaitcnt |= ScoreBrackets->updateByWait(
962 EXP_CNT, ScoreBrackets->getEventUB(EXP_GPR_LOCK));
963 EmitSwaitcnt |= ScoreBrackets->updateByWait(
964 EXP_CNT, ScoreBrackets->getEventUB(EXP_PARAM_ACCESS));
965 EmitSwaitcnt |= ScoreBrackets->updateByWait(
966 EXP_CNT, ScoreBrackets->getEventUB(EXP_POS_ACCESS));
967 EmitSwaitcnt |= ScoreBrackets->updateByWait(
968 EXP_CNT, ScoreBrackets->getEventUB(GDS_GPR_LOCK));
969 }
970
971#if 0 // TODO: the following code to handle CALL.
972 // The argument passing for CALLs should suffice for VM_CNT and LGKM_CNT.
973 // However, there is a problem with EXP_CNT, because the call cannot
974 // easily tell if a register is used in the function, and if it did, then
975 // the referring instruction would have to have an S_WAITCNT, which is
976 // dependent on all call sites. So Instead, force S_WAITCNT for EXP_CNTs
977 // before the call.
978 if (MI.getOpcode() == SC_CALL) {
979 if (ScoreBrackets->getScoreUB(EXP_CNT) >
Evgeny Mankovbf975172017-08-16 16:47:29 +0000980 ScoreBrackets->getScoreLB(EXP_CNT)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000981 ScoreBrackets->setScoreLB(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
982 EmitSwaitcnt |= CNT_MASK(EXP_CNT);
983 }
984 }
985#endif
986
Matt Arsenault0ed39d32017-07-21 18:54:54 +0000987 // FIXME: Should not be relying on memoperands.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000988 // Look at the source operands of every instruction to see if
989 // any of them results from a previous memory operation that affects
990 // its current usage. If so, an s_waitcnt instruction needs to be
991 // emitted.
992 // If the source operand was defined by a load, add the s_waitcnt
993 // instruction.
994 for (const MachineMemOperand *Memop : MI.memoperands()) {
995 unsigned AS = Memop->getAddrSpace();
996 if (AS != AMDGPUASI.LOCAL_ADDRESS)
997 continue;
998 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
999 // VM_CNT is only relevant to vgpr or LDS.
1000 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1001 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1002 }
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001003
Kannan Narayananacb089e2017-04-12 03:25:12 +00001004 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1005 const MachineOperand &Op = MI.getOperand(I);
1006 const MachineRegisterInfo &MRIA = *MRI;
1007 RegInterval Interval =
1008 ScoreBrackets->getRegInterval(&MI, TII, MRI, TRI, I, false);
1009 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1010 if (TRI->isVGPR(MRIA, Op.getReg())) {
1011 // VM_CNT is only relevant to vgpr or LDS.
1012 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1013 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1014 }
1015 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1016 LGKM_CNT, ScoreBrackets->getRegScore(RegNo, LGKM_CNT));
1017 }
1018 }
1019 // End of for loop that looks at all source operands to decide vm_wait_cnt
1020 // and lgk_wait_cnt.
1021
1022 // Two cases are handled for destination operands:
1023 // 1) If the destination operand was defined by a load, add the s_waitcnt
1024 // instruction to guarantee the right WAW order.
1025 // 2) If a destination operand that was used by a recent export/store ins,
1026 // add s_waitcnt on exp_cnt to guarantee the WAR order.
1027 if (MI.mayStore()) {
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001028 // FIXME: Should not be relying on memoperands.
Kannan Narayananacb089e2017-04-12 03:25:12 +00001029 for (const MachineMemOperand *Memop : MI.memoperands()) {
1030 unsigned AS = Memop->getAddrSpace();
1031 if (AS != AMDGPUASI.LOCAL_ADDRESS)
1032 continue;
1033 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
1034 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1035 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1036 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1037 EXP_CNT, ScoreBrackets->getRegScore(RegNo, EXP_CNT));
1038 }
1039 }
1040 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1041 MachineOperand &Def = MI.getOperand(I);
1042 const MachineRegisterInfo &MRIA = *MRI;
1043 RegInterval Interval =
1044 ScoreBrackets->getRegInterval(&MI, TII, MRI, TRI, I, true);
1045 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1046 if (TRI->isVGPR(MRIA, Def.getReg())) {
1047 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1048 VM_CNT, ScoreBrackets->getRegScore(RegNo, VM_CNT));
1049 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1050 EXP_CNT, ScoreBrackets->getRegScore(RegNo, EXP_CNT));
1051 }
1052 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1053 LGKM_CNT, ScoreBrackets->getRegScore(RegNo, LGKM_CNT));
1054 }
1055 } // End of for loop that looks at all dest operands.
1056 }
1057
Kannan Narayananacb089e2017-04-12 03:25:12 +00001058 // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1059 // occurs before the instruction. Doing it here prevents any additional
1060 // S_WAITCNTs from being emitted if the instruction was marked as
1061 // requiring a WAITCNT beforehand.
Konstantin Zhuravlyovbe6c0ca2017-06-02 17:40:26 +00001062 if (MI.getOpcode() == AMDGPU::S_BARRIER &&
1063 !ST->hasAutoWaitcntBeforeBarrier()) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001064 EmitSwaitcnt |=
1065 ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
1066 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1067 EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
1068 EmitSwaitcnt |= ScoreBrackets->updateByWait(
1069 LGKM_CNT, ScoreBrackets->getScoreUB(LGKM_CNT));
1070 }
1071
1072 // TODO: Remove this work-around, enable the assert for Bug 457939
1073 // after fixing the scheduler. Also, the Shader Compiler code is
1074 // independent of target.
1075 if (readsVCCZ(MI) && ST->getGeneration() <= SISubtarget::SEA_ISLANDS) {
1076 if (ScoreBrackets->getScoreLB(LGKM_CNT) <
1077 ScoreBrackets->getScoreUB(LGKM_CNT) &&
1078 ScoreBrackets->hasPendingSMEM()) {
1079 // Wait on everything, not just LGKM. vccz reads usually come from
1080 // terminators, and we always wait on everything at the end of the
1081 // block, so if we only wait on LGKM here, we might end up with
1082 // another s_waitcnt inserted right after this if there are non-LGKM
1083 // instructions still outstanding.
1084 ForceZero = true;
1085 EmitSwaitcnt = true;
1086 }
1087 }
1088
1089 // Does this operand processing indicate s_wait counter update?
Mark Searlesa84d2342017-12-07 20:36:39 +00001090 if (EmitSwaitcnt || ForceEmit()) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001091 int CntVal[NUM_INST_CNTS];
1092
1093 bool UseDefaultWaitcntStrategy = true;
1094 if (ForceZero) {
1095 // Force all waitcnts to 0.
1096 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1097 T = (enum InstCounterType)(T + 1)) {
1098 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
1099 }
1100 CntVal[VM_CNT] = 0;
1101 CntVal[EXP_CNT] = 0;
1102 CntVal[LGKM_CNT] = 0;
1103 UseDefaultWaitcntStrategy = false;
1104 }
1105
1106 if (UseDefaultWaitcntStrategy) {
1107 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1108 T = (enum InstCounterType)(T + 1)) {
1109 if (EmitSwaitcnt & CNT_MASK(T)) {
1110 int Delta =
1111 ScoreBrackets->getScoreUB(T) - ScoreBrackets->getScoreLB(T);
1112 int MaxDelta = ScoreBrackets->getWaitCountMax(T);
1113 if (Delta >= MaxDelta) {
1114 Delta = -1;
1115 if (T != EXP_CNT) {
1116 ScoreBrackets->setScoreLB(
1117 T, ScoreBrackets->getScoreUB(T) - MaxDelta);
1118 }
1119 EmitSwaitcnt &= ~CNT_MASK(T);
1120 }
1121 CntVal[T] = Delta;
1122 } else {
1123 // If we are not waiting for a particular counter then encode
1124 // it as -1 which means "don't care."
1125 CntVal[T] = -1;
1126 }
1127 }
1128 }
1129
1130 // If we are not waiting on any counter we can skip the wait altogether.
Mark Searlesa84d2342017-12-07 20:36:39 +00001131 if (EmitSwaitcnt != 0 || ForceEmit()) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001132 MachineInstr *OldWaitcnt = ScoreBrackets->getWaitcnt();
1133 int Imm = (!OldWaitcnt) ? 0 : OldWaitcnt->getOperand(0).getImm();
1134 if (!OldWaitcnt || (AMDGPU::decodeVmcnt(IV, Imm) !=
1135 (CntVal[VM_CNT] & AMDGPU::getVmcntBitMask(IV))) ||
1136 (AMDGPU::decodeExpcnt(IV, Imm) !=
1137 (CntVal[EXP_CNT] & AMDGPU::getExpcntBitMask(IV))) ||
1138 (AMDGPU::decodeLgkmcnt(IV, Imm) !=
1139 (CntVal[LGKM_CNT] & AMDGPU::getLgkmcntBitMask(IV)))) {
1140 MachineLoop *ContainingLoop = MLI->getLoopFor(MI.getParent());
1141 if (ContainingLoop) {
Kannan Narayanan5e73b042017-05-05 21:10:17 +00001142 MachineBasicBlock *TBB = ContainingLoop->getHeader();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001143 BlockWaitcntBrackets *ScoreBracket =
1144 BlockWaitcntBracketsMap[TBB].get();
1145 if (!ScoreBracket) {
1146 assert(BlockVisitedSet.find(TBB) == BlockVisitedSet.end());
Eugene Zelenko59e12822017-08-08 00:47:13 +00001147 BlockWaitcntBracketsMap[TBB] =
1148 llvm::make_unique<BlockWaitcntBrackets>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001149 ScoreBracket = BlockWaitcntBracketsMap[TBB].get();
1150 }
1151 ScoreBracket->setRevisitLoop(true);
1152 DEBUG(dbgs() << "set-revisit: block"
Kannan Narayanan5e73b042017-05-05 21:10:17 +00001153 << ContainingLoop->getHeader()->getNumber() << '\n';);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001154 }
1155 }
1156
1157 // Update an existing waitcount, or make a new one.
1158 MachineFunction &MF = *MI.getParent()->getParent();
1159 if (OldWaitcnt && OldWaitcnt->getOpcode() != AMDGPU::S_WAITCNT) {
1160 SWaitInst = OldWaitcnt;
1161 } else {
1162 SWaitInst = MF.CreateMachineInstr(TII->get(AMDGPU::S_WAITCNT),
1163 MI.getDebugLoc());
1164 CompilerGeneratedWaitcntSet.insert(SWaitInst);
1165 }
1166
Mark Searlesa84d2342017-12-07 20:36:39 +00001167 if (!EmitSwaitcnt) {
1168 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1169 T = (enum InstCounterType)(T + 1)) {
1170 if (ForceSwaitcnt[T] > 0 ) {
1171 DEBUG(dbgs() << "ForceSwaitcnt[" << T << "]: "
1172 << ForceSwaitcnt[T] << '\n';);
1173 }
1174 }
1175 }
1176
Kannan Narayananacb089e2017-04-12 03:25:12 +00001177 const MachineOperand &Op =
1178 MachineOperand::CreateImm(AMDGPU::encodeWaitcnt(
Mark Searlesa84d2342017-12-07 20:36:39 +00001179 IV,
1180 (ForceSwaitcnt[VM_CNT] > 0) ? 0 : CntVal[VM_CNT],
1181 (ForceSwaitcnt[EXP_CNT] > 0) ? 0 : CntVal[EXP_CNT],
1182 (ForceSwaitcnt[LGKM_CNT] > 0) ? 0 : CntVal[LGKM_CNT]));
Kannan Narayananacb089e2017-04-12 03:25:12 +00001183 SWaitInst->addOperand(MF, Op);
1184
Mark Searlesa84d2342017-12-07 20:36:39 +00001185 if (!EmitSwaitcnt) {
1186 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1187 T = (enum InstCounterType)(T + 1)) {
1188 --ForceSwaitcnt[T];
1189 }
1190 }
1191
Kannan Narayananacb089e2017-04-12 03:25:12 +00001192 if (CntVal[EXP_CNT] == 0) {
1193 ScoreBrackets->setMixedExpTypes(false);
1194 }
1195 }
1196 }
1197
1198 return SWaitInst;
1199}
1200
1201void SIInsertWaitcnts::insertWaitcntBeforeCF(MachineBasicBlock &MBB,
1202 MachineInstr *Waitcnt) {
1203 if (MBB.empty()) {
1204 MBB.push_back(Waitcnt);
1205 return;
1206 }
1207
1208 MachineBasicBlock::iterator It = MBB.end();
1209 MachineInstr *MI = &*(--It);
1210 if (MI->isBranch()) {
1211 MBB.insert(It, Waitcnt);
1212 } else {
1213 MBB.push_back(Waitcnt);
1214 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001215}
1216
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001217// This is a flat memory operation. Check to see if it has memory
1218// tokens for both LDS and Memory, and if so mark it as a flat.
1219bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
1220 if (MI.memoperands_empty())
1221 return true;
1222
1223 for (const MachineMemOperand *Memop : MI.memoperands()) {
1224 unsigned AS = Memop->getAddrSpace();
1225 if (AS == AMDGPUASI.LOCAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS)
1226 return true;
1227 }
1228
1229 return false;
1230}
1231
Kannan Narayananacb089e2017-04-12 03:25:12 +00001232void SIInsertWaitcnts::updateEventWaitCntAfter(
1233 MachineInstr &Inst, BlockWaitcntBrackets *ScoreBrackets) {
1234 // Now look at the instruction opcode. If it is a memory access
1235 // instruction, update the upper-bound of the appropriate counter's
1236 // bracket and the destination operand scores.
1237 // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001238 if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001239 if (TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001240 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1241 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1242 } else {
1243 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1244 }
1245 } else if (TII->isFLAT(Inst)) {
1246 assert(Inst.mayLoad() || Inst.mayStore());
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001247
1248 if (TII->usesVM_CNT(Inst))
1249 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1250
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001251 if (TII->usesLGKM_CNT(Inst)) {
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001252 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001253
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001254 // This is a flat memory operation, so note it - it will require
1255 // that both the VM and LGKM be flushed to zero if it is pending when
1256 // a VM or LGKM dependency occurs.
1257 if (mayAccessLDSThroughFlat(Inst))
1258 ScoreBrackets->setPendingFlat();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001259 }
1260 } else if (SIInstrInfo::isVMEM(Inst) &&
1261 // TODO: get a better carve out.
1262 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1 &&
1263 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_SC &&
1264 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_VOL) {
1265 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1266 if ( // TODO: assumed yes -- target_info->MemWriteNeedsExpWait() &&
Mark Searles11d0a042017-05-31 16:44:23 +00001267 (Inst.mayStore() || AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001268 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1269 }
1270 } else if (TII->isSMRD(Inst)) {
1271 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1272 } else {
1273 switch (Inst.getOpcode()) {
1274 case AMDGPU::S_SENDMSG:
1275 case AMDGPU::S_SENDMSGHALT:
1276 ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1277 break;
1278 case AMDGPU::EXP:
1279 case AMDGPU::EXP_DONE: {
1280 int Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1281 if (Imm >= 32 && Imm <= 63)
1282 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1283 else if (Imm >= 12 && Imm <= 15)
1284 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1285 else
1286 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1287 break;
1288 }
1289 case AMDGPU::S_MEMTIME:
1290 case AMDGPU::S_MEMREALTIME:
1291 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1292 break;
1293 default:
1294 break;
1295 }
1296 }
1297}
1298
1299void SIInsertWaitcnts::mergeInputScoreBrackets(MachineBasicBlock &Block) {
1300 BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&Block].get();
1301 int32_t MaxPending[NUM_INST_CNTS] = {0};
1302 int32_t MaxFlat[NUM_INST_CNTS] = {0};
1303 bool MixedExpTypes = false;
1304
1305 // Clear the score bracket state.
1306 ScoreBrackets->clear();
1307
1308 // Compute the number of pending elements on block entry.
1309
1310 // IMPORTANT NOTE: If iterative handling of loops is added, the code will
1311 // need to handle single BBs with backedges to themselves. This means that
1312 // they will need to retain and not clear their initial state.
1313
1314 // See if there are any uninitialized predecessors. If so, emit an
1315 // s_waitcnt 0 at the beginning of the block.
1316 for (MachineBasicBlock *pred : Block.predecessors()) {
1317 BlockWaitcntBrackets *PredScoreBrackets =
1318 BlockWaitcntBracketsMap[pred].get();
1319 bool Visited = BlockVisitedSet.find(pred) != BlockVisitedSet.end();
1320 if (!Visited || PredScoreBrackets->getWaitAtBeginning()) {
Tim Corringham6c6d5e22017-12-04 12:30:49 +00001321 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001322 }
1323 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1324 T = (enum InstCounterType)(T + 1)) {
1325 int span =
1326 PredScoreBrackets->getScoreUB(T) - PredScoreBrackets->getScoreLB(T);
1327 MaxPending[T] = std::max(MaxPending[T], span);
1328 span =
1329 PredScoreBrackets->pendingFlat(T) - PredScoreBrackets->getScoreLB(T);
1330 MaxFlat[T] = std::max(MaxFlat[T], span);
1331 }
1332
1333 MixedExpTypes |= PredScoreBrackets->mixedExpTypes();
1334 }
1335
1336 // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1337 // Also handle kills for exit block.
1338 if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1339 for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1340 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1341 T = (enum InstCounterType)(T + 1)) {
1342 int Span = KillWaitBrackets[I]->getScoreUB(T) -
1343 KillWaitBrackets[I]->getScoreLB(T);
1344 MaxPending[T] = std::max(MaxPending[T], Span);
1345 Span = KillWaitBrackets[I]->pendingFlat(T) -
1346 KillWaitBrackets[I]->getScoreLB(T);
1347 MaxFlat[T] = std::max(MaxFlat[T], Span);
1348 }
1349
1350 MixedExpTypes |= KillWaitBrackets[I]->mixedExpTypes();
1351 }
1352 }
1353
1354 // Special handling for GDS_GPR_LOCK and EXP_GPR_LOCK.
1355 for (MachineBasicBlock *Pred : Block.predecessors()) {
1356 BlockWaitcntBrackets *PredScoreBrackets =
1357 BlockWaitcntBracketsMap[Pred].get();
1358 bool Visited = BlockVisitedSet.find(Pred) != BlockVisitedSet.end();
1359 if (!Visited || PredScoreBrackets->getWaitAtBeginning()) {
Tim Corringham6c6d5e22017-12-04 12:30:49 +00001360 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001361 }
1362
1363 int GDSSpan = PredScoreBrackets->getEventUB(GDS_GPR_LOCK) -
1364 PredScoreBrackets->getScoreLB(EXP_CNT);
1365 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], GDSSpan);
1366 int EXPSpan = PredScoreBrackets->getEventUB(EXP_GPR_LOCK) -
1367 PredScoreBrackets->getScoreLB(EXP_CNT);
1368 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], EXPSpan);
1369 }
1370
1371 // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1372 if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1373 for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1374 int GDSSpan = KillWaitBrackets[I]->getEventUB(GDS_GPR_LOCK) -
1375 KillWaitBrackets[I]->getScoreLB(EXP_CNT);
1376 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], GDSSpan);
1377 int EXPSpan = KillWaitBrackets[I]->getEventUB(EXP_GPR_LOCK) -
1378 KillWaitBrackets[I]->getScoreLB(EXP_CNT);
1379 MaxPending[EXP_CNT] = std::max(MaxPending[EXP_CNT], EXPSpan);
1380 }
1381 }
1382
1383#if 0
1384 // LC does not (unlike) add a waitcnt at beginning. Leaving it as marker.
1385 // TODO: how does LC distinguish between function entry and main entry?
1386 // If this is the entry to a function, force a wait.
1387 MachineBasicBlock &Entry = Block.getParent()->front();
1388 if (Entry.getNumber() == Block.getNumber()) {
1389 ScoreBrackets->setWaitAtBeginning();
1390 return;
1391 }
1392#endif
1393
1394 // Now set the current Block's brackets to the largest ending bracket.
1395 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1396 T = (enum InstCounterType)(T + 1)) {
1397 ScoreBrackets->setScoreUB(T, MaxPending[T]);
1398 ScoreBrackets->setScoreLB(T, 0);
1399 ScoreBrackets->setLastFlat(T, MaxFlat[T]);
1400 }
1401
1402 ScoreBrackets->setMixedExpTypes(MixedExpTypes);
1403
1404 // Set the register scoreboard.
1405 for (MachineBasicBlock *Pred : Block.predecessors()) {
1406 if (BlockVisitedSet.find(Pred) == BlockVisitedSet.end()) {
Tim Corringham6c6d5e22017-12-04 12:30:49 +00001407 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001408 }
1409
1410 BlockWaitcntBrackets *PredScoreBrackets =
1411 BlockWaitcntBracketsMap[Pred].get();
1412
1413 // Now merge the gpr_reg_score information
1414 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1415 T = (enum InstCounterType)(T + 1)) {
1416 int PredLB = PredScoreBrackets->getScoreLB(T);
1417 int PredUB = PredScoreBrackets->getScoreUB(T);
1418 if (PredLB < PredUB) {
1419 int PredScale = MaxPending[T] - PredUB;
1420 // Merge vgpr scores.
1421 for (int J = 0; J <= PredScoreBrackets->getMaxVGPR(); J++) {
1422 int PredRegScore = PredScoreBrackets->getRegScore(J, T);
1423 if (PredRegScore <= PredLB)
1424 continue;
1425 int NewRegScore = PredScale + PredRegScore;
1426 ScoreBrackets->setRegScore(
1427 J, T, std::max(ScoreBrackets->getRegScore(J, T), NewRegScore));
1428 }
1429 // Also need to merge sgpr scores for lgkm_cnt.
1430 if (T == LGKM_CNT) {
1431 for (int J = 0; J <= PredScoreBrackets->getMaxSGPR(); J++) {
1432 int PredRegScore =
1433 PredScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
1434 if (PredRegScore <= PredLB)
1435 continue;
1436 int NewRegScore = PredScale + PredRegScore;
1437 ScoreBrackets->setRegScore(
1438 J + NUM_ALL_VGPRS, LGKM_CNT,
1439 std::max(
1440 ScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT),
1441 NewRegScore));
1442 }
1443 }
1444 }
1445 }
1446
1447 // Also merge the WaitEvent information.
1448 ForAllWaitEventType(W) {
1449 enum InstCounterType T = PredScoreBrackets->eventCounter(W);
1450 int PredEventUB = PredScoreBrackets->getEventUB(W);
1451 if (PredEventUB > PredScoreBrackets->getScoreLB(T)) {
1452 int NewEventUB =
1453 MaxPending[T] + PredEventUB - PredScoreBrackets->getScoreUB(T);
1454 if (NewEventUB > 0) {
1455 ScoreBrackets->setEventUB(
1456 W, std::max(ScoreBrackets->getEventUB(W), NewEventUB));
1457 }
1458 }
1459 }
1460 }
1461
1462 // TODO: Is SC Block->IsMainExit() same as Block.succ_empty()?
1463 // Set the register scoreboard.
1464 if (Block.succ_empty() && !KillWaitBrackets.empty()) {
1465 for (unsigned int I = 0; I < KillWaitBrackets.size(); I++) {
1466 // Now merge the gpr_reg_score information.
1467 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1468 T = (enum InstCounterType)(T + 1)) {
1469 int PredLB = KillWaitBrackets[I]->getScoreLB(T);
1470 int PredUB = KillWaitBrackets[I]->getScoreUB(T);
1471 if (PredLB < PredUB) {
1472 int PredScale = MaxPending[T] - PredUB;
1473 // Merge vgpr scores.
1474 for (int J = 0; J <= KillWaitBrackets[I]->getMaxVGPR(); J++) {
1475 int PredRegScore = KillWaitBrackets[I]->getRegScore(J, T);
1476 if (PredRegScore <= PredLB)
1477 continue;
1478 int NewRegScore = PredScale + PredRegScore;
1479 ScoreBrackets->setRegScore(
1480 J, T, std::max(ScoreBrackets->getRegScore(J, T), NewRegScore));
1481 }
1482 // Also need to merge sgpr scores for lgkm_cnt.
1483 if (T == LGKM_CNT) {
1484 for (int J = 0; J <= KillWaitBrackets[I]->getMaxSGPR(); J++) {
1485 int PredRegScore =
1486 KillWaitBrackets[I]->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
1487 if (PredRegScore <= PredLB)
1488 continue;
1489 int NewRegScore = PredScale + PredRegScore;
1490 ScoreBrackets->setRegScore(
1491 J + NUM_ALL_VGPRS, LGKM_CNT,
1492 std::max(
1493 ScoreBrackets->getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT),
1494 NewRegScore));
1495 }
1496 }
1497 }
1498 }
1499
1500 // Also merge the WaitEvent information.
1501 ForAllWaitEventType(W) {
1502 enum InstCounterType T = KillWaitBrackets[I]->eventCounter(W);
1503 int PredEventUB = KillWaitBrackets[I]->getEventUB(W);
1504 if (PredEventUB > KillWaitBrackets[I]->getScoreLB(T)) {
1505 int NewEventUB =
1506 MaxPending[T] + PredEventUB - KillWaitBrackets[I]->getScoreUB(T);
1507 if (NewEventUB > 0) {
1508 ScoreBrackets->setEventUB(
1509 W, std::max(ScoreBrackets->getEventUB(W), NewEventUB));
1510 }
1511 }
1512 }
1513 }
1514 }
1515
1516 // Special case handling of GDS_GPR_LOCK and EXP_GPR_LOCK. Merge this for the
1517 // sequencing predecessors, because changes to EXEC require waitcnts due to
1518 // the delayed nature of these operations.
1519 for (MachineBasicBlock *Pred : Block.predecessors()) {
1520 if (BlockVisitedSet.find(Pred) == BlockVisitedSet.end()) {
Tim Corringham6c6d5e22017-12-04 12:30:49 +00001521 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001522 }
1523
1524 BlockWaitcntBrackets *PredScoreBrackets =
1525 BlockWaitcntBracketsMap[Pred].get();
1526
1527 int pred_gds_ub = PredScoreBrackets->getEventUB(GDS_GPR_LOCK);
1528 if (pred_gds_ub > PredScoreBrackets->getScoreLB(EXP_CNT)) {
1529 int new_gds_ub = MaxPending[EXP_CNT] + pred_gds_ub -
1530 PredScoreBrackets->getScoreUB(EXP_CNT);
1531 if (new_gds_ub > 0) {
1532 ScoreBrackets->setEventUB(
1533 GDS_GPR_LOCK,
1534 std::max(ScoreBrackets->getEventUB(GDS_GPR_LOCK), new_gds_ub));
1535 }
1536 }
1537 int pred_exp_ub = PredScoreBrackets->getEventUB(EXP_GPR_LOCK);
1538 if (pred_exp_ub > PredScoreBrackets->getScoreLB(EXP_CNT)) {
1539 int new_exp_ub = MaxPending[EXP_CNT] + pred_exp_ub -
1540 PredScoreBrackets->getScoreUB(EXP_CNT);
1541 if (new_exp_ub > 0) {
1542 ScoreBrackets->setEventUB(
1543 EXP_GPR_LOCK,
1544 std::max(ScoreBrackets->getEventUB(EXP_GPR_LOCK), new_exp_ub));
1545 }
1546 }
1547 }
1548}
1549
1550/// Return the "bottom" block of a loop. This differs from
1551/// MachineLoop::getBottomBlock in that it works even if the loop is
1552/// discontiguous.
1553MachineBasicBlock *SIInsertWaitcnts::loopBottom(const MachineLoop *Loop) {
1554 MachineBasicBlock *Bottom = Loop->getHeader();
1555 for (MachineBasicBlock *MBB : Loop->blocks())
1556 if (MBB->getNumber() > Bottom->getNumber())
1557 Bottom = MBB;
1558 return Bottom;
1559}
1560
1561// Generate s_waitcnt instructions where needed.
1562void SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1563 MachineBasicBlock &Block) {
1564 // Initialize the state information.
1565 mergeInputScoreBrackets(Block);
1566
1567 BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&Block].get();
1568
1569 DEBUG({
Mark Searlesa84d2342017-12-07 20:36:39 +00001570 dbgs() << "*** Block" << Block.getNumber() << " ***";
Kannan Narayananacb089e2017-04-12 03:25:12 +00001571 ScoreBrackets->dump();
1572 });
1573
Kannan Narayananacb089e2017-04-12 03:25:12 +00001574 // Walk over the instructions.
1575 for (MachineBasicBlock::iterator Iter = Block.begin(), E = Block.end();
1576 Iter != E;) {
1577 MachineInstr &Inst = *Iter;
1578 // Remove any previously existing waitcnts.
1579 if (Inst.getOpcode() == AMDGPU::S_WAITCNT) {
1580 // TODO: Register the old waitcnt and optimize the following waitcnts.
1581 // Leaving the previously existing waitcnts is conservatively correct.
1582 if (CompilerGeneratedWaitcntSet.find(&Inst) ==
1583 CompilerGeneratedWaitcntSet.end())
1584 ++Iter;
1585 else {
1586 ScoreBrackets->setWaitcnt(&Inst);
1587 ++Iter;
1588 Inst.removeFromParent();
1589 }
1590 continue;
1591 }
1592
1593 // Kill instructions generate a conditional branch to the endmain block.
1594 // Merge the current waitcnt state into the endmain block information.
1595 // TODO: Are there other flavors of KILL instruction?
1596 if (Inst.getOpcode() == AMDGPU::KILL) {
1597 addKillWaitBracket(ScoreBrackets);
1598 }
1599
1600 bool VCCZBugWorkAround = false;
1601 if (readsVCCZ(Inst) &&
1602 (VCCZBugHandledSet.find(&Inst) == VCCZBugHandledSet.end())) {
1603 if (ScoreBrackets->getScoreLB(LGKM_CNT) <
1604 ScoreBrackets->getScoreUB(LGKM_CNT) &&
1605 ScoreBrackets->hasPendingSMEM()) {
1606 if (ST->getGeneration() <= SISubtarget::SEA_ISLANDS)
1607 VCCZBugWorkAround = true;
1608 }
1609 }
1610
1611 // Generate an s_waitcnt instruction to be placed before
1612 // cur_Inst, if needed.
1613 MachineInstr *SWaitInst = generateSWaitCntInstBefore(Inst, ScoreBrackets);
1614
1615 if (SWaitInst) {
1616 Block.insert(Inst, SWaitInst);
1617 if (ScoreBrackets->getWaitcnt() != SWaitInst) {
1618 DEBUG(dbgs() << "insertWaitcntInBlock\n"
1619 << "Old Instr: " << Inst << '\n'
1620 << "New Instr: " << *SWaitInst << '\n';);
1621 }
1622 }
1623
1624 updateEventWaitCntAfter(Inst, ScoreBrackets);
1625
1626#if 0 // TODO: implement resource type check controlled by options with ub = LB.
1627 // If this instruction generates a S_SETVSKIP because it is an
1628 // indexed resource, and we are on Tahiti, then it will also force
1629 // an S_WAITCNT vmcnt(0)
1630 if (RequireCheckResourceType(Inst, context)) {
1631 // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1632 ScoreBrackets->setScoreLB(VM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +00001633 ScoreBrackets->getScoreUB(VM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +00001634 }
1635#endif
1636
1637 ScoreBrackets->clearWaitcnt();
1638
1639 if (SWaitInst) {
1640 DEBUG({ SWaitInst->print(dbgs() << '\n'); });
1641 }
1642 DEBUG({
Mark Searlesa84d2342017-12-07 20:36:39 +00001643 dbgs() << "Instr" << ++InstCnt << ": " << Inst;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001644 ScoreBrackets->dump();
1645 });
1646
1647 // Check to see if this is a GWS instruction. If so, and if this is CI or
1648 // VI, then the generated code sequence will include an S_WAITCNT 0.
1649 // TODO: Are these the only GWS instructions?
1650 if (Inst.getOpcode() == AMDGPU::DS_GWS_INIT ||
1651 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_V ||
1652 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_BR ||
1653 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_P ||
1654 Inst.getOpcode() == AMDGPU::DS_GWS_BARRIER) {
1655 // TODO: && context->target_info->GwsRequiresMemViolTest() ) {
1656 ScoreBrackets->updateByWait(VM_CNT, ScoreBrackets->getScoreUB(VM_CNT));
1657 ScoreBrackets->updateByWait(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
1658 ScoreBrackets->updateByWait(LGKM_CNT,
1659 ScoreBrackets->getScoreUB(LGKM_CNT));
1660 }
1661
1662 // TODO: Remove this work-around after fixing the scheduler and enable the
1663 // assert above.
1664 if (VCCZBugWorkAround) {
1665 // Restore the vccz bit. Any time a value is written to vcc, the vcc
1666 // bit is updated, so we can restore the bit by reading the value of
1667 // vcc and then writing it back to the register.
1668 BuildMI(Block, Inst, Inst.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
1669 AMDGPU::VCC)
1670 .addReg(AMDGPU::VCC);
1671 VCCZBugHandledSet.insert(&Inst);
1672 }
1673
Kannan Narayananacb089e2017-04-12 03:25:12 +00001674 ++Iter;
1675 }
1676
1677 // Check if we need to force convergence at loop footer.
1678 MachineLoop *ContainingLoop = MLI->getLoopFor(&Block);
1679 if (ContainingLoop && loopBottom(ContainingLoop) == &Block) {
1680 LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1681 WaitcntData->print();
1682 DEBUG(dbgs() << '\n';);
1683
1684 // The iterative waitcnt insertion algorithm aims for optimal waitcnt
1685 // placement and doesn't always guarantee convergence for a loop. Each
1686 // loop should take at most 2 iterations for it to converge naturally.
1687 // When this max is reached and result doesn't converge, we force
1688 // convergence by inserting a s_waitcnt at the end of loop footer.
1689 if (WaitcntData->getIterCnt() > 2) {
1690 // To ensure convergence, need to make wait events at loop footer be no
1691 // more than those from the previous iteration.
1692 // As a simplification, Instead of tracking individual scores and
1693 // generate the precise wait count, just wait on 0.
1694 bool HasPending = false;
1695 MachineInstr *SWaitInst = WaitcntData->getWaitcnt();
1696 for (enum InstCounterType T = VM_CNT; T < NUM_INST_CNTS;
1697 T = (enum InstCounterType)(T + 1)) {
1698 if (ScoreBrackets->getScoreUB(T) > ScoreBrackets->getScoreLB(T)) {
1699 ScoreBrackets->setScoreLB(T, ScoreBrackets->getScoreUB(T));
1700 HasPending = true;
1701 }
1702 }
1703
1704 if (HasPending) {
1705 if (!SWaitInst) {
1706 SWaitInst = Block.getParent()->CreateMachineInstr(
1707 TII->get(AMDGPU::S_WAITCNT), DebugLoc());
1708 CompilerGeneratedWaitcntSet.insert(SWaitInst);
1709 const MachineOperand &Op = MachineOperand::CreateImm(0);
1710 SWaitInst->addOperand(MF, Op);
1711#if 0 // TODO: Format the debug output
1712 OutputTransformBanner("insertWaitcntInBlock",0,"Create:",context);
1713 OutputTransformAdd(SWaitInst, context);
1714#endif
1715 }
1716#if 0 // TODO: ??
1717 _DEV( REPORTED_STATS->force_waitcnt_converge = 1; )
1718#endif
1719 }
1720
1721 if (SWaitInst) {
1722 DEBUG({
1723 SWaitInst->print(dbgs());
1724 dbgs() << "\nAdjusted score board:";
1725 ScoreBrackets->dump();
1726 });
1727
1728 // Add this waitcnt to the block. It is either newly created or
1729 // created in previous iterations and added back since block traversal
1730 // always remove waitcnt.
1731 insertWaitcntBeforeCF(Block, SWaitInst);
1732 WaitcntData->setWaitcnt(SWaitInst);
1733 }
1734 }
1735 }
1736}
1737
1738bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
1739 ST = &MF.getSubtarget<SISubtarget>();
1740 TII = ST->getInstrInfo();
1741 TRI = &TII->getRegisterInfo();
1742 MRI = &MF.getRegInfo();
1743 MLI = &getAnalysis<MachineLoopInfo>();
1744 IV = AMDGPU::IsaInfo::getIsaVersion(ST->getFeatureBits());
Mark Searles11d0a042017-05-31 16:44:23 +00001745 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001746 AMDGPUASI = ST->getAMDGPUAS();
1747
Mark Searlesa84d2342017-12-07 20:36:39 +00001748 ForceZero = ForceZeroFlag;
1749 ForceSwaitcnt[VM_CNT] = ForceVmFlag;
1750 ForceSwaitcnt[EXP_CNT] = ForceExpFlag;
1751 ForceSwaitcnt[LGKM_CNT] = ForceLgkmFlag;
1752
Kannan Narayananacb089e2017-04-12 03:25:12 +00001753 HardwareLimits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1754 HardwareLimits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1755 HardwareLimits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
1756
1757 HardwareLimits.NumVGPRsMax = ST->getAddressableNumVGPRs();
1758 HardwareLimits.NumSGPRsMax = ST->getAddressableNumSGPRs();
1759 assert(HardwareLimits.NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1760 assert(HardwareLimits.NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1761
1762 RegisterEncoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1763 RegisterEncoding.VGPRL =
1764 RegisterEncoding.VGPR0 + HardwareLimits.NumVGPRsMax - 1;
1765 RegisterEncoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1766 RegisterEncoding.SGPRL =
1767 RegisterEncoding.SGPR0 + HardwareLimits.NumSGPRsMax - 1;
1768
1769 // Walk over the blocks in reverse post-dominator order, inserting
1770 // s_waitcnt where needed.
1771 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1772 bool Modified = false;
1773 for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1774 I = RPOT.begin(),
1775 E = RPOT.end(), J = RPOT.begin();
1776 I != E;) {
1777 MachineBasicBlock &MBB = **I;
1778
1779 BlockVisitedSet.insert(&MBB);
1780
1781 BlockWaitcntBrackets *ScoreBrackets = BlockWaitcntBracketsMap[&MBB].get();
1782 if (!ScoreBrackets) {
Eugene Zelenko59e12822017-08-08 00:47:13 +00001783 BlockWaitcntBracketsMap[&MBB] = llvm::make_unique<BlockWaitcntBrackets>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001784 ScoreBrackets = BlockWaitcntBracketsMap[&MBB].get();
1785 }
1786 ScoreBrackets->setPostOrder(MBB.getNumber());
1787 MachineLoop *ContainingLoop = MLI->getLoopFor(&MBB);
1788 if (ContainingLoop && LoopWaitcntDataMap[ContainingLoop] == nullptr)
Eugene Zelenko59e12822017-08-08 00:47:13 +00001789 LoopWaitcntDataMap[ContainingLoop] = llvm::make_unique<LoopWaitcntData>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001790
1791 // If we are walking into the block from before the loop, then guarantee
1792 // at least 1 re-walk over the loop to propagate the information, even if
1793 // no S_WAITCNT instructions were generated.
Kannan Narayanan5e73b042017-05-05 21:10:17 +00001794 if (ContainingLoop && ContainingLoop->getHeader() == &MBB && J < I &&
Kannan Narayananacb089e2017-04-12 03:25:12 +00001795 (BlockWaitcntProcessedSet.find(&MBB) ==
1796 BlockWaitcntProcessedSet.end())) {
1797 BlockWaitcntBracketsMap[&MBB]->setRevisitLoop(true);
1798 DEBUG(dbgs() << "set-revisit: block"
Kannan Narayanan5e73b042017-05-05 21:10:17 +00001799 << ContainingLoop->getHeader()->getNumber() << '\n';);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001800 }
1801
1802 // Walk over the instructions.
1803 insertWaitcntInBlock(MF, MBB);
1804
1805 // Flag that waitcnts have been processed at least once.
1806 BlockWaitcntProcessedSet.insert(&MBB);
1807
1808 // See if we want to revisit the loop.
1809 if (ContainingLoop && loopBottom(ContainingLoop) == &MBB) {
Kannan Narayanan5e73b042017-05-05 21:10:17 +00001810 MachineBasicBlock *EntryBB = ContainingLoop->getHeader();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001811 BlockWaitcntBrackets *EntrySB = BlockWaitcntBracketsMap[EntryBB].get();
1812 if (EntrySB && EntrySB->getRevisitLoop()) {
1813 EntrySB->setRevisitLoop(false);
1814 J = I;
1815 int32_t PostOrder = EntrySB->getPostOrder();
1816 // TODO: Avoid this loop. Find another way to set I.
1817 for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1818 X = RPOT.begin(),
1819 Y = RPOT.end();
1820 X != Y; ++X) {
1821 MachineBasicBlock &MBBX = **X;
1822 if (MBBX.getNumber() == PostOrder) {
1823 I = X;
1824 break;
1825 }
1826 }
1827 LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1828 WaitcntData->incIterCnt();
1829 DEBUG(dbgs() << "revisit: block" << EntryBB->getNumber() << '\n';);
1830 continue;
1831 } else {
1832 LoopWaitcntData *WaitcntData = LoopWaitcntDataMap[ContainingLoop].get();
1833 // Loop converged, reset iteration count. If this loop gets revisited,
1834 // it must be from an outer loop, the counter will restart, this will
1835 // ensure we don't force convergence on such revisits.
1836 WaitcntData->resetIterCnt();
1837 }
1838 }
1839
1840 J = I;
1841 ++I;
1842 }
1843
1844 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1845
1846 bool HaveScalarStores = false;
1847
1848 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE;
1849 ++BI) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001850 MachineBasicBlock &MBB = *BI;
1851
1852 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1853 ++I) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001854 if (!HaveScalarStores && TII->isScalarStore(*I))
1855 HaveScalarStores = true;
1856
1857 if (I->getOpcode() == AMDGPU::S_ENDPGM ||
1858 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1859 EndPgmBlocks.push_back(&MBB);
1860 }
1861 }
1862
1863 if (HaveScalarStores) {
1864 // If scalar writes are used, the cache must be flushed or else the next
1865 // wave to reuse the same scratch memory can be clobbered.
1866 //
1867 // Insert s_dcache_wb at wave termination points if there were any scalar
1868 // stores, and only if the cache hasn't already been flushed. This could be
1869 // improved by looking across blocks for flushes in postdominating blocks
1870 // from the stores but an explicitly requested flush is probably very rare.
1871 for (MachineBasicBlock *MBB : EndPgmBlocks) {
1872 bool SeenDCacheWB = false;
1873
1874 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
1875 ++I) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001876 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1877 SeenDCacheWB = true;
1878 else if (TII->isScalarStore(*I))
1879 SeenDCacheWB = false;
1880
1881 // FIXME: It would be better to insert this before a waitcnt if any.
1882 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1883 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1884 !SeenDCacheWB) {
1885 Modified = true;
1886 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
1887 }
1888 }
1889 }
1890 }
1891
Mark Searles11d0a042017-05-31 16:44:23 +00001892 if (!MFI->isEntryFunction()) {
1893 // Wait for any outstanding memory operations that the input registers may
1894 // depend on. We can't track them and it's better to to the wait after the
1895 // costly call sequence.
1896
1897 // TODO: Could insert earlier and schedule more liberally with operations
1898 // that only use caller preserved registers.
1899 MachineBasicBlock &EntryBB = MF.front();
1900 BuildMI(EntryBB, EntryBB.getFirstNonPHI(), DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1901 .addImm(0);
1902
1903 Modified = true;
1904 }
1905
Kannan Narayananacb089e2017-04-12 03:25:12 +00001906 return Modified;
1907}