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