blob: 9e6dbd692e1982fc3f0d31b54792f0e66ab34c64 [file] [log] [blame]
Eugene Zelenko59e12822017-08-08 00:47:13 +00001//===- SIInsertWaitcnts.cpp - Insert Wait Instructions --------------------===//
Kannan Narayananacb089e2017-04-12 03:25:12 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Kannan Narayananacb089e2017-04-12 03:25:12 +00006//
7//===----------------------------------------------------------------------===//
8//
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// Insert wait instructions for memory reads and writes.
Kannan Narayananacb089e2017-04-12 03:25:12 +000011///
12/// Memory reads and writes are issued asynchronously, so we need to insert
13/// S_WAITCNT instructions when we want to access any of their results or
14/// overwrite any register that's used asynchronously.
Nicolai Haehnled1f45da2018-11-29 11:06:14 +000015///
16/// TODO: This pass currently keeps one timeline per hardware counter. A more
17/// finely-grained approach that keeps one timeline per event type could
18/// sometimes get away with generating weaker s_waitcnt instructions. For
19/// example, when both SMEM and LDS are in flight and we need to wait for
20/// the i-th-last LDS instruction, then an lgkmcnt(i) is actually sufficient,
21/// but the pass will currently generate a conservative lgkmcnt(0) because
22/// multiple event types are in flight.
Kannan Narayananacb089e2017-04-12 03:25:12 +000023//
24//===----------------------------------------------------------------------===//
25
26#include "AMDGPU.h"
27#include "AMDGPUSubtarget.h"
28#include "SIDefines.h"
29#include "SIInstrInfo.h"
30#include "SIMachineFunctionInfo.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000031#include "SIRegisterInfo.h"
Kannan Narayananacb089e2017-04-12 03:25:12 +000032#include "Utils/AMDGPUBaseInfo.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000033#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/DenseSet.h"
Kannan Narayananacb089e2017-04-12 03:25:12 +000035#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000036#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/CodeGen/MachineBasicBlock.h"
Kannan Narayananacb089e2017-04-12 03:25:12 +000039#include "llvm/CodeGen/MachineFunction.h"
40#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000041#include "llvm/CodeGen/MachineInstr.h"
Kannan Narayananacb089e2017-04-12 03:25:12 +000042#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000043#include "llvm/CodeGen/MachineMemOperand.h"
44#include "llvm/CodeGen/MachineOperand.h"
Kannan Narayananacb089e2017-04-12 03:25:12 +000045#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000046#include "llvm/IR/DebugLoc.h"
47#include "llvm/Pass.h"
48#include "llvm/Support/Debug.h"
Mark Searlesec581832018-04-25 19:21:26 +000049#include "llvm/Support/DebugCounter.h"
Eugene Zelenko59e12822017-08-08 00:47:13 +000050#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/raw_ostream.h"
52#include <algorithm>
53#include <cassert>
54#include <cstdint>
55#include <cstring>
56#include <memory>
57#include <utility>
58#include <vector>
Kannan Narayananacb089e2017-04-12 03:25:12 +000059
Mark Searlesec581832018-04-25 19:21:26 +000060using namespace llvm;
61
Kannan Narayananacb089e2017-04-12 03:25:12 +000062#define DEBUG_TYPE "si-insert-waitcnts"
63
Mark Searlesec581832018-04-25 19:21:26 +000064DEBUG_COUNTER(ForceExpCounter, DEBUG_TYPE"-forceexp",
65 "Force emit s_waitcnt expcnt(0) instrs");
66DEBUG_COUNTER(ForceLgkmCounter, DEBUG_TYPE"-forcelgkm",
67 "Force emit s_waitcnt lgkmcnt(0) instrs");
68DEBUG_COUNTER(ForceVMCounter, DEBUG_TYPE"-forcevm",
69 "Force emit s_waitcnt vmcnt(0) instrs");
70
Matt Arsenault0b31b242019-03-14 21:23:59 +000071static cl::opt<bool> ForceEmitZeroFlag(
Mark Searlesec581832018-04-25 19:21:26 +000072 "amdgpu-waitcnt-forcezero",
73 cl::desc("Force all waitcnt instrs to be emitted as s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
Matt Arsenault0b31b242019-03-14 21:23:59 +000074 cl::init(false), cl::Hidden);
Kannan Narayananacb089e2017-04-12 03:25:12 +000075
76namespace {
77
Nicolai Haehnleae369d72018-11-29 11:06:11 +000078template <typename EnumT>
79class enum_iterator
80 : public iterator_facade_base<enum_iterator<EnumT>,
81 std::forward_iterator_tag, const EnumT> {
82 EnumT Value;
83public:
84 enum_iterator() = default;
85 enum_iterator(EnumT Value) : Value(Value) {}
86
87 enum_iterator &operator++() {
88 Value = static_cast<EnumT>(Value + 1);
89 return *this;
90 }
91
92 bool operator==(const enum_iterator &RHS) const { return Value == RHS.Value; }
93
94 EnumT operator*() const { return Value; }
95};
96
Kannan Narayananacb089e2017-04-12 03:25:12 +000097// Class of object that encapsulates latest instruction counter score
98// associated with the operand. Used for determining whether
99// s_waitcnt instruction needs to be emited.
100
101#define CNT_MASK(t) (1u << (t))
102
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000103enum InstCounterType { VM_CNT = 0, LGKM_CNT, EXP_CNT, VS_CNT, NUM_INST_CNTS };
Kannan Narayananacb089e2017-04-12 03:25:12 +0000104
Nicolai Haehnleae369d72018-11-29 11:06:11 +0000105iterator_range<enum_iterator<InstCounterType>> inst_counter_types() {
106 return make_range(enum_iterator<InstCounterType>(VM_CNT),
107 enum_iterator<InstCounterType>(NUM_INST_CNTS));
108}
109
Eugene Zelenko59e12822017-08-08 00:47:13 +0000110using RegInterval = std::pair<signed, signed>;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000111
112struct {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000113 uint32_t VmcntMax;
114 uint32_t ExpcntMax;
115 uint32_t LgkmcntMax;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000116 uint32_t VscntMax;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000117 int32_t NumVGPRsMax;
118 int32_t NumSGPRsMax;
119} HardwareLimits;
120
121struct {
122 unsigned VGPR0;
123 unsigned VGPRL;
124 unsigned SGPR0;
125 unsigned SGPRL;
126} RegisterEncoding;
127
128enum WaitEventType {
129 VMEM_ACCESS, // vector-memory read & write
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000130 VMEM_READ_ACCESS, // vector-memory read
131 VMEM_WRITE_ACCESS,// vector-memory write
Kannan Narayananacb089e2017-04-12 03:25:12 +0000132 LDS_ACCESS, // lds read & write
133 GDS_ACCESS, // gds read & write
134 SQ_MESSAGE, // send message
135 SMEM_ACCESS, // scalar-memory read & write
136 EXP_GPR_LOCK, // export holding on its data src
137 GDS_GPR_LOCK, // GDS holding on its data and addr src
138 EXP_POS_ACCESS, // write to export position
139 EXP_PARAM_ACCESS, // write to export parameter
140 VMW_GPR_LOCK, // vector-memory write holding on its data src
141 NUM_WAIT_EVENTS,
142};
143
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000144static const uint32_t WaitEventMaskForInst[NUM_INST_CNTS] = {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000145 (1 << VMEM_ACCESS) | (1 << VMEM_READ_ACCESS),
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000146 (1 << SMEM_ACCESS) | (1 << LDS_ACCESS) | (1 << GDS_ACCESS) |
147 (1 << SQ_MESSAGE),
148 (1 << EXP_GPR_LOCK) | (1 << GDS_GPR_LOCK) | (1 << VMW_GPR_LOCK) |
149 (1 << EXP_PARAM_ACCESS) | (1 << EXP_POS_ACCESS),
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000150 (1 << VMEM_WRITE_ACCESS)
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000151};
Nicolai Haehnleae369d72018-11-29 11:06:11 +0000152
Kannan Narayananacb089e2017-04-12 03:25:12 +0000153// The mapping is:
154// 0 .. SQ_MAX_PGM_VGPRS-1 real VGPRs
155// SQ_MAX_PGM_VGPRS .. NUM_ALL_VGPRS-1 extra VGPR-like slots
156// NUM_ALL_VGPRS .. NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS-1 real SGPRs
157// We reserve a fixed number of VGPR slots in the scoring tables for
158// special tokens like SCMEM_LDS (needed for buffer load to LDS).
159enum RegisterMapping {
160 SQ_MAX_PGM_VGPRS = 256, // Maximum programmable VGPRs across all targets.
161 SQ_MAX_PGM_SGPRS = 256, // Maximum programmable SGPRs across all targets.
162 NUM_EXTRA_VGPRS = 1, // A reserved slot for DS.
163 EXTRA_VGPR_LDS = 0, // This is a placeholder the Shader algorithm uses.
164 NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_EXTRA_VGPRS, // Where SGPR starts.
165};
166
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000167void addWait(AMDGPU::Waitcnt &Wait, InstCounterType T, unsigned Count) {
168 switch (T) {
169 case VM_CNT:
170 Wait.VmCnt = std::min(Wait.VmCnt, Count);
171 break;
172 case EXP_CNT:
173 Wait.ExpCnt = std::min(Wait.ExpCnt, Count);
174 break;
175 case LGKM_CNT:
176 Wait.LgkmCnt = std::min(Wait.LgkmCnt, Count);
177 break;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000178 case VS_CNT:
179 Wait.VsCnt = std::min(Wait.VsCnt, Count);
180 break;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000181 default:
182 llvm_unreachable("bad InstCounterType");
183 }
184}
185
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000186// This objects maintains the current score brackets of each wait counter, and
187// a per-register scoreboard for each wait counter.
188//
Kannan Narayananacb089e2017-04-12 03:25:12 +0000189// We also maintain the latest score for every event type that can change the
190// waitcnt in order to know if there are multiple types of events within
191// the brackets. When multiple types of event happen in the bracket,
Mark Searlesc3c02bd2018-03-14 22:04:32 +0000192// wait count may get decreased out of order, therefore we need to put in
Kannan Narayananacb089e2017-04-12 03:25:12 +0000193// "s_waitcnt 0" before use.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000194class WaitcntBrackets {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000195public:
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000196 WaitcntBrackets(const GCNSubtarget *SubTarget) : ST(SubTarget) {
Nicolai Haehnleae369d72018-11-29 11:06:11 +0000197 for (auto T : inst_counter_types())
Eugene Zelenko59e12822017-08-08 00:47:13 +0000198 memset(VgprScores[T], 0, sizeof(VgprScores[T]));
Eugene Zelenko59e12822017-08-08 00:47:13 +0000199 }
200
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000201 static uint32_t getWaitCountMax(InstCounterType T) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000202 switch (T) {
203 case VM_CNT:
204 return HardwareLimits.VmcntMax;
205 case LGKM_CNT:
206 return HardwareLimits.LgkmcntMax;
207 case EXP_CNT:
208 return HardwareLimits.ExpcntMax;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000209 case VS_CNT:
210 return HardwareLimits.VscntMax;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000211 default:
212 break;
213 }
214 return 0;
Eugene Zelenko59e12822017-08-08 00:47:13 +0000215 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000216
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000217 uint32_t getScoreLB(InstCounterType T) const {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000218 assert(T < NUM_INST_CNTS);
219 if (T >= NUM_INST_CNTS)
220 return 0;
221 return ScoreLBs[T];
Eugene Zelenko59e12822017-08-08 00:47:13 +0000222 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000223
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000224 uint32_t getScoreUB(InstCounterType T) const {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000225 assert(T < NUM_INST_CNTS);
226 if (T >= NUM_INST_CNTS)
227 return 0;
228 return ScoreUBs[T];
Eugene Zelenko59e12822017-08-08 00:47:13 +0000229 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000230
231 // Mapping from event to counter.
232 InstCounterType eventCounter(WaitEventType E) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000233 if (WaitEventMaskForInst[VM_CNT] & (1 << E))
Kannan Narayananacb089e2017-04-12 03:25:12 +0000234 return VM_CNT;
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000235 if (WaitEventMaskForInst[LGKM_CNT] & (1 << E))
Kannan Narayananacb089e2017-04-12 03:25:12 +0000236 return LGKM_CNT;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000237 if (WaitEventMaskForInst[VS_CNT] & (1 << E))
238 return VS_CNT;
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000239 assert(WaitEventMaskForInst[EXP_CNT] & (1 << E));
240 return EXP_CNT;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000241 }
242
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000243 uint32_t getRegScore(int GprNo, InstCounterType T) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000244 if (GprNo < NUM_ALL_VGPRS) {
245 return VgprScores[T][GprNo];
246 }
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000247 assert(T == LGKM_CNT);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000248 return SgprScores[GprNo - NUM_ALL_VGPRS];
249 }
250
251 void clear() {
252 memset(ScoreLBs, 0, sizeof(ScoreLBs));
253 memset(ScoreUBs, 0, sizeof(ScoreUBs));
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000254 PendingEvents = 0;
255 memset(MixedPendingEvents, 0, sizeof(MixedPendingEvents));
Nicolai Haehnleae369d72018-11-29 11:06:11 +0000256 for (auto T : inst_counter_types())
Kannan Narayananacb089e2017-04-12 03:25:12 +0000257 memset(VgprScores[T], 0, sizeof(VgprScores[T]));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000258 memset(SgprScores, 0, sizeof(SgprScores));
259 }
260
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000261 bool merge(const WaitcntBrackets &Other);
262
Kannan Narayananacb089e2017-04-12 03:25:12 +0000263 RegInterval getRegInterval(const MachineInstr *MI, const SIInstrInfo *TII,
264 const MachineRegisterInfo *MRI,
265 const SIRegisterInfo *TRI, unsigned OpNo,
266 bool Def) const;
267
Kannan Narayananacb089e2017-04-12 03:25:12 +0000268 int32_t getMaxVGPR() const { return VgprUB; }
269 int32_t getMaxSGPR() const { return SgprUB; }
Eugene Zelenko59e12822017-08-08 00:47:13 +0000270
Nicolai Haehnlec548d912018-11-19 12:03:11 +0000271 bool counterOutOfOrder(InstCounterType T) const;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000272 bool simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const;
273 bool simplifyWaitcnt(InstCounterType T, unsigned &Count) const;
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000274 void determineWait(InstCounterType T, uint32_t ScoreToWait,
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000275 AMDGPU::Waitcnt &Wait) const;
276 void applyWaitcnt(const AMDGPU::Waitcnt &Wait);
277 void applyWaitcnt(InstCounterType T, unsigned Count);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000278 void updateByEvent(const SIInstrInfo *TII, const SIRegisterInfo *TRI,
279 const MachineRegisterInfo *MRI, WaitEventType E,
280 MachineInstr &MI);
281
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000282 bool hasPending() const { return PendingEvents != 0; }
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000283 bool hasPendingEvent(WaitEventType E) const {
284 return PendingEvents & (1 << E);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000285 }
286
287 bool hasPendingFlat() const {
288 return ((LastFlat[LGKM_CNT] > ScoreLBs[LGKM_CNT] &&
289 LastFlat[LGKM_CNT] <= ScoreUBs[LGKM_CNT]) ||
290 (LastFlat[VM_CNT] > ScoreLBs[VM_CNT] &&
291 LastFlat[VM_CNT] <= ScoreUBs[VM_CNT]));
292 }
293
294 void setPendingFlat() {
295 LastFlat[VM_CNT] = ScoreUBs[VM_CNT];
296 LastFlat[LGKM_CNT] = ScoreUBs[LGKM_CNT];
297 }
298
Kannan Narayananacb089e2017-04-12 03:25:12 +0000299 void print(raw_ostream &);
300 void dump() { print(dbgs()); }
301
302private:
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000303 struct MergeInfo {
304 uint32_t OldLB;
305 uint32_t OtherLB;
306 uint32_t MyShift;
307 uint32_t OtherShift;
308 };
309 static bool mergeScore(const MergeInfo &M, uint32_t &Score,
310 uint32_t OtherScore);
311
312 void setScoreLB(InstCounterType T, uint32_t Val) {
313 assert(T < NUM_INST_CNTS);
314 if (T >= NUM_INST_CNTS)
315 return;
316 ScoreLBs[T] = Val;
317 }
318
319 void setScoreUB(InstCounterType T, uint32_t Val) {
320 assert(T < NUM_INST_CNTS);
321 if (T >= NUM_INST_CNTS)
322 return;
323 ScoreUBs[T] = Val;
324 if (T == EXP_CNT) {
325 uint32_t UB = ScoreUBs[T] - getWaitCountMax(EXP_CNT);
326 if (ScoreLBs[T] < UB && UB < ScoreUBs[T])
327 ScoreLBs[T] = UB;
328 }
329 }
330
331 void setRegScore(int GprNo, InstCounterType T, uint32_t Val) {
332 if (GprNo < NUM_ALL_VGPRS) {
333 if (GprNo > VgprUB) {
334 VgprUB = GprNo;
335 }
336 VgprScores[T][GprNo] = Val;
337 } else {
338 assert(T == LGKM_CNT);
339 if (GprNo - NUM_ALL_VGPRS > SgprUB) {
340 SgprUB = GprNo - NUM_ALL_VGPRS;
341 }
342 SgprScores[GprNo - NUM_ALL_VGPRS] = Val;
343 }
344 }
345
346 void setExpScore(const MachineInstr *MI, const SIInstrInfo *TII,
347 const SIRegisterInfo *TRI, const MachineRegisterInfo *MRI,
348 unsigned OpNo, uint32_t Val);
349
Tom Stellard5bfbae52018-07-11 20:59:01 +0000350 const GCNSubtarget *ST = nullptr;
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000351 uint32_t ScoreLBs[NUM_INST_CNTS] = {0};
352 uint32_t ScoreUBs[NUM_INST_CNTS] = {0};
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000353 uint32_t PendingEvents = 0;
354 bool MixedPendingEvents[NUM_INST_CNTS] = {false};
Kannan Narayananacb089e2017-04-12 03:25:12 +0000355 // Remember the last flat memory operation.
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000356 uint32_t LastFlat[NUM_INST_CNTS] = {0};
Kannan Narayananacb089e2017-04-12 03:25:12 +0000357 // wait_cnt scores for every vgpr.
358 // Keep track of the VgprUB and SgprUB to make merge at join efficient.
Eugene Zelenko59e12822017-08-08 00:47:13 +0000359 int32_t VgprUB = 0;
360 int32_t SgprUB = 0;
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000361 uint32_t VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS];
Kannan Narayananacb089e2017-04-12 03:25:12 +0000362 // Wait cnt scores for every sgpr, only lgkmcnt is relevant.
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000363 uint32_t SgprScores[SQ_MAX_PGM_SGPRS] = {0};
Kannan Narayananacb089e2017-04-12 03:25:12 +0000364};
365
Kannan Narayananacb089e2017-04-12 03:25:12 +0000366class SIInsertWaitcnts : public MachineFunctionPass {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000367private:
Tom Stellard5bfbae52018-07-11 20:59:01 +0000368 const GCNSubtarget *ST = nullptr;
Eugene Zelenko59e12822017-08-08 00:47:13 +0000369 const SIInstrInfo *TII = nullptr;
370 const SIRegisterInfo *TRI = nullptr;
371 const MachineRegisterInfo *MRI = nullptr;
Konstantin Zhuravlyov71e43ee2018-09-12 18:50:47 +0000372 AMDGPU::IsaVersion IV;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000373
Mark Searles24c92ee2018-02-07 02:21:21 +0000374 DenseSet<MachineInstr *> TrackedWaitcntSet;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000375 DenseSet<MachineInstr *> VCCZBugHandledSet;
376
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000377 struct BlockInfo {
378 MachineBasicBlock *MBB;
379 std::unique_ptr<WaitcntBrackets> Incoming;
380 bool Dirty = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000381
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000382 explicit BlockInfo(MachineBasicBlock *MBB) : MBB(MBB) {}
383 };
Kannan Narayananacb089e2017-04-12 03:25:12 +0000384
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000385 std::vector<BlockInfo> BlockInfos; // by reverse post-order traversal index
386 DenseMap<MachineBasicBlock *, unsigned> RpotIdxMap;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000387
Mark Searles4a0f2c52018-05-07 14:43:28 +0000388 // ForceEmitZeroWaitcnts: force all waitcnts insts to be s_waitcnt 0
389 // because of amdgpu-waitcnt-forcezero flag
390 bool ForceEmitZeroWaitcnts;
Mark Searlesec581832018-04-25 19:21:26 +0000391 bool ForceEmitWaitcnt[NUM_INST_CNTS];
392
Kannan Narayananacb089e2017-04-12 03:25:12 +0000393public:
394 static char ID;
395
Konstantin Zhuravlyov77747772018-06-26 21:33:38 +0000396 SIInsertWaitcnts() : MachineFunctionPass(ID) {
397 (void)ForceExpCounter;
398 (void)ForceLgkmCounter;
399 (void)ForceVMCounter;
400 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000401
402 bool runOnMachineFunction(MachineFunction &MF) override;
403
404 StringRef getPassName() const override {
405 return "SI insert wait instructions";
406 }
407
408 void getAnalysisUsage(AnalysisUsage &AU) const override {
409 AU.setPreservesCFG();
Kannan Narayananacb089e2017-04-12 03:25:12 +0000410 MachineFunctionPass::getAnalysisUsage(AU);
411 }
412
Mark Searlesec581832018-04-25 19:21:26 +0000413 bool isForceEmitWaitcnt() const {
Nicolai Haehnleae369d72018-11-29 11:06:11 +0000414 for (auto T : inst_counter_types())
Mark Searlesec581832018-04-25 19:21:26 +0000415 if (ForceEmitWaitcnt[T])
416 return true;
417 return false;
418 }
419
420 void setForceEmitWaitcnt() {
421// For non-debug builds, ForceEmitWaitcnt has been initialized to false;
422// For debug builds, get the debug counter info and adjust if need be
423#ifndef NDEBUG
424 if (DebugCounter::isCounterSet(ForceExpCounter) &&
425 DebugCounter::shouldExecute(ForceExpCounter)) {
426 ForceEmitWaitcnt[EXP_CNT] = true;
427 } else {
428 ForceEmitWaitcnt[EXP_CNT] = false;
429 }
430
431 if (DebugCounter::isCounterSet(ForceLgkmCounter) &&
432 DebugCounter::shouldExecute(ForceLgkmCounter)) {
433 ForceEmitWaitcnt[LGKM_CNT] = true;
434 } else {
435 ForceEmitWaitcnt[LGKM_CNT] = false;
436 }
437
438 if (DebugCounter::isCounterSet(ForceVMCounter) &&
439 DebugCounter::shouldExecute(ForceVMCounter)) {
440 ForceEmitWaitcnt[VM_CNT] = true;
441 } else {
442 ForceEmitWaitcnt[VM_CNT] = false;
443 }
444#endif // NDEBUG
445 }
446
Matt Arsenault0ed39d32017-07-21 18:54:54 +0000447 bool mayAccessLDSThroughFlat(const MachineInstr &MI) const;
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000448 bool generateWaitcntInstBefore(MachineInstr &MI,
449 WaitcntBrackets &ScoreBrackets,
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000450 MachineInstr *OldWaitcntInstr);
Mark Searles70901b92018-04-24 15:59:59 +0000451 void updateEventWaitcntAfter(MachineInstr &Inst,
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000452 WaitcntBrackets *ScoreBrackets);
453 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block,
454 WaitcntBrackets &ScoreBrackets);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000455};
456
Eugene Zelenko59e12822017-08-08 00:47:13 +0000457} // end anonymous namespace
Kannan Narayananacb089e2017-04-12 03:25:12 +0000458
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000459RegInterval WaitcntBrackets::getRegInterval(const MachineInstr *MI,
460 const SIInstrInfo *TII,
461 const MachineRegisterInfo *MRI,
462 const SIRegisterInfo *TRI,
463 unsigned OpNo, bool Def) const {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000464 const MachineOperand &Op = MI->getOperand(OpNo);
465 if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()) ||
466 (Def && !Op.isDef()))
467 return {-1, -1};
468
469 // A use via a PW operand does not need a waitcnt.
470 // A partial write is not a WAW.
471 assert(!Op.getSubReg() || !Op.isUndef());
472
473 RegInterval Result;
474 const MachineRegisterInfo &MRIA = *MRI;
475
476 unsigned Reg = TRI->getEncodingValue(Op.getReg());
477
478 if (TRI->isVGPR(MRIA, Op.getReg())) {
479 assert(Reg >= RegisterEncoding.VGPR0 && Reg <= RegisterEncoding.VGPRL);
480 Result.first = Reg - RegisterEncoding.VGPR0;
481 assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
482 } else if (TRI->isSGPRReg(MRIA, Op.getReg())) {
483 assert(Reg >= RegisterEncoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS);
484 Result.first = Reg - RegisterEncoding.SGPR0 + NUM_ALL_VGPRS;
485 assert(Result.first >= NUM_ALL_VGPRS &&
486 Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS);
487 }
488 // TODO: Handle TTMP
489 // else if (TRI->isTTMP(MRIA, Reg.getReg())) ...
490 else
491 return {-1, -1};
492
493 const MachineInstr &MIA = *MI;
494 const TargetRegisterClass *RC = TII->getOpRegClass(MIA, OpNo);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +0000495 unsigned Size = TRI->getRegSizeInBits(*RC);
496 Result.second = Result.first + (Size / 32);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000497
498 return Result;
499}
500
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000501void WaitcntBrackets::setExpScore(const MachineInstr *MI,
502 const SIInstrInfo *TII,
503 const SIRegisterInfo *TRI,
504 const MachineRegisterInfo *MRI, unsigned OpNo,
505 uint32_t Val) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000506 RegInterval Interval = getRegInterval(MI, TII, MRI, TRI, OpNo, false);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000507 LLVM_DEBUG({
Kannan Narayananacb089e2017-04-12 03:25:12 +0000508 const MachineOperand &Opnd = MI->getOperand(OpNo);
509 assert(TRI->isVGPR(*MRI, Opnd.getReg()));
510 });
511 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
512 setRegScore(RegNo, EXP_CNT, Val);
513 }
514}
515
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000516void WaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
517 const SIRegisterInfo *TRI,
518 const MachineRegisterInfo *MRI,
519 WaitEventType E, MachineInstr &Inst) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000520 const MachineRegisterInfo &MRIA = *MRI;
521 InstCounterType T = eventCounter(E);
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000522 uint32_t CurrScore = getScoreUB(T) + 1;
523 if (CurrScore == 0)
524 report_fatal_error("InsertWaitcnt score wraparound");
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000525 // PendingEvents and ScoreUB need to be update regardless if this event
526 // changes the score of a register or not.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000527 // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000528 if (!hasPendingEvent(E)) {
529 if (PendingEvents & WaitEventMaskForInst[T])
530 MixedPendingEvents[T] = true;
531 PendingEvents |= 1 << E;
532 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000533 setScoreUB(T, CurrScore);
534
535 if (T == EXP_CNT) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000536 // Put score on the source vgprs. If this is a store, just use those
537 // specific register(s).
538 if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) {
539 // All GDS operations must protect their address register (same as
540 // export.)
541 if (Inst.getOpcode() != AMDGPU::DS_APPEND &&
542 Inst.getOpcode() != AMDGPU::DS_CONSUME) {
543 setExpScore(
544 &Inst, TII, TRI, MRI,
545 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr),
546 CurrScore);
547 }
548 if (Inst.mayStore()) {
Marek Olsakc5cec5e2019-01-16 15:43:53 +0000549 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
550 AMDGPU::OpName::data0) != -1) {
551 setExpScore(
552 &Inst, TII, TRI, MRI,
553 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0),
554 CurrScore);
555 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000556 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
557 AMDGPU::OpName::data1) != -1) {
558 setExpScore(&Inst, TII, TRI, MRI,
559 AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
560 AMDGPU::OpName::data1),
561 CurrScore);
562 }
563 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1 &&
564 Inst.getOpcode() != AMDGPU::DS_GWS_INIT &&
565 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V &&
566 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR &&
567 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P &&
568 Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER &&
569 Inst.getOpcode() != AMDGPU::DS_APPEND &&
570 Inst.getOpcode() != AMDGPU::DS_CONSUME &&
571 Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
572 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
573 const MachineOperand &Op = Inst.getOperand(I);
574 if (Op.isReg() && !Op.isDef() && TRI->isVGPR(MRIA, Op.getReg())) {
575 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
576 }
577 }
578 }
579 } else if (TII->isFLAT(Inst)) {
580 if (Inst.mayStore()) {
581 setExpScore(
582 &Inst, TII, TRI, MRI,
583 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
584 CurrScore);
585 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
586 setExpScore(
587 &Inst, TII, TRI, MRI,
588 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
589 CurrScore);
590 }
591 } else if (TII->isMIMG(Inst)) {
592 if (Inst.mayStore()) {
593 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
594 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
595 setExpScore(
596 &Inst, TII, TRI, MRI,
597 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
598 CurrScore);
599 }
600 } else if (TII->isMTBUF(Inst)) {
601 if (Inst.mayStore()) {
602 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
603 }
604 } else if (TII->isMUBUF(Inst)) {
605 if (Inst.mayStore()) {
606 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
607 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
608 setExpScore(
609 &Inst, TII, TRI, MRI,
610 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
611 CurrScore);
612 }
613 } else {
614 if (TII->isEXP(Inst)) {
615 // For export the destination registers are really temps that
616 // can be used as the actual source after export patching, so
617 // we need to treat them like sources and set the EXP_CNT
618 // score.
619 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
620 MachineOperand &DefMO = Inst.getOperand(I);
621 if (DefMO.isReg() && DefMO.isDef() &&
622 TRI->isVGPR(MRIA, DefMO.getReg())) {
623 setRegScore(TRI->getEncodingValue(DefMO.getReg()), EXP_CNT,
624 CurrScore);
625 }
626 }
627 }
628 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
629 MachineOperand &MO = Inst.getOperand(I);
630 if (MO.isReg() && !MO.isDef() && TRI->isVGPR(MRIA, MO.getReg())) {
631 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
632 }
633 }
634 }
635#if 0 // TODO: check if this is handled by MUBUF code above.
636 } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD ||
Evgeny Mankovbf975172017-08-16 16:47:29 +0000637 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 ||
638 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000639 MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data);
640 unsigned OpNo;//TODO: find the OpNo for this operand;
641 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo, false);
642 for (signed RegNo = Interval.first; RegNo < Interval.second;
Evgeny Mankovbf975172017-08-16 16:47:29 +0000643 ++RegNo) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000644 setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore);
645 }
646#endif
647 } else {
648 // Match the score to the destination registers.
649 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
650 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I, true);
651 if (T == VM_CNT && Interval.first >= NUM_ALL_VGPRS)
652 continue;
653 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
654 setRegScore(RegNo, T, CurrScore);
655 }
656 }
657 if (TII->isDS(Inst) && Inst.mayStore()) {
658 setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore);
659 }
660 }
661}
662
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000663void WaitcntBrackets::print(raw_ostream &OS) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000664 OS << '\n';
Nicolai Haehnleae369d72018-11-29 11:06:11 +0000665 for (auto T : inst_counter_types()) {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000666 uint32_t LB = getScoreLB(T);
667 uint32_t UB = getScoreUB(T);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000668
669 switch (T) {
670 case VM_CNT:
671 OS << " VM_CNT(" << UB - LB << "): ";
672 break;
673 case LGKM_CNT:
674 OS << " LGKM_CNT(" << UB - LB << "): ";
675 break;
676 case EXP_CNT:
677 OS << " EXP_CNT(" << UB - LB << "): ";
678 break;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000679 case VS_CNT:
680 OS << " VS_CNT(" << UB - LB << "): ";
681 break;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000682 default:
683 OS << " UNKNOWN(" << UB - LB << "): ";
684 break;
685 }
686
687 if (LB < UB) {
688 // Print vgpr scores.
689 for (int J = 0; J <= getMaxVGPR(); J++) {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000690 uint32_t RegScore = getRegScore(J, T);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000691 if (RegScore <= LB)
692 continue;
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000693 uint32_t RelScore = RegScore - LB - 1;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000694 if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
695 OS << RelScore << ":v" << J << " ";
696 } else {
697 OS << RelScore << ":ds ";
698 }
699 }
700 // Also need to print sgpr scores for lgkm_cnt.
701 if (T == LGKM_CNT) {
702 for (int J = 0; J <= getMaxSGPR(); J++) {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000703 uint32_t RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000704 if (RegScore <= LB)
705 continue;
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000706 uint32_t RelScore = RegScore - LB - 1;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000707 OS << RelScore << ":s" << J << " ";
708 }
709 }
710 }
711 OS << '\n';
712 }
713 OS << '\n';
Kannan Narayananacb089e2017-04-12 03:25:12 +0000714}
715
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000716/// Simplify the waitcnt, in the sense of removing redundant counts, and return
717/// whether a waitcnt instruction is needed at all.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000718bool WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000719 return simplifyWaitcnt(VM_CNT, Wait.VmCnt) |
720 simplifyWaitcnt(EXP_CNT, Wait.ExpCnt) |
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000721 simplifyWaitcnt(LGKM_CNT, Wait.LgkmCnt) |
722 simplifyWaitcnt(VS_CNT, Wait.VsCnt);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000723}
724
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000725bool WaitcntBrackets::simplifyWaitcnt(InstCounterType T,
726 unsigned &Count) const {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000727 const uint32_t LB = getScoreLB(T);
728 const uint32_t UB = getScoreUB(T);
729 if (Count < UB && UB - Count > LB)
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000730 return true;
731
732 Count = ~0u;
733 return false;
734}
735
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000736void WaitcntBrackets::determineWait(InstCounterType T, uint32_t ScoreToWait,
737 AMDGPU::Waitcnt &Wait) const {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000738 // If the score of src_operand falls within the bracket, we need an
739 // s_waitcnt instruction.
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000740 const uint32_t LB = getScoreLB(T);
741 const uint32_t UB = getScoreUB(T);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000742 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
Mark Searlesf0b93f12018-06-04 16:51:59 +0000743 if ((T == VM_CNT || T == LGKM_CNT) &&
744 hasPendingFlat() &&
745 !ST->hasFlatLgkmVMemCountInOrder()) {
746 // If there is a pending FLAT operation, and this is a VMem or LGKM
747 // waitcnt and the target can report early completion, then we need
748 // to force a waitcnt 0.
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000749 addWait(Wait, T, 0);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000750 } else if (counterOutOfOrder(T)) {
751 // Counter can get decremented out-of-order when there
Mark Searlesc3c02bd2018-03-14 22:04:32 +0000752 // are multiple types event in the bracket. Also emit an s_wait counter
Kannan Narayananacb089e2017-04-12 03:25:12 +0000753 // with a conservative value of 0 for the counter.
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000754 addWait(Wait, T, 0);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000755 } else {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000756 addWait(Wait, T, UB - ScoreToWait);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000757 }
758 }
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000759}
Kannan Narayananacb089e2017-04-12 03:25:12 +0000760
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000761void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000762 applyWaitcnt(VM_CNT, Wait.VmCnt);
763 applyWaitcnt(EXP_CNT, Wait.ExpCnt);
764 applyWaitcnt(LGKM_CNT, Wait.LgkmCnt);
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000765 applyWaitcnt(VS_CNT, Wait.VsCnt);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000766}
767
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000768void WaitcntBrackets::applyWaitcnt(InstCounterType T, unsigned Count) {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000769 const uint32_t UB = getScoreUB(T);
770 if (Count >= UB)
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000771 return;
772 if (Count != 0) {
773 if (counterOutOfOrder(T))
774 return;
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000775 setScoreLB(T, std::max(getScoreLB(T), UB - Count));
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000776 } else {
777 setScoreLB(T, UB);
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000778 MixedPendingEvents[T] = false;
779 PendingEvents &= ~WaitEventMaskForInst[T];
780 }
781}
782
Kannan Narayananacb089e2017-04-12 03:25:12 +0000783// Where there are multiple types of event in the bracket of a counter,
784// the decrement may go out of order.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000785bool WaitcntBrackets::counterOutOfOrder(InstCounterType T) const {
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000786 // Scalar memory read always can go out of order.
787 if (T == LGKM_CNT && hasPendingEvent(SMEM_ACCESS))
788 return true;
789 return MixedPendingEvents[T];
Kannan Narayananacb089e2017-04-12 03:25:12 +0000790}
791
792INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
793 false)
794INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
795 false)
796
797char SIInsertWaitcnts::ID = 0;
798
799char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID;
800
801FunctionPass *llvm::createSIInsertWaitcntsPass() {
802 return new SIInsertWaitcnts();
803}
804
805static bool readsVCCZ(const MachineInstr &MI) {
806 unsigned Opc = MI.getOpcode();
807 return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
808 !MI.getOperand(1).isUndef();
809}
810
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000811/// \returns true if the callee inserts an s_waitcnt 0 on function entry.
812static bool callWaitsOnFunctionEntry(const MachineInstr &MI) {
813 // Currently all conventions wait, but this may not always be the case.
814 //
815 // TODO: If IPRA is enabled, and the callee is isSafeForNoCSROpt, it may make
816 // senses to omit the wait and do it in the caller.
817 return true;
818}
819
820/// \returns true if the callee is expected to wait for any outstanding waits
821/// before returning.
822static bool callWaitsOnFunctionReturn(const MachineInstr &MI) {
823 return true;
824}
825
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000826/// Generate s_waitcnt instruction to be placed before cur_Inst.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000827/// Instructions of a given type are returned in order,
828/// but instructions of different types can complete out of order.
829/// We rely on this in-order completion
830/// and simply assign a score to the memory access instructions.
831/// We keep track of the active "score bracket" to determine
832/// if an access of a memory read requires an s_waitcnt
833/// and if so what the value of each counter is.
834/// The "score bracket" is bound by the lower bound and upper bound
835/// scores (*_score_LB and *_score_ub respectively).
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000836bool SIInsertWaitcnts::generateWaitcntInstBefore(
837 MachineInstr &MI, WaitcntBrackets &ScoreBrackets,
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000838 MachineInstr *OldWaitcntInstr) {
Mark Searles4a0f2c52018-05-07 14:43:28 +0000839 setForceEmitWaitcnt();
Mark Searlesec581832018-04-25 19:21:26 +0000840 bool IsForceEmitWaitcnt = isForceEmitWaitcnt();
841
Nicolai Haehnle61396ff2018-11-07 21:53:36 +0000842 if (MI.isDebugInstr())
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000843 return false;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000844
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000845 AMDGPU::Waitcnt Wait;
846
Kannan Narayananacb089e2017-04-12 03:25:12 +0000847 // See if this instruction has a forced S_WAITCNT VM.
848 // TODO: Handle other cases of NeedsWaitcntVmBefore()
Nicolai Haehnlef96456c2018-11-29 11:06:18 +0000849 if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000850 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000851 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL ||
852 MI.getOpcode() == AMDGPU::BUFFER_GL0_INV ||
853 MI.getOpcode() == AMDGPU::BUFFER_GL1_INV) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000854 Wait.VmCnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000855 }
856
857 // All waits must be resolved at call return.
858 // NOTE: this could be improved with knowledge of all call sites or
859 // with knowledge of the called routines.
Tom Stellardc5a154d2018-06-28 23:47:12 +0000860 if (MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000861 MI.getOpcode() == AMDGPU::S_SETPC_B64_return ||
862 (MI.isReturn() && MI.isCall() && !callWaitsOnFunctionEntry(MI))) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000863 Wait = Wait.combined(AMDGPU::Waitcnt::allZero(IV));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000864 }
865 // Resolve vm waits before gs-done.
866 else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
867 MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
868 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) ==
869 AMDGPU::SendMsg::ID_GS_DONE)) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000870 Wait.VmCnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000871 }
872#if 0 // TODO: the following blocks of logic when we have fence.
873 else if (MI.getOpcode() == SC_FENCE) {
874 const unsigned int group_size =
875 context->shader_info->GetMaxThreadGroupSize();
876 // group_size == 0 means thread group size is unknown at compile time
877 const bool group_is_multi_wave =
878 (group_size == 0 || group_size > target_info->GetWaveFrontSize());
879 const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
880
881 for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
882 SCRegType src_type = Inst->GetSrcType(i);
883 switch (src_type) {
884 case SCMEM_LDS:
885 if (group_is_multi_wave ||
Evgeny Mankovbf975172017-08-16 16:47:29 +0000886 context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
Mark Searles70901b92018-04-24 15:59:59 +0000887 EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
Kannan Narayananacb089e2017-04-12 03:25:12 +0000888 ScoreBrackets->getScoreUB(LGKM_CNT));
889 // LDS may have to wait for VM_CNT after buffer load to LDS
890 if (target_info->HasBufferLoadToLDS()) {
Mark Searles70901b92018-04-24 15:59:59 +0000891 EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
Kannan Narayananacb089e2017-04-12 03:25:12 +0000892 ScoreBrackets->getScoreUB(VM_CNT));
893 }
894 }
895 break;
896
897 case SCMEM_GDS:
898 if (group_is_multi_wave || fence_is_global) {
Mark Searles70901b92018-04-24 15:59:59 +0000899 EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000900 ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +0000901 EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000902 ScoreBrackets->getScoreUB(LGKM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000903 }
904 break;
905
906 case SCMEM_UAV:
907 case SCMEM_TFBUF:
908 case SCMEM_RING:
909 case SCMEM_SCATTER:
910 if (group_is_multi_wave || fence_is_global) {
Mark Searles70901b92018-04-24 15:59:59 +0000911 EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000912 ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +0000913 EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000914 ScoreBrackets->getScoreUB(VM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000915 }
916 break;
917
918 case SCMEM_SCRATCH:
919 default:
920 break;
921 }
922 }
923 }
924#endif
925
926 // Export & GDS instructions do not read the EXEC mask until after the export
927 // is granted (which can occur well after the instruction is issued).
928 // The shader program must flush all EXP operations on the export-count
929 // before overwriting the EXEC mask.
930 else {
931 if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
932 // Export and GDS are tracked individually, either may trigger a waitcnt
933 // for EXEC.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000934 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
935 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
936 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
937 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000938 Wait.ExpCnt = 0;
939 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000940 }
941
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000942 if (MI.isCall() && callWaitsOnFunctionEntry(MI)) {
943 // Don't bother waiting on anything except the call address. The function
944 // is going to insert a wait on everything in its prolog. This still needs
945 // to be careful if the call target is a load (e.g. a GOT load).
946 Wait = AMDGPU::Waitcnt();
Kannan Narayananacb089e2017-04-12 03:25:12 +0000947
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000948 int CallAddrOpIdx =
949 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
950 RegInterval Interval = ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI,
951 CallAddrOpIdx, false);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000952 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000953 ScoreBrackets.determineWait(
954 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000955 }
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000956 } else {
Matt Arsenault0ed39d32017-07-21 18:54:54 +0000957 // FIXME: Should not be relying on memoperands.
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000958 // Look at the source operands of every instruction to see if
959 // any of them results from a previous memory operation that affects
960 // its current usage. If so, an s_waitcnt instruction needs to be
961 // emitted.
962 // If the source operand was defined by a load, add the s_waitcnt
963 // instruction.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000964 for (const MachineMemOperand *Memop : MI.memoperands()) {
965 unsigned AS = Memop->getAddrSpace();
Matt Arsenault0da63502018-08-31 05:49:54 +0000966 if (AS != AMDGPUAS::LOCAL_ADDRESS)
Kannan Narayananacb089e2017-04-12 03:25:12 +0000967 continue;
968 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000969 // VM_CNT is only relevant to vgpr or LDS.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000970 ScoreBrackets.determineWait(
971 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000972 }
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000973
974 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
975 const MachineOperand &Op = MI.getOperand(I);
976 const MachineRegisterInfo &MRIA = *MRI;
977 RegInterval Interval =
978 ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, I, false);
979 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
980 if (TRI->isVGPR(MRIA, Op.getReg())) {
981 // VM_CNT is only relevant to vgpr or LDS.
982 ScoreBrackets.determineWait(
983 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
984 }
985 ScoreBrackets.determineWait(
986 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
987 }
988 }
989 // End of for loop that looks at all source operands to decide vm_wait_cnt
990 // and lgk_wait_cnt.
991
992 // Two cases are handled for destination operands:
993 // 1) If the destination operand was defined by a load, add the s_waitcnt
994 // instruction to guarantee the right WAW order.
995 // 2) If a destination operand that was used by a recent export/store ins,
996 // add s_waitcnt on exp_cnt to guarantee the WAR order.
997 if (MI.mayStore()) {
998 // FIXME: Should not be relying on memoperands.
999 for (const MachineMemOperand *Memop : MI.memoperands()) {
1000 unsigned AS = Memop->getAddrSpace();
1001 if (AS != AMDGPUAS::LOCAL_ADDRESS)
1002 continue;
1003 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001004 ScoreBrackets.determineWait(
1005 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1006 ScoreBrackets.determineWait(
1007 EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001008 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001009 }
Matt Arsenaultaa41e922019-06-14 21:52:26 +00001010 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1011 MachineOperand &Def = MI.getOperand(I);
1012 const MachineRegisterInfo &MRIA = *MRI;
1013 RegInterval Interval =
1014 ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, I, true);
1015 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1016 if (TRI->isVGPR(MRIA, Def.getReg())) {
1017 ScoreBrackets.determineWait(
1018 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1019 ScoreBrackets.determineWait(
1020 EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
1021 }
1022 ScoreBrackets.determineWait(
1023 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1024 }
1025 } // End of for loop that looks at all dest operands.
1026 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001027 }
1028
Kannan Narayananacb089e2017-04-12 03:25:12 +00001029 // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1030 // occurs before the instruction. Doing it here prevents any additional
1031 // S_WAITCNTs from being emitted if the instruction was marked as
1032 // requiring a WAITCNT beforehand.
Konstantin Zhuravlyovbe6c0ca2017-06-02 17:40:26 +00001033 if (MI.getOpcode() == AMDGPU::S_BARRIER &&
1034 !ST->hasAutoWaitcntBeforeBarrier()) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001035 Wait = Wait.combined(AMDGPU::Waitcnt::allZero(IV));
Kannan Narayananacb089e2017-04-12 03:25:12 +00001036 }
1037
1038 // TODO: Remove this work-around, enable the assert for Bug 457939
1039 // after fixing the scheduler. Also, the Shader Compiler code is
1040 // independent of target.
Tom Stellardc5a154d2018-06-28 23:47:12 +00001041 if (readsVCCZ(MI) && ST->getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001042 if (ScoreBrackets.getScoreLB(LGKM_CNT) <
1043 ScoreBrackets.getScoreUB(LGKM_CNT) &&
1044 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001045 Wait.LgkmCnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001046 }
1047 }
1048
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001049 // Early-out if no wait is indicated.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001050 if (!ScoreBrackets.simplifyWaitcnt(Wait) && !IsForceEmitWaitcnt) {
1051 bool Modified = false;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001052 if (OldWaitcntInstr) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001053 for (auto II = OldWaitcntInstr->getIterator(), NextI = std::next(II);
1054 &*II != &MI; II = NextI, ++NextI) {
1055 if (II->isDebugInstr())
1056 continue;
1057
1058 if (TrackedWaitcntSet.count(&*II)) {
1059 TrackedWaitcntSet.erase(&*II);
1060 II->eraseFromParent();
1061 Modified = true;
1062 } else if (II->getOpcode() == AMDGPU::S_WAITCNT) {
1063 int64_t Imm = II->getOperand(0).getImm();
1064 ScoreBrackets.applyWaitcnt(AMDGPU::decodeWaitcnt(IV, Imm));
1065 } else {
1066 assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT);
1067 assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1068 ScoreBrackets.applyWaitcnt(
1069 AMDGPU::Waitcnt(0, 0, 0, II->getOperand(1).getImm()));
1070 }
Stanislav Mekhanoshindb39b4b2018-02-08 00:18:35 +00001071 }
Nicolai Haehnle61396ff2018-11-07 21:53:36 +00001072 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001073 return Modified;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001074 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001075
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001076 if (ForceEmitZeroWaitcnts)
Stanislav Mekhanoshin956b0be2019-04-25 18:53:41 +00001077 Wait = AMDGPU::Waitcnt::allZero(IV);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001078
1079 if (ForceEmitWaitcnt[VM_CNT])
1080 Wait.VmCnt = 0;
1081 if (ForceEmitWaitcnt[EXP_CNT])
1082 Wait.ExpCnt = 0;
1083 if (ForceEmitWaitcnt[LGKM_CNT])
1084 Wait.LgkmCnt = 0;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001085 if (ForceEmitWaitcnt[VS_CNT])
1086 Wait.VsCnt = 0;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001087
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001088 ScoreBrackets.applyWaitcnt(Wait);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001089
1090 AMDGPU::Waitcnt OldWait;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001091 bool Modified = false;
1092
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001093 if (OldWaitcntInstr) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001094 for (auto II = OldWaitcntInstr->getIterator(), NextI = std::next(II);
1095 &*II != &MI; II = NextI, NextI++) {
1096 if (II->isDebugInstr())
1097 continue;
1098
1099 if (II->getOpcode() == AMDGPU::S_WAITCNT) {
1100 unsigned IEnc = II->getOperand(0).getImm();
1101 AMDGPU::Waitcnt IWait = AMDGPU::decodeWaitcnt(IV, IEnc);
1102 OldWait = OldWait.combined(IWait);
1103 if (!TrackedWaitcntSet.count(&*II))
1104 Wait = Wait.combined(IWait);
1105 unsigned NewEnc = AMDGPU::encodeWaitcnt(IV, Wait);
1106 if (IEnc != NewEnc) {
1107 II->getOperand(0).setImm(NewEnc);
1108 Modified = true;
1109 }
1110 Wait.VmCnt = ~0u;
1111 Wait.LgkmCnt = ~0u;
1112 Wait.ExpCnt = ~0u;
1113 } else {
1114 assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT);
1115 assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1116
1117 unsigned ICnt = II->getOperand(1).getImm();
1118 OldWait.VsCnt = std::min(OldWait.VsCnt, ICnt);
1119 if (!TrackedWaitcntSet.count(&*II))
1120 Wait.VsCnt = std::min(Wait.VsCnt, ICnt);
1121 if (Wait.VsCnt != ICnt) {
1122 II->getOperand(1).setImm(Wait.VsCnt);
1123 Modified = true;
1124 }
1125 Wait.VsCnt = ~0u;
1126 }
1127
1128 LLVM_DEBUG(dbgs() << "updateWaitcntInBlock\n"
1129 << "Old Instr: " << MI << '\n'
1130 << "New Instr: " << *II << '\n');
1131
1132 if (!Wait.hasWait())
1133 return Modified;
1134 }
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001135 }
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001136
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001137 if (Wait.VmCnt != ~0u || Wait.LgkmCnt != ~0u || Wait.ExpCnt != ~0u) {
1138 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001139 auto SWaitInst = BuildMI(*MI.getParent(), MI.getIterator(),
1140 MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1141 .addImm(Enc);
1142 TrackedWaitcntSet.insert(SWaitInst);
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001143 Modified = true;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001144
1145 LLVM_DEBUG(dbgs() << "insertWaitcntInBlock\n"
1146 << "Old Instr: " << MI << '\n'
1147 << "New Instr: " << *SWaitInst << '\n');
Kannan Narayananacb089e2017-04-12 03:25:12 +00001148 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001149
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001150 if (Wait.VsCnt != ~0u) {
1151 assert(ST->hasVscnt());
1152
1153 auto SWaitInst =
1154 BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
1155 TII->get(AMDGPU::S_WAITCNT_VSCNT))
1156 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1157 .addImm(Wait.VsCnt);
1158 TrackedWaitcntSet.insert(SWaitInst);
1159 Modified = true;
1160
1161 LLVM_DEBUG(dbgs() << "insertWaitcntInBlock\n"
1162 << "Old Instr: " << MI << '\n'
1163 << "New Instr: " << *SWaitInst << '\n');
1164 }
1165
1166 return Modified;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001167}
1168
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001169// This is a flat memory operation. Check to see if it has memory
1170// tokens for both LDS and Memory, and if so mark it as a flat.
1171bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
1172 if (MI.memoperands_empty())
1173 return true;
1174
1175 for (const MachineMemOperand *Memop : MI.memoperands()) {
1176 unsigned AS = Memop->getAddrSpace();
Matt Arsenault0da63502018-08-31 05:49:54 +00001177 if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS)
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001178 return true;
1179 }
1180
1181 return false;
1182}
1183
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001184void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
1185 WaitcntBrackets *ScoreBrackets) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001186 // Now look at the instruction opcode. If it is a memory access
1187 // instruction, update the upper-bound of the appropriate counter's
1188 // bracket and the destination operand scores.
1189 // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001190 if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
Marek Olsakc5cec5e2019-01-16 15:43:53 +00001191 if (TII->isAlwaysGDS(Inst.getOpcode()) ||
1192 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001193 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1194 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1195 } else {
1196 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1197 }
1198 } else if (TII->isFLAT(Inst)) {
1199 assert(Inst.mayLoad() || Inst.mayStore());
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001200
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001201 if (TII->usesVM_CNT(Inst)) {
1202 if (!ST->hasVscnt())
1203 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1204 else if (Inst.mayLoad() &&
1205 AMDGPU::getAtomicRetOp(Inst.getOpcode()) == -1)
1206 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1207 else
1208 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1209 }
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001210
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001211 if (TII->usesLGKM_CNT(Inst)) {
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001212 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001213
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001214 // This is a flat memory operation, so note it - it will require
1215 // that both the VM and LGKM be flushed to zero if it is pending when
1216 // a VM or LGKM dependency occurs.
1217 if (mayAccessLDSThroughFlat(Inst))
1218 ScoreBrackets->setPendingFlat();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001219 }
1220 } else if (SIInstrInfo::isVMEM(Inst) &&
1221 // TODO: get a better carve out.
1222 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1 &&
1223 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_SC &&
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001224 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_VOL &&
1225 Inst.getOpcode() != AMDGPU::BUFFER_GL0_INV &&
1226 Inst.getOpcode() != AMDGPU::BUFFER_GL1_INV) {
1227 if (!ST->hasVscnt())
1228 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1229 else if ((Inst.mayLoad() &&
1230 AMDGPU::getAtomicRetOp(Inst.getOpcode()) == -1) ||
1231 /* IMAGE_GET_RESINFO / IMAGE_GET_LOD */
1232 (TII->isMIMG(Inst) && !Inst.mayLoad() && !Inst.mayStore()))
1233 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1234 else if (Inst.mayStore())
1235 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1236
Mark Searles2a19af62018-04-26 16:11:19 +00001237 if (ST->vmemWriteNeedsExpWaitcnt() &&
Mark Searles11d0a042017-05-31 16:44:23 +00001238 (Inst.mayStore() || AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001239 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1240 }
1241 } else if (TII->isSMRD(Inst)) {
1242 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
Matt Arsenaultaa41e922019-06-14 21:52:26 +00001243 } else if (Inst.isCall()) {
1244 if (callWaitsOnFunctionReturn(Inst)) {
1245 // Act as a wait on everything
1246 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt::allZero(IV));
1247 } else {
1248 // May need to way wait for anything.
1249 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
1250 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001251 } else {
1252 switch (Inst.getOpcode()) {
1253 case AMDGPU::S_SENDMSG:
1254 case AMDGPU::S_SENDMSGHALT:
1255 ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1256 break;
1257 case AMDGPU::EXP:
1258 case AMDGPU::EXP_DONE: {
1259 int Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1260 if (Imm >= 32 && Imm <= 63)
1261 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1262 else if (Imm >= 12 && Imm <= 15)
1263 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1264 else
1265 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1266 break;
1267 }
1268 case AMDGPU::S_MEMTIME:
1269 case AMDGPU::S_MEMREALTIME:
1270 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1271 break;
1272 default:
1273 break;
1274 }
1275 }
1276}
1277
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001278bool WaitcntBrackets::mergeScore(const MergeInfo &M, uint32_t &Score,
1279 uint32_t OtherScore) {
1280 uint32_t MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
1281 uint32_t OtherShifted =
1282 OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
1283 Score = std::max(MyShifted, OtherShifted);
1284 return OtherShifted > MyShifted;
1285}
Kannan Narayananacb089e2017-04-12 03:25:12 +00001286
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001287/// Merge the pending events and associater score brackets of \p Other into
1288/// this brackets status.
1289///
1290/// Returns whether the merge resulted in a change that requires tighter waits
1291/// (i.e. the merged brackets strictly dominate the original brackets).
1292bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
1293 bool StrictDom = false;
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001294
Nicolai Haehnleae369d72018-11-29 11:06:11 +00001295 for (auto T : inst_counter_types()) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001296 // Merge event flags for this counter
1297 const bool OldOutOfOrder = counterOutOfOrder(T);
1298 const uint32_t OldEvents = PendingEvents & WaitEventMaskForInst[T];
1299 const uint32_t OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T];
1300 if (OtherEvents & ~OldEvents)
1301 StrictDom = true;
1302 if (Other.MixedPendingEvents[T] ||
1303 (OldEvents && OtherEvents && OldEvents != OtherEvents))
1304 MixedPendingEvents[T] = true;
1305 PendingEvents |= OtherEvents;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001306
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001307 // Merge scores for this counter
1308 const uint32_t MyPending = ScoreUBs[T] - ScoreLBs[T];
1309 const uint32_t OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
1310 MergeInfo M;
1311 M.OldLB = ScoreLBs[T];
1312 M.OtherLB = Other.ScoreLBs[T];
1313 M.MyShift = OtherPending > MyPending ? OtherPending - MyPending : 0;
1314 M.OtherShift = ScoreUBs[T] - Other.ScoreUBs[T] + M.MyShift;
1315
1316 const uint32_t NewUB = ScoreUBs[T] + M.MyShift;
1317 if (NewUB < ScoreUBs[T])
1318 report_fatal_error("waitcnt score overflow");
1319 ScoreUBs[T] = NewUB;
1320 ScoreLBs[T] = std::min(M.OldLB + M.MyShift, M.OtherLB + M.OtherShift);
1321
1322 StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
1323
1324 bool RegStrictDom = false;
1325 for (int J = 0, E = std::max(getMaxVGPR(), Other.getMaxVGPR()) + 1; J != E;
1326 J++) {
1327 RegStrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001328 }
1329
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001330 if (T == LGKM_CNT) {
1331 for (int J = 0, E = std::max(getMaxSGPR(), Other.getMaxSGPR()) + 1;
1332 J != E; J++) {
1333 RegStrictDom |= mergeScore(M, SgprScores[J], Other.SgprScores[J]);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001334 }
1335 }
1336
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001337 if (RegStrictDom && !OldOutOfOrder)
1338 StrictDom = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001339 }
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001340
Carl Ritsonc521ac32018-12-19 10:17:49 +00001341 VgprUB = std::max(getMaxVGPR(), Other.getMaxVGPR());
1342 SgprUB = std::max(getMaxSGPR(), Other.getMaxSGPR());
1343
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001344 return StrictDom;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001345}
1346
1347// Generate s_waitcnt instructions where needed.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001348bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1349 MachineBasicBlock &Block,
1350 WaitcntBrackets &ScoreBrackets) {
1351 bool Modified = false;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001352
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001353 LLVM_DEBUG({
Mark Searlesec581832018-04-25 19:21:26 +00001354 dbgs() << "*** Block" << Block.getNumber() << " ***";
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001355 ScoreBrackets.dump();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001356 });
1357
Kannan Narayananacb089e2017-04-12 03:25:12 +00001358 // Walk over the instructions.
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001359 MachineInstr *OldWaitcntInstr = nullptr;
1360
Kannan Narayananacb089e2017-04-12 03:25:12 +00001361 for (MachineBasicBlock::iterator Iter = Block.begin(), E = Block.end();
1362 Iter != E;) {
1363 MachineInstr &Inst = *Iter;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001364
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001365 // Track pre-existing waitcnts from earlier iterations.
1366 if (Inst.getOpcode() == AMDGPU::S_WAITCNT ||
1367 (Inst.getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1368 Inst.getOperand(0).isReg() &&
1369 Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL)) {
1370 if (!OldWaitcntInstr)
1371 OldWaitcntInstr = &Inst;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001372 ++Iter;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001373 continue;
1374 }
1375
Kannan Narayananacb089e2017-04-12 03:25:12 +00001376 bool VCCZBugWorkAround = false;
1377 if (readsVCCZ(Inst) &&
Mark Searles24c92ee2018-02-07 02:21:21 +00001378 (!VCCZBugHandledSet.count(&Inst))) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001379 if (ScoreBrackets.getScoreLB(LGKM_CNT) <
1380 ScoreBrackets.getScoreUB(LGKM_CNT) &&
1381 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
Tom Stellardc5a154d2018-06-28 23:47:12 +00001382 if (ST->getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS)
Kannan Narayananacb089e2017-04-12 03:25:12 +00001383 VCCZBugWorkAround = true;
1384 }
1385 }
1386
1387 // Generate an s_waitcnt instruction to be placed before
1388 // cur_Inst, if needed.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001389 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001390 OldWaitcntInstr = nullptr;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001391
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001392 updateEventWaitcntAfter(Inst, &ScoreBrackets);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001393
1394#if 0 // TODO: implement resource type check controlled by options with ub = LB.
1395 // If this instruction generates a S_SETVSKIP because it is an
1396 // indexed resource, and we are on Tahiti, then it will also force
1397 // an S_WAITCNT vmcnt(0)
1398 if (RequireCheckResourceType(Inst, context)) {
1399 // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1400 ScoreBrackets->setScoreLB(VM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +00001401 ScoreBrackets->getScoreUB(VM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +00001402 }
1403#endif
1404
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001405 LLVM_DEBUG({
Mark Searles94ae3b22018-01-30 17:17:06 +00001406 Inst.print(dbgs());
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001407 ScoreBrackets.dump();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001408 });
1409
1410 // Check to see if this is a GWS instruction. If so, and if this is CI or
1411 // VI, then the generated code sequence will include an S_WAITCNT 0.
1412 // TODO: Are these the only GWS instructions?
1413 if (Inst.getOpcode() == AMDGPU::DS_GWS_INIT ||
1414 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_V ||
1415 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_BR ||
1416 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_P ||
1417 Inst.getOpcode() == AMDGPU::DS_GWS_BARRIER) {
1418 // TODO: && context->target_info->GwsRequiresMemViolTest() ) {
Stanislav Mekhanoshin956b0be2019-04-25 18:53:41 +00001419 ScoreBrackets.applyWaitcnt(AMDGPU::Waitcnt::allZeroExceptVsCnt());
Kannan Narayananacb089e2017-04-12 03:25:12 +00001420 }
1421
1422 // TODO: Remove this work-around after fixing the scheduler and enable the
1423 // assert above.
1424 if (VCCZBugWorkAround) {
1425 // Restore the vccz bit. Any time a value is written to vcc, the vcc
1426 // bit is updated, so we can restore the bit by reading the value of
1427 // vcc and then writing it back to the register.
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001428 BuildMI(Block, Inst, Inst.getDebugLoc(),
1429 TII->get(AMDGPU::S_MOV_B64),
Kannan Narayananacb089e2017-04-12 03:25:12 +00001430 AMDGPU::VCC)
1431 .addReg(AMDGPU::VCC);
1432 VCCZBugHandledSet.insert(&Inst);
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001433 Modified = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001434 }
1435
Kannan Narayananacb089e2017-04-12 03:25:12 +00001436 ++Iter;
1437 }
1438
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001439 return Modified;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001440}
1441
1442bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
Tom Stellard5bfbae52018-07-11 20:59:01 +00001443 ST = &MF.getSubtarget<GCNSubtarget>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001444 TII = ST->getInstrInfo();
1445 TRI = &TII->getRegisterInfo();
1446 MRI = &MF.getRegInfo();
Konstantin Zhuravlyov71e43ee2018-09-12 18:50:47 +00001447 IV = AMDGPU::getIsaVersion(ST->getCPU());
Mark Searles11d0a042017-05-31 16:44:23 +00001448 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001449
Mark Searles4a0f2c52018-05-07 14:43:28 +00001450 ForceEmitZeroWaitcnts = ForceEmitZeroFlag;
Nicolai Haehnleae369d72018-11-29 11:06:11 +00001451 for (auto T : inst_counter_types())
Mark Searlesec581832018-04-25 19:21:26 +00001452 ForceEmitWaitcnt[T] = false;
1453
Kannan Narayananacb089e2017-04-12 03:25:12 +00001454 HardwareLimits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1455 HardwareLimits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1456 HardwareLimits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001457 HardwareLimits.VscntMax = ST->hasVscnt() ? 63 : 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001458
1459 HardwareLimits.NumVGPRsMax = ST->getAddressableNumVGPRs();
1460 HardwareLimits.NumSGPRsMax = ST->getAddressableNumSGPRs();
1461 assert(HardwareLimits.NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1462 assert(HardwareLimits.NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1463
1464 RegisterEncoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1465 RegisterEncoding.VGPRL =
1466 RegisterEncoding.VGPR0 + HardwareLimits.NumVGPRsMax - 1;
1467 RegisterEncoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1468 RegisterEncoding.SGPRL =
1469 RegisterEncoding.SGPR0 + HardwareLimits.NumSGPRsMax - 1;
1470
Mark Searles24c92ee2018-02-07 02:21:21 +00001471 TrackedWaitcntSet.clear();
Mark Searles24c92ee2018-02-07 02:21:21 +00001472 VCCZBugHandledSet.clear();
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001473 RpotIdxMap.clear();
1474 BlockInfos.clear();
Mark Searles24c92ee2018-02-07 02:21:21 +00001475
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001476 // Keep iterating over the blocks in reverse post order, inserting and
1477 // updating s_waitcnt where needed, until a fix point is reached.
1478 for (MachineBasicBlock *MBB :
1479 ReversePostOrderTraversal<MachineFunction *>(&MF)) {
1480 RpotIdxMap[MBB] = BlockInfos.size();
1481 BlockInfos.emplace_back(MBB);
1482 }
1483
1484 std::unique_ptr<WaitcntBrackets> Brackets;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001485 bool Modified = false;
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001486 bool Repeat;
1487 do {
1488 Repeat = false;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001489
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001490 for (BlockInfo &BI : BlockInfos) {
1491 if (!BI.Dirty)
1492 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001493
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001494 unsigned Idx = std::distance(&*BlockInfos.begin(), &BI);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001495
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001496 if (BI.Incoming) {
1497 if (!Brackets)
1498 Brackets = llvm::make_unique<WaitcntBrackets>(*BI.Incoming);
1499 else
1500 *Brackets = *BI.Incoming;
1501 } else {
1502 if (!Brackets)
1503 Brackets = llvm::make_unique<WaitcntBrackets>(ST);
1504 else
1505 Brackets->clear();
Mark Searles1bc6e712018-04-19 15:42:30 +00001506 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001507
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001508 Modified |= insertWaitcntInBlock(MF, *BI.MBB, *Brackets);
1509 BI.Dirty = false;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001510
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001511 if (Brackets->hasPending()) {
1512 BlockInfo *MoveBracketsToSucc = nullptr;
1513 for (MachineBasicBlock *Succ : BI.MBB->successors()) {
1514 unsigned SuccIdx = RpotIdxMap[Succ];
1515 BlockInfo &SuccBI = BlockInfos[SuccIdx];
1516 if (!SuccBI.Incoming) {
1517 SuccBI.Dirty = true;
1518 if (SuccIdx <= Idx)
1519 Repeat = true;
1520 if (!MoveBracketsToSucc) {
1521 MoveBracketsToSucc = &SuccBI;
1522 } else {
1523 SuccBI.Incoming = llvm::make_unique<WaitcntBrackets>(*Brackets);
1524 }
1525 } else if (SuccBI.Incoming->merge(*Brackets)) {
1526 SuccBI.Dirty = true;
1527 if (SuccIdx <= Idx)
1528 Repeat = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001529 }
1530 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001531 if (MoveBracketsToSucc)
1532 MoveBracketsToSucc->Incoming = std::move(Brackets);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001533 }
1534 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001535 } while (Repeat);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001536
1537 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1538
1539 bool HaveScalarStores = false;
1540
1541 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE;
1542 ++BI) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001543 MachineBasicBlock &MBB = *BI;
1544
1545 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1546 ++I) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001547 if (!HaveScalarStores && TII->isScalarStore(*I))
1548 HaveScalarStores = true;
1549
1550 if (I->getOpcode() == AMDGPU::S_ENDPGM ||
1551 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1552 EndPgmBlocks.push_back(&MBB);
1553 }
1554 }
1555
1556 if (HaveScalarStores) {
1557 // If scalar writes are used, the cache must be flushed or else the next
1558 // wave to reuse the same scratch memory can be clobbered.
1559 //
1560 // Insert s_dcache_wb at wave termination points if there were any scalar
1561 // stores, and only if the cache hasn't already been flushed. This could be
1562 // improved by looking across blocks for flushes in postdominating blocks
1563 // from the stores but an explicitly requested flush is probably very rare.
1564 for (MachineBasicBlock *MBB : EndPgmBlocks) {
1565 bool SeenDCacheWB = false;
1566
1567 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
1568 ++I) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001569 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1570 SeenDCacheWB = true;
1571 else if (TII->isScalarStore(*I))
1572 SeenDCacheWB = false;
1573
1574 // FIXME: It would be better to insert this before a waitcnt if any.
1575 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1576 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1577 !SeenDCacheWB) {
1578 Modified = true;
1579 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
1580 }
1581 }
1582 }
1583 }
1584
Mark Searles11d0a042017-05-31 16:44:23 +00001585 if (!MFI->isEntryFunction()) {
1586 // Wait for any outstanding memory operations that the input registers may
Hiroshi Inouec8e92452018-01-29 05:17:03 +00001587 // depend on. We can't track them and it's better to the wait after the
Mark Searles11d0a042017-05-31 16:44:23 +00001588 // costly call sequence.
1589
1590 // TODO: Could insert earlier and schedule more liberally with operations
1591 // that only use caller preserved registers.
1592 MachineBasicBlock &EntryBB = MF.front();
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001593 if (ST->hasVscnt())
1594 BuildMI(EntryBB, EntryBB.getFirstNonPHI(), DebugLoc(),
1595 TII->get(AMDGPU::S_WAITCNT_VSCNT))
1596 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1597 .addImm(0);
Mark Searlesed54ff12018-05-30 16:27:57 +00001598 BuildMI(EntryBB, EntryBB.getFirstNonPHI(), DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1599 .addImm(0);
Mark Searles11d0a042017-05-31 16:44:23 +00001600
1601 Modified = true;
1602 }
1603
Kannan Narayananacb089e2017-04-12 03:25:12 +00001604 return Modified;
1605}