blob: 34513d3450ac59dfc61955fa7469fdfe15e4cb2f [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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000811/// Generate s_waitcnt instruction to be placed before cur_Inst.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000812/// Instructions of a given type are returned in order,
813/// but instructions of different types can complete out of order.
814/// We rely on this in-order completion
815/// and simply assign a score to the memory access instructions.
816/// We keep track of the active "score bracket" to determine
817/// if an access of a memory read requires an s_waitcnt
818/// and if so what the value of each counter is.
819/// The "score bracket" is bound by the lower bound and upper bound
820/// scores (*_score_LB and *_score_ub respectively).
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000821bool SIInsertWaitcnts::generateWaitcntInstBefore(
822 MachineInstr &MI, WaitcntBrackets &ScoreBrackets,
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000823 MachineInstr *OldWaitcntInstr) {
Mark Searles4a0f2c52018-05-07 14:43:28 +0000824 setForceEmitWaitcnt();
Mark Searlesec581832018-04-25 19:21:26 +0000825 bool IsForceEmitWaitcnt = isForceEmitWaitcnt();
826
Nicolai Haehnle61396ff2018-11-07 21:53:36 +0000827 if (MI.isDebugInstr())
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000828 return false;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000829
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000830 AMDGPU::Waitcnt Wait;
831
Kannan Narayananacb089e2017-04-12 03:25:12 +0000832 // See if this instruction has a forced S_WAITCNT VM.
833 // TODO: Handle other cases of NeedsWaitcntVmBefore()
Nicolai Haehnlef96456c2018-11-29 11:06:18 +0000834 if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000835 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000836 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL ||
837 MI.getOpcode() == AMDGPU::BUFFER_GL0_INV ||
838 MI.getOpcode() == AMDGPU::BUFFER_GL1_INV) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000839 Wait.VmCnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000840 }
841
842 // All waits must be resolved at call return.
843 // NOTE: this could be improved with knowledge of all call sites or
844 // with knowledge of the called routines.
Tom Stellardc5a154d2018-06-28 23:47:12 +0000845 if (MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
Mark Searles11d0a042017-05-31 16:44:23 +0000846 MI.getOpcode() == AMDGPU::S_SETPC_B64_return) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000847 Wait = Wait.combined(AMDGPU::Waitcnt::allZero(IV));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000848 }
849 // Resolve vm waits before gs-done.
850 else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
851 MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
852 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) ==
853 AMDGPU::SendMsg::ID_GS_DONE)) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000854 Wait.VmCnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000855 }
856#if 0 // TODO: the following blocks of logic when we have fence.
857 else if (MI.getOpcode() == SC_FENCE) {
858 const unsigned int group_size =
859 context->shader_info->GetMaxThreadGroupSize();
860 // group_size == 0 means thread group size is unknown at compile time
861 const bool group_is_multi_wave =
862 (group_size == 0 || group_size > target_info->GetWaveFrontSize());
863 const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
864
865 for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
866 SCRegType src_type = Inst->GetSrcType(i);
867 switch (src_type) {
868 case SCMEM_LDS:
869 if (group_is_multi_wave ||
Evgeny Mankovbf975172017-08-16 16:47:29 +0000870 context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
Mark Searles70901b92018-04-24 15:59:59 +0000871 EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
Kannan Narayananacb089e2017-04-12 03:25:12 +0000872 ScoreBrackets->getScoreUB(LGKM_CNT));
873 // LDS may have to wait for VM_CNT after buffer load to LDS
874 if (target_info->HasBufferLoadToLDS()) {
Mark Searles70901b92018-04-24 15:59:59 +0000875 EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
Kannan Narayananacb089e2017-04-12 03:25:12 +0000876 ScoreBrackets->getScoreUB(VM_CNT));
877 }
878 }
879 break;
880
881 case SCMEM_GDS:
882 if (group_is_multi_wave || fence_is_global) {
Mark Searles70901b92018-04-24 15:59:59 +0000883 EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000884 ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +0000885 EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000886 ScoreBrackets->getScoreUB(LGKM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000887 }
888 break;
889
890 case SCMEM_UAV:
891 case SCMEM_TFBUF:
892 case SCMEM_RING:
893 case SCMEM_SCATTER:
894 if (group_is_multi_wave || fence_is_global) {
Mark Searles70901b92018-04-24 15:59:59 +0000895 EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000896 ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +0000897 EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000898 ScoreBrackets->getScoreUB(VM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000899 }
900 break;
901
902 case SCMEM_SCRATCH:
903 default:
904 break;
905 }
906 }
907 }
908#endif
909
910 // Export & GDS instructions do not read the EXEC mask until after the export
911 // is granted (which can occur well after the instruction is issued).
912 // The shader program must flush all EXP operations on the export-count
913 // before overwriting the EXEC mask.
914 else {
915 if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
916 // Export and GDS are tracked individually, either may trigger a waitcnt
917 // for EXEC.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000918 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
919 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
920 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
921 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000922 Wait.ExpCnt = 0;
923 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000924 }
925
926#if 0 // TODO: the following code to handle CALL.
927 // The argument passing for CALLs should suffice for VM_CNT and LGKM_CNT.
928 // However, there is a problem with EXP_CNT, because the call cannot
929 // easily tell if a register is used in the function, and if it did, then
930 // the referring instruction would have to have an S_WAITCNT, which is
931 // dependent on all call sites. So Instead, force S_WAITCNT for EXP_CNTs
932 // before the call.
933 if (MI.getOpcode() == SC_CALL) {
934 if (ScoreBrackets->getScoreUB(EXP_CNT) >
Evgeny Mankovbf975172017-08-16 16:47:29 +0000935 ScoreBrackets->getScoreLB(EXP_CNT)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000936 ScoreBrackets->setScoreLB(EXP_CNT, ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +0000937 EmitWaitcnt |= CNT_MASK(EXP_CNT);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000938 }
939 }
940#endif
941
Matt Arsenault0ed39d32017-07-21 18:54:54 +0000942 // FIXME: Should not be relying on memoperands.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000943 // Look at the source operands of every instruction to see if
944 // any of them results from a previous memory operation that affects
945 // its current usage. If so, an s_waitcnt instruction needs to be
946 // emitted.
947 // If the source operand was defined by a load, add the s_waitcnt
948 // instruction.
949 for (const MachineMemOperand *Memop : MI.memoperands()) {
950 unsigned AS = Memop->getAddrSpace();
Matt Arsenault0da63502018-08-31 05:49:54 +0000951 if (AS != AMDGPUAS::LOCAL_ADDRESS)
Kannan Narayananacb089e2017-04-12 03:25:12 +0000952 continue;
953 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
954 // VM_CNT is only relevant to vgpr or LDS.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000955 ScoreBrackets.determineWait(
956 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000957 }
Matt Arsenault0ed39d32017-07-21 18:54:54 +0000958
Kannan Narayananacb089e2017-04-12 03:25:12 +0000959 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
960 const MachineOperand &Op = MI.getOperand(I);
961 const MachineRegisterInfo &MRIA = *MRI;
962 RegInterval Interval =
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000963 ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, I, false);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000964 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
965 if (TRI->isVGPR(MRIA, Op.getReg())) {
966 // VM_CNT is only relevant to vgpr or LDS.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000967 ScoreBrackets.determineWait(
968 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000969 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000970 ScoreBrackets.determineWait(
971 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000972 }
973 }
974 // End of for loop that looks at all source operands to decide vm_wait_cnt
975 // and lgk_wait_cnt.
976
977 // Two cases are handled for destination operands:
978 // 1) If the destination operand was defined by a load, add the s_waitcnt
979 // instruction to guarantee the right WAW order.
980 // 2) If a destination operand that was used by a recent export/store ins,
981 // add s_waitcnt on exp_cnt to guarantee the WAR order.
982 if (MI.mayStore()) {
Matt Arsenault0ed39d32017-07-21 18:54:54 +0000983 // FIXME: Should not be relying on memoperands.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000984 for (const MachineMemOperand *Memop : MI.memoperands()) {
985 unsigned AS = Memop->getAddrSpace();
Matt Arsenault0da63502018-08-31 05:49:54 +0000986 if (AS != AMDGPUAS::LOCAL_ADDRESS)
Kannan Narayananacb089e2017-04-12 03:25:12 +0000987 continue;
988 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000989 ScoreBrackets.determineWait(
990 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
991 ScoreBrackets.determineWait(
992 EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000993 }
994 }
995 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
996 MachineOperand &Def = MI.getOperand(I);
997 const MachineRegisterInfo &MRIA = *MRI;
998 RegInterval Interval =
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000999 ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, I, true);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001000 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1001 if (TRI->isVGPR(MRIA, Def.getReg())) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001002 ScoreBrackets.determineWait(
1003 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1004 ScoreBrackets.determineWait(
1005 EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001006 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001007 ScoreBrackets.determineWait(
1008 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001009 }
1010 } // End of for loop that looks at all dest operands.
1011 }
1012
Kannan Narayananacb089e2017-04-12 03:25:12 +00001013 // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1014 // occurs before the instruction. Doing it here prevents any additional
1015 // S_WAITCNTs from being emitted if the instruction was marked as
1016 // requiring a WAITCNT beforehand.
Konstantin Zhuravlyovbe6c0ca2017-06-02 17:40:26 +00001017 if (MI.getOpcode() == AMDGPU::S_BARRIER &&
1018 !ST->hasAutoWaitcntBeforeBarrier()) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001019 Wait = Wait.combined(AMDGPU::Waitcnt::allZero(IV));
Kannan Narayananacb089e2017-04-12 03:25:12 +00001020 }
1021
1022 // TODO: Remove this work-around, enable the assert for Bug 457939
1023 // after fixing the scheduler. Also, the Shader Compiler code is
1024 // independent of target.
Tom Stellardc5a154d2018-06-28 23:47:12 +00001025 if (readsVCCZ(MI) && ST->getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001026 if (ScoreBrackets.getScoreLB(LGKM_CNT) <
1027 ScoreBrackets.getScoreUB(LGKM_CNT) &&
1028 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001029 Wait.LgkmCnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001030 }
1031 }
1032
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001033 // Early-out if no wait is indicated.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001034 if (!ScoreBrackets.simplifyWaitcnt(Wait) && !IsForceEmitWaitcnt) {
1035 bool Modified = false;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001036 if (OldWaitcntInstr) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001037 for (auto II = OldWaitcntInstr->getIterator(), NextI = std::next(II);
1038 &*II != &MI; II = NextI, ++NextI) {
1039 if (II->isDebugInstr())
1040 continue;
1041
1042 if (TrackedWaitcntSet.count(&*II)) {
1043 TrackedWaitcntSet.erase(&*II);
1044 II->eraseFromParent();
1045 Modified = true;
1046 } else if (II->getOpcode() == AMDGPU::S_WAITCNT) {
1047 int64_t Imm = II->getOperand(0).getImm();
1048 ScoreBrackets.applyWaitcnt(AMDGPU::decodeWaitcnt(IV, Imm));
1049 } else {
1050 assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT);
1051 assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1052 ScoreBrackets.applyWaitcnt(
1053 AMDGPU::Waitcnt(0, 0, 0, II->getOperand(1).getImm()));
1054 }
Stanislav Mekhanoshindb39b4b2018-02-08 00:18:35 +00001055 }
Nicolai Haehnle61396ff2018-11-07 21:53:36 +00001056 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001057 return Modified;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001058 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001059
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001060 if (ForceEmitZeroWaitcnts)
Stanislav Mekhanoshin956b0be2019-04-25 18:53:41 +00001061 Wait = AMDGPU::Waitcnt::allZero(IV);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001062
1063 if (ForceEmitWaitcnt[VM_CNT])
1064 Wait.VmCnt = 0;
1065 if (ForceEmitWaitcnt[EXP_CNT])
1066 Wait.ExpCnt = 0;
1067 if (ForceEmitWaitcnt[LGKM_CNT])
1068 Wait.LgkmCnt = 0;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001069 if (ForceEmitWaitcnt[VS_CNT])
1070 Wait.VsCnt = 0;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001071
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001072 ScoreBrackets.applyWaitcnt(Wait);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001073
1074 AMDGPU::Waitcnt OldWait;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001075 bool Modified = false;
1076
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001077 if (OldWaitcntInstr) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001078 for (auto II = OldWaitcntInstr->getIterator(), NextI = std::next(II);
1079 &*II != &MI; II = NextI, NextI++) {
1080 if (II->isDebugInstr())
1081 continue;
1082
1083 if (II->getOpcode() == AMDGPU::S_WAITCNT) {
1084 unsigned IEnc = II->getOperand(0).getImm();
1085 AMDGPU::Waitcnt IWait = AMDGPU::decodeWaitcnt(IV, IEnc);
1086 OldWait = OldWait.combined(IWait);
1087 if (!TrackedWaitcntSet.count(&*II))
1088 Wait = Wait.combined(IWait);
1089 unsigned NewEnc = AMDGPU::encodeWaitcnt(IV, Wait);
1090 if (IEnc != NewEnc) {
1091 II->getOperand(0).setImm(NewEnc);
1092 Modified = true;
1093 }
1094 Wait.VmCnt = ~0u;
1095 Wait.LgkmCnt = ~0u;
1096 Wait.ExpCnt = ~0u;
1097 } else {
1098 assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT);
1099 assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1100
1101 unsigned ICnt = II->getOperand(1).getImm();
1102 OldWait.VsCnt = std::min(OldWait.VsCnt, ICnt);
1103 if (!TrackedWaitcntSet.count(&*II))
1104 Wait.VsCnt = std::min(Wait.VsCnt, ICnt);
1105 if (Wait.VsCnt != ICnt) {
1106 II->getOperand(1).setImm(Wait.VsCnt);
1107 Modified = true;
1108 }
1109 Wait.VsCnt = ~0u;
1110 }
1111
1112 LLVM_DEBUG(dbgs() << "updateWaitcntInBlock\n"
1113 << "Old Instr: " << MI << '\n'
1114 << "New Instr: " << *II << '\n');
1115
1116 if (!Wait.hasWait())
1117 return Modified;
1118 }
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001119 }
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001120
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001121 if (Wait.VmCnt != ~0u || Wait.LgkmCnt != ~0u || Wait.ExpCnt != ~0u) {
1122 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001123 auto SWaitInst = BuildMI(*MI.getParent(), MI.getIterator(),
1124 MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1125 .addImm(Enc);
1126 TrackedWaitcntSet.insert(SWaitInst);
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001127 Modified = true;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001128
1129 LLVM_DEBUG(dbgs() << "insertWaitcntInBlock\n"
1130 << "Old Instr: " << MI << '\n'
1131 << "New Instr: " << *SWaitInst << '\n');
Kannan Narayananacb089e2017-04-12 03:25:12 +00001132 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001133
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001134 if (Wait.VsCnt != ~0u) {
1135 assert(ST->hasVscnt());
1136
1137 auto SWaitInst =
1138 BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
1139 TII->get(AMDGPU::S_WAITCNT_VSCNT))
1140 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1141 .addImm(Wait.VsCnt);
1142 TrackedWaitcntSet.insert(SWaitInst);
1143 Modified = true;
1144
1145 LLVM_DEBUG(dbgs() << "insertWaitcntInBlock\n"
1146 << "Old Instr: " << MI << '\n'
1147 << "New Instr: " << *SWaitInst << '\n');
1148 }
1149
1150 return Modified;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001151}
1152
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001153// This is a flat memory operation. Check to see if it has memory
1154// tokens for both LDS and Memory, and if so mark it as a flat.
1155bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
1156 if (MI.memoperands_empty())
1157 return true;
1158
1159 for (const MachineMemOperand *Memop : MI.memoperands()) {
1160 unsigned AS = Memop->getAddrSpace();
Matt Arsenault0da63502018-08-31 05:49:54 +00001161 if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS)
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001162 return true;
1163 }
1164
1165 return false;
1166}
1167
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001168void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
1169 WaitcntBrackets *ScoreBrackets) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001170 // Now look at the instruction opcode. If it is a memory access
1171 // instruction, update the upper-bound of the appropriate counter's
1172 // bracket and the destination operand scores.
1173 // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001174 if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
Marek Olsakc5cec5e2019-01-16 15:43:53 +00001175 if (TII->isAlwaysGDS(Inst.getOpcode()) ||
1176 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001177 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1178 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1179 } else {
1180 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1181 }
1182 } else if (TII->isFLAT(Inst)) {
1183 assert(Inst.mayLoad() || Inst.mayStore());
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001184
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001185 if (TII->usesVM_CNT(Inst)) {
1186 if (!ST->hasVscnt())
1187 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1188 else if (Inst.mayLoad() &&
1189 AMDGPU::getAtomicRetOp(Inst.getOpcode()) == -1)
1190 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1191 else
1192 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1193 }
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001194
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001195 if (TII->usesLGKM_CNT(Inst)) {
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001196 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001197
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001198 // This is a flat memory operation, so note it - it will require
1199 // that both the VM and LGKM be flushed to zero if it is pending when
1200 // a VM or LGKM dependency occurs.
1201 if (mayAccessLDSThroughFlat(Inst))
1202 ScoreBrackets->setPendingFlat();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001203 }
1204 } else if (SIInstrInfo::isVMEM(Inst) &&
1205 // TODO: get a better carve out.
1206 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1 &&
1207 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_SC &&
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001208 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_VOL &&
1209 Inst.getOpcode() != AMDGPU::BUFFER_GL0_INV &&
1210 Inst.getOpcode() != AMDGPU::BUFFER_GL1_INV) {
1211 if (!ST->hasVscnt())
1212 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1213 else if ((Inst.mayLoad() &&
1214 AMDGPU::getAtomicRetOp(Inst.getOpcode()) == -1) ||
1215 /* IMAGE_GET_RESINFO / IMAGE_GET_LOD */
1216 (TII->isMIMG(Inst) && !Inst.mayLoad() && !Inst.mayStore()))
1217 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1218 else if (Inst.mayStore())
1219 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1220
Mark Searles2a19af62018-04-26 16:11:19 +00001221 if (ST->vmemWriteNeedsExpWaitcnt() &&
Mark Searles11d0a042017-05-31 16:44:23 +00001222 (Inst.mayStore() || AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001223 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1224 }
1225 } else if (TII->isSMRD(Inst)) {
1226 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1227 } else {
1228 switch (Inst.getOpcode()) {
1229 case AMDGPU::S_SENDMSG:
1230 case AMDGPU::S_SENDMSGHALT:
1231 ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1232 break;
1233 case AMDGPU::EXP:
1234 case AMDGPU::EXP_DONE: {
1235 int Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1236 if (Imm >= 32 && Imm <= 63)
1237 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1238 else if (Imm >= 12 && Imm <= 15)
1239 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1240 else
1241 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1242 break;
1243 }
1244 case AMDGPU::S_MEMTIME:
1245 case AMDGPU::S_MEMREALTIME:
1246 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1247 break;
1248 default:
1249 break;
1250 }
1251 }
1252}
1253
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001254bool WaitcntBrackets::mergeScore(const MergeInfo &M, uint32_t &Score,
1255 uint32_t OtherScore) {
1256 uint32_t MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
1257 uint32_t OtherShifted =
1258 OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
1259 Score = std::max(MyShifted, OtherShifted);
1260 return OtherShifted > MyShifted;
1261}
Kannan Narayananacb089e2017-04-12 03:25:12 +00001262
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001263/// Merge the pending events and associater score brackets of \p Other into
1264/// this brackets status.
1265///
1266/// Returns whether the merge resulted in a change that requires tighter waits
1267/// (i.e. the merged brackets strictly dominate the original brackets).
1268bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
1269 bool StrictDom = false;
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001270
Nicolai Haehnleae369d72018-11-29 11:06:11 +00001271 for (auto T : inst_counter_types()) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001272 // Merge event flags for this counter
1273 const bool OldOutOfOrder = counterOutOfOrder(T);
1274 const uint32_t OldEvents = PendingEvents & WaitEventMaskForInst[T];
1275 const uint32_t OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T];
1276 if (OtherEvents & ~OldEvents)
1277 StrictDom = true;
1278 if (Other.MixedPendingEvents[T] ||
1279 (OldEvents && OtherEvents && OldEvents != OtherEvents))
1280 MixedPendingEvents[T] = true;
1281 PendingEvents |= OtherEvents;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001282
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001283 // Merge scores for this counter
1284 const uint32_t MyPending = ScoreUBs[T] - ScoreLBs[T];
1285 const uint32_t OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
1286 MergeInfo M;
1287 M.OldLB = ScoreLBs[T];
1288 M.OtherLB = Other.ScoreLBs[T];
1289 M.MyShift = OtherPending > MyPending ? OtherPending - MyPending : 0;
1290 M.OtherShift = ScoreUBs[T] - Other.ScoreUBs[T] + M.MyShift;
1291
1292 const uint32_t NewUB = ScoreUBs[T] + M.MyShift;
1293 if (NewUB < ScoreUBs[T])
1294 report_fatal_error("waitcnt score overflow");
1295 ScoreUBs[T] = NewUB;
1296 ScoreLBs[T] = std::min(M.OldLB + M.MyShift, M.OtherLB + M.OtherShift);
1297
1298 StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
1299
1300 bool RegStrictDom = false;
1301 for (int J = 0, E = std::max(getMaxVGPR(), Other.getMaxVGPR()) + 1; J != E;
1302 J++) {
1303 RegStrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001304 }
1305
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001306 if (T == LGKM_CNT) {
1307 for (int J = 0, E = std::max(getMaxSGPR(), Other.getMaxSGPR()) + 1;
1308 J != E; J++) {
1309 RegStrictDom |= mergeScore(M, SgprScores[J], Other.SgprScores[J]);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001310 }
1311 }
1312
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001313 if (RegStrictDom && !OldOutOfOrder)
1314 StrictDom = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001315 }
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001316
Carl Ritsonc521ac32018-12-19 10:17:49 +00001317 VgprUB = std::max(getMaxVGPR(), Other.getMaxVGPR());
1318 SgprUB = std::max(getMaxSGPR(), Other.getMaxSGPR());
1319
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001320 return StrictDom;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001321}
1322
1323// Generate s_waitcnt instructions where needed.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001324bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1325 MachineBasicBlock &Block,
1326 WaitcntBrackets &ScoreBrackets) {
1327 bool Modified = false;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001328
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001329 LLVM_DEBUG({
Mark Searlesec581832018-04-25 19:21:26 +00001330 dbgs() << "*** Block" << Block.getNumber() << " ***";
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001331 ScoreBrackets.dump();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001332 });
1333
Kannan Narayananacb089e2017-04-12 03:25:12 +00001334 // Walk over the instructions.
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001335 MachineInstr *OldWaitcntInstr = nullptr;
1336
Kannan Narayananacb089e2017-04-12 03:25:12 +00001337 for (MachineBasicBlock::iterator Iter = Block.begin(), E = Block.end();
1338 Iter != E;) {
1339 MachineInstr &Inst = *Iter;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001340
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001341 // Track pre-existing waitcnts from earlier iterations.
1342 if (Inst.getOpcode() == AMDGPU::S_WAITCNT ||
1343 (Inst.getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1344 Inst.getOperand(0).isReg() &&
1345 Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL)) {
1346 if (!OldWaitcntInstr)
1347 OldWaitcntInstr = &Inst;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001348 ++Iter;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001349 continue;
1350 }
1351
Kannan Narayananacb089e2017-04-12 03:25:12 +00001352 bool VCCZBugWorkAround = false;
1353 if (readsVCCZ(Inst) &&
Mark Searles24c92ee2018-02-07 02:21:21 +00001354 (!VCCZBugHandledSet.count(&Inst))) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001355 if (ScoreBrackets.getScoreLB(LGKM_CNT) <
1356 ScoreBrackets.getScoreUB(LGKM_CNT) &&
1357 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
Tom Stellardc5a154d2018-06-28 23:47:12 +00001358 if (ST->getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS)
Kannan Narayananacb089e2017-04-12 03:25:12 +00001359 VCCZBugWorkAround = true;
1360 }
1361 }
1362
1363 // Generate an s_waitcnt instruction to be placed before
1364 // cur_Inst, if needed.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001365 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001366 OldWaitcntInstr = nullptr;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001367
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001368 updateEventWaitcntAfter(Inst, &ScoreBrackets);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001369
1370#if 0 // TODO: implement resource type check controlled by options with ub = LB.
1371 // If this instruction generates a S_SETVSKIP because it is an
1372 // indexed resource, and we are on Tahiti, then it will also force
1373 // an S_WAITCNT vmcnt(0)
1374 if (RequireCheckResourceType(Inst, context)) {
1375 // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1376 ScoreBrackets->setScoreLB(VM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +00001377 ScoreBrackets->getScoreUB(VM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +00001378 }
1379#endif
1380
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001381 LLVM_DEBUG({
Mark Searles94ae3b22018-01-30 17:17:06 +00001382 Inst.print(dbgs());
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001383 ScoreBrackets.dump();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001384 });
1385
1386 // Check to see if this is a GWS instruction. If so, and if this is CI or
1387 // VI, then the generated code sequence will include an S_WAITCNT 0.
1388 // TODO: Are these the only GWS instructions?
1389 if (Inst.getOpcode() == AMDGPU::DS_GWS_INIT ||
1390 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_V ||
1391 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_BR ||
1392 Inst.getOpcode() == AMDGPU::DS_GWS_SEMA_P ||
1393 Inst.getOpcode() == AMDGPU::DS_GWS_BARRIER) {
1394 // TODO: && context->target_info->GwsRequiresMemViolTest() ) {
Stanislav Mekhanoshin956b0be2019-04-25 18:53:41 +00001395 ScoreBrackets.applyWaitcnt(AMDGPU::Waitcnt::allZeroExceptVsCnt());
Kannan Narayananacb089e2017-04-12 03:25:12 +00001396 }
1397
1398 // TODO: Remove this work-around after fixing the scheduler and enable the
1399 // assert above.
1400 if (VCCZBugWorkAround) {
1401 // Restore the vccz bit. Any time a value is written to vcc, the vcc
1402 // bit is updated, so we can restore the bit by reading the value of
1403 // vcc and then writing it back to the register.
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001404 BuildMI(Block, Inst, Inst.getDebugLoc(),
1405 TII->get(AMDGPU::S_MOV_B64),
Kannan Narayananacb089e2017-04-12 03:25:12 +00001406 AMDGPU::VCC)
1407 .addReg(AMDGPU::VCC);
1408 VCCZBugHandledSet.insert(&Inst);
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001409 Modified = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001410 }
1411
Kannan Narayananacb089e2017-04-12 03:25:12 +00001412 ++Iter;
1413 }
1414
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001415 return Modified;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001416}
1417
1418bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
Tom Stellard5bfbae52018-07-11 20:59:01 +00001419 ST = &MF.getSubtarget<GCNSubtarget>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001420 TII = ST->getInstrInfo();
1421 TRI = &TII->getRegisterInfo();
1422 MRI = &MF.getRegInfo();
Konstantin Zhuravlyov71e43ee2018-09-12 18:50:47 +00001423 IV = AMDGPU::getIsaVersion(ST->getCPU());
Mark Searles11d0a042017-05-31 16:44:23 +00001424 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001425
Mark Searles4a0f2c52018-05-07 14:43:28 +00001426 ForceEmitZeroWaitcnts = ForceEmitZeroFlag;
Nicolai Haehnleae369d72018-11-29 11:06:11 +00001427 for (auto T : inst_counter_types())
Mark Searlesec581832018-04-25 19:21:26 +00001428 ForceEmitWaitcnt[T] = false;
1429
Kannan Narayananacb089e2017-04-12 03:25:12 +00001430 HardwareLimits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1431 HardwareLimits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1432 HardwareLimits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001433 HardwareLimits.VscntMax = ST->hasVscnt() ? 63 : 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001434
1435 HardwareLimits.NumVGPRsMax = ST->getAddressableNumVGPRs();
1436 HardwareLimits.NumSGPRsMax = ST->getAddressableNumSGPRs();
1437 assert(HardwareLimits.NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1438 assert(HardwareLimits.NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1439
1440 RegisterEncoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1441 RegisterEncoding.VGPRL =
1442 RegisterEncoding.VGPR0 + HardwareLimits.NumVGPRsMax - 1;
1443 RegisterEncoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1444 RegisterEncoding.SGPRL =
1445 RegisterEncoding.SGPR0 + HardwareLimits.NumSGPRsMax - 1;
1446
Mark Searles24c92ee2018-02-07 02:21:21 +00001447 TrackedWaitcntSet.clear();
Mark Searles24c92ee2018-02-07 02:21:21 +00001448 VCCZBugHandledSet.clear();
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001449 RpotIdxMap.clear();
1450 BlockInfos.clear();
Mark Searles24c92ee2018-02-07 02:21:21 +00001451
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001452 // Keep iterating over the blocks in reverse post order, inserting and
1453 // updating s_waitcnt where needed, until a fix point is reached.
1454 for (MachineBasicBlock *MBB :
1455 ReversePostOrderTraversal<MachineFunction *>(&MF)) {
1456 RpotIdxMap[MBB] = BlockInfos.size();
1457 BlockInfos.emplace_back(MBB);
1458 }
1459
1460 std::unique_ptr<WaitcntBrackets> Brackets;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001461 bool Modified = false;
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001462 bool Repeat;
1463 do {
1464 Repeat = false;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001465
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001466 for (BlockInfo &BI : BlockInfos) {
1467 if (!BI.Dirty)
1468 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001469
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001470 unsigned Idx = std::distance(&*BlockInfos.begin(), &BI);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001471
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001472 if (BI.Incoming) {
1473 if (!Brackets)
1474 Brackets = llvm::make_unique<WaitcntBrackets>(*BI.Incoming);
1475 else
1476 *Brackets = *BI.Incoming;
1477 } else {
1478 if (!Brackets)
1479 Brackets = llvm::make_unique<WaitcntBrackets>(ST);
1480 else
1481 Brackets->clear();
Mark Searles1bc6e712018-04-19 15:42:30 +00001482 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001483
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001484 Modified |= insertWaitcntInBlock(MF, *BI.MBB, *Brackets);
1485 BI.Dirty = false;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001486
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001487 if (Brackets->hasPending()) {
1488 BlockInfo *MoveBracketsToSucc = nullptr;
1489 for (MachineBasicBlock *Succ : BI.MBB->successors()) {
1490 unsigned SuccIdx = RpotIdxMap[Succ];
1491 BlockInfo &SuccBI = BlockInfos[SuccIdx];
1492 if (!SuccBI.Incoming) {
1493 SuccBI.Dirty = true;
1494 if (SuccIdx <= Idx)
1495 Repeat = true;
1496 if (!MoveBracketsToSucc) {
1497 MoveBracketsToSucc = &SuccBI;
1498 } else {
1499 SuccBI.Incoming = llvm::make_unique<WaitcntBrackets>(*Brackets);
1500 }
1501 } else if (SuccBI.Incoming->merge(*Brackets)) {
1502 SuccBI.Dirty = true;
1503 if (SuccIdx <= Idx)
1504 Repeat = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001505 }
1506 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001507 if (MoveBracketsToSucc)
1508 MoveBracketsToSucc->Incoming = std::move(Brackets);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001509 }
1510 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001511 } while (Repeat);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001512
1513 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1514
1515 bool HaveScalarStores = false;
1516
1517 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE;
1518 ++BI) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001519 MachineBasicBlock &MBB = *BI;
1520
1521 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1522 ++I) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001523 if (!HaveScalarStores && TII->isScalarStore(*I))
1524 HaveScalarStores = true;
1525
1526 if (I->getOpcode() == AMDGPU::S_ENDPGM ||
1527 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1528 EndPgmBlocks.push_back(&MBB);
1529 }
1530 }
1531
1532 if (HaveScalarStores) {
1533 // If scalar writes are used, the cache must be flushed or else the next
1534 // wave to reuse the same scratch memory can be clobbered.
1535 //
1536 // Insert s_dcache_wb at wave termination points if there were any scalar
1537 // stores, and only if the cache hasn't already been flushed. This could be
1538 // improved by looking across blocks for flushes in postdominating blocks
1539 // from the stores but an explicitly requested flush is probably very rare.
1540 for (MachineBasicBlock *MBB : EndPgmBlocks) {
1541 bool SeenDCacheWB = false;
1542
1543 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
1544 ++I) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001545 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1546 SeenDCacheWB = true;
1547 else if (TII->isScalarStore(*I))
1548 SeenDCacheWB = false;
1549
1550 // FIXME: It would be better to insert this before a waitcnt if any.
1551 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1552 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1553 !SeenDCacheWB) {
1554 Modified = true;
1555 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
1556 }
1557 }
1558 }
1559 }
1560
Mark Searles11d0a042017-05-31 16:44:23 +00001561 if (!MFI->isEntryFunction()) {
1562 // Wait for any outstanding memory operations that the input registers may
Hiroshi Inouec8e92452018-01-29 05:17:03 +00001563 // depend on. We can't track them and it's better to the wait after the
Mark Searles11d0a042017-05-31 16:44:23 +00001564 // costly call sequence.
1565
1566 // TODO: Could insert earlier and schedule more liberally with operations
1567 // that only use caller preserved registers.
1568 MachineBasicBlock &EntryBB = MF.front();
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001569 if (ST->hasVscnt())
1570 BuildMI(EntryBB, EntryBB.getFirstNonPHI(), DebugLoc(),
1571 TII->get(AMDGPU::S_WAITCNT_VSCNT))
1572 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1573 .addImm(0);
Mark Searlesed54ff12018-05-30 16:27:57 +00001574 BuildMI(EntryBB, EntryBB.getFirstNonPHI(), DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1575 .addImm(0);
Mark Searles11d0a042017-05-31 16:44:23 +00001576
1577 Modified = true;
1578 }
1579
Kannan Narayananacb089e2017-04-12 03:25:12 +00001580 return Modified;
1581}