blob: 14b12f901979dbc77fe7b3dcd89269689c90a4fc [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
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000376 struct BlockInfo {
377 MachineBasicBlock *MBB;
378 std::unique_ptr<WaitcntBrackets> Incoming;
379 bool Dirty = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000380
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000381 explicit BlockInfo(MachineBasicBlock *MBB) : MBB(MBB) {}
382 };
Kannan Narayananacb089e2017-04-12 03:25:12 +0000383
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000384 std::vector<BlockInfo> BlockInfos; // by reverse post-order traversal index
385 DenseMap<MachineBasicBlock *, unsigned> RpotIdxMap;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000386
Mark Searles4a0f2c52018-05-07 14:43:28 +0000387 // ForceEmitZeroWaitcnts: force all waitcnts insts to be s_waitcnt 0
388 // because of amdgpu-waitcnt-forcezero flag
389 bool ForceEmitZeroWaitcnts;
Mark Searlesec581832018-04-25 19:21:26 +0000390 bool ForceEmitWaitcnt[NUM_INST_CNTS];
391
Kannan Narayananacb089e2017-04-12 03:25:12 +0000392public:
393 static char ID;
394
Konstantin Zhuravlyov77747772018-06-26 21:33:38 +0000395 SIInsertWaitcnts() : MachineFunctionPass(ID) {
396 (void)ForceExpCounter;
397 (void)ForceLgkmCounter;
398 (void)ForceVMCounter;
399 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000400
401 bool runOnMachineFunction(MachineFunction &MF) override;
402
403 StringRef getPassName() const override {
404 return "SI insert wait instructions";
405 }
406
407 void getAnalysisUsage(AnalysisUsage &AU) const override {
408 AU.setPreservesCFG();
Kannan Narayananacb089e2017-04-12 03:25:12 +0000409 MachineFunctionPass::getAnalysisUsage(AU);
410 }
411
Mark Searlesec581832018-04-25 19:21:26 +0000412 bool isForceEmitWaitcnt() const {
Nicolai Haehnleae369d72018-11-29 11:06:11 +0000413 for (auto T : inst_counter_types())
Mark Searlesec581832018-04-25 19:21:26 +0000414 if (ForceEmitWaitcnt[T])
415 return true;
416 return false;
417 }
418
419 void setForceEmitWaitcnt() {
420// For non-debug builds, ForceEmitWaitcnt has been initialized to false;
421// For debug builds, get the debug counter info and adjust if need be
422#ifndef NDEBUG
423 if (DebugCounter::isCounterSet(ForceExpCounter) &&
424 DebugCounter::shouldExecute(ForceExpCounter)) {
425 ForceEmitWaitcnt[EXP_CNT] = true;
426 } else {
427 ForceEmitWaitcnt[EXP_CNT] = false;
428 }
429
430 if (DebugCounter::isCounterSet(ForceLgkmCounter) &&
431 DebugCounter::shouldExecute(ForceLgkmCounter)) {
432 ForceEmitWaitcnt[LGKM_CNT] = true;
433 } else {
434 ForceEmitWaitcnt[LGKM_CNT] = false;
435 }
436
437 if (DebugCounter::isCounterSet(ForceVMCounter) &&
438 DebugCounter::shouldExecute(ForceVMCounter)) {
439 ForceEmitWaitcnt[VM_CNT] = true;
440 } else {
441 ForceEmitWaitcnt[VM_CNT] = false;
442 }
443#endif // NDEBUG
444 }
445
Matt Arsenault0ed39d32017-07-21 18:54:54 +0000446 bool mayAccessLDSThroughFlat(const MachineInstr &MI) const;
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000447 bool generateWaitcntInstBefore(MachineInstr &MI,
448 WaitcntBrackets &ScoreBrackets,
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000449 MachineInstr *OldWaitcntInstr);
Mark Searles70901b92018-04-24 15:59:59 +0000450 void updateEventWaitcntAfter(MachineInstr &Inst,
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000451 WaitcntBrackets *ScoreBrackets);
452 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block,
453 WaitcntBrackets &ScoreBrackets);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000454};
455
Eugene Zelenko59e12822017-08-08 00:47:13 +0000456} // end anonymous namespace
Kannan Narayananacb089e2017-04-12 03:25:12 +0000457
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000458RegInterval WaitcntBrackets::getRegInterval(const MachineInstr *MI,
459 const SIInstrInfo *TII,
460 const MachineRegisterInfo *MRI,
461 const SIRegisterInfo *TRI,
462 unsigned OpNo, bool Def) const {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000463 const MachineOperand &Op = MI->getOperand(OpNo);
464 if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()) ||
Stanislav Mekhanoshine67cc382019-07-11 21:19:33 +0000465 (Def && !Op.isDef()) || TRI->isAGPR(*MRI, Op.getReg()))
Kannan Narayananacb089e2017-04-12 03:25:12 +0000466 return {-1, -1};
467
468 // A use via a PW operand does not need a waitcnt.
469 // A partial write is not a WAW.
470 assert(!Op.getSubReg() || !Op.isUndef());
471
472 RegInterval Result;
473 const MachineRegisterInfo &MRIA = *MRI;
474
475 unsigned Reg = TRI->getEncodingValue(Op.getReg());
476
477 if (TRI->isVGPR(MRIA, Op.getReg())) {
478 assert(Reg >= RegisterEncoding.VGPR0 && Reg <= RegisterEncoding.VGPRL);
479 Result.first = Reg - RegisterEncoding.VGPR0;
480 assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
481 } else if (TRI->isSGPRReg(MRIA, Op.getReg())) {
482 assert(Reg >= RegisterEncoding.SGPR0 && Reg < SQ_MAX_PGM_SGPRS);
483 Result.first = Reg - RegisterEncoding.SGPR0 + NUM_ALL_VGPRS;
484 assert(Result.first >= NUM_ALL_VGPRS &&
485 Result.first < SQ_MAX_PGM_SGPRS + NUM_ALL_VGPRS);
486 }
487 // TODO: Handle TTMP
488 // else if (TRI->isTTMP(MRIA, Reg.getReg())) ...
489 else
490 return {-1, -1};
491
492 const MachineInstr &MIA = *MI;
493 const TargetRegisterClass *RC = TII->getOpRegClass(MIA, OpNo);
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +0000494 unsigned Size = TRI->getRegSizeInBits(*RC);
495 Result.second = Result.first + (Size / 32);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000496
497 return Result;
498}
499
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000500void WaitcntBrackets::setExpScore(const MachineInstr *MI,
501 const SIInstrInfo *TII,
502 const SIRegisterInfo *TRI,
503 const MachineRegisterInfo *MRI, unsigned OpNo,
504 uint32_t Val) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000505 RegInterval Interval = getRegInterval(MI, TII, MRI, TRI, OpNo, false);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000506 LLVM_DEBUG({
Kannan Narayananacb089e2017-04-12 03:25:12 +0000507 const MachineOperand &Opnd = MI->getOperand(OpNo);
508 assert(TRI->isVGPR(*MRI, Opnd.getReg()));
509 });
510 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
511 setRegScore(RegNo, EXP_CNT, Val);
512 }
513}
514
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000515void WaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
516 const SIRegisterInfo *TRI,
517 const MachineRegisterInfo *MRI,
518 WaitEventType E, MachineInstr &Inst) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000519 const MachineRegisterInfo &MRIA = *MRI;
520 InstCounterType T = eventCounter(E);
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000521 uint32_t CurrScore = getScoreUB(T) + 1;
522 if (CurrScore == 0)
523 report_fatal_error("InsertWaitcnt score wraparound");
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000524 // PendingEvents and ScoreUB need to be update regardless if this event
525 // changes the score of a register or not.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000526 // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000527 if (!hasPendingEvent(E)) {
528 if (PendingEvents & WaitEventMaskForInst[T])
529 MixedPendingEvents[T] = true;
530 PendingEvents |= 1 << E;
531 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000532 setScoreUB(T, CurrScore);
533
534 if (T == EXP_CNT) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000535 // Put score on the source vgprs. If this is a store, just use those
536 // specific register(s).
537 if (TII->isDS(Inst) && (Inst.mayStore() || Inst.mayLoad())) {
Matt Arsenault4d55d022019-06-19 19:55:27 +0000538 int AddrOpIdx =
539 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::addr);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000540 // All GDS operations must protect their address register (same as
541 // export.)
Matt Arsenault4d55d022019-06-19 19:55:27 +0000542 if (AddrOpIdx != -1) {
543 setExpScore(&Inst, TII, TRI, MRI, AddrOpIdx, CurrScore);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000544 }
Matt Arsenault4d55d022019-06-19 19:55:27 +0000545
Kannan Narayananacb089e2017-04-12 03:25:12 +0000546 if (Inst.mayStore()) {
Marek Olsakc5cec5e2019-01-16 15:43:53 +0000547 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
548 AMDGPU::OpName::data0) != -1) {
549 setExpScore(
550 &Inst, TII, TRI, MRI,
551 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data0),
552 CurrScore);
553 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000554 if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
555 AMDGPU::OpName::data1) != -1) {
556 setExpScore(&Inst, TII, TRI, MRI,
557 AMDGPU::getNamedOperandIdx(Inst.getOpcode(),
558 AMDGPU::OpName::data1),
559 CurrScore);
560 }
561 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1 &&
562 Inst.getOpcode() != AMDGPU::DS_GWS_INIT &&
563 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_V &&
564 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_BR &&
565 Inst.getOpcode() != AMDGPU::DS_GWS_SEMA_P &&
566 Inst.getOpcode() != AMDGPU::DS_GWS_BARRIER &&
567 Inst.getOpcode() != AMDGPU::DS_APPEND &&
568 Inst.getOpcode() != AMDGPU::DS_CONSUME &&
569 Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
570 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
571 const MachineOperand &Op = Inst.getOperand(I);
572 if (Op.isReg() && !Op.isDef() && TRI->isVGPR(MRIA, Op.getReg())) {
573 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
574 }
575 }
576 }
577 } else if (TII->isFLAT(Inst)) {
578 if (Inst.mayStore()) {
579 setExpScore(
580 &Inst, TII, TRI, MRI,
581 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
582 CurrScore);
583 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
584 setExpScore(
585 &Inst, TII, TRI, MRI,
586 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
587 CurrScore);
588 }
589 } else if (TII->isMIMG(Inst)) {
590 if (Inst.mayStore()) {
591 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
592 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
593 setExpScore(
594 &Inst, TII, TRI, MRI,
595 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
596 CurrScore);
597 }
598 } else if (TII->isMTBUF(Inst)) {
599 if (Inst.mayStore()) {
600 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
601 }
602 } else if (TII->isMUBUF(Inst)) {
603 if (Inst.mayStore()) {
604 setExpScore(&Inst, TII, TRI, MRI, 0, CurrScore);
605 } else if (AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1) {
606 setExpScore(
607 &Inst, TII, TRI, MRI,
608 AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::data),
609 CurrScore);
610 }
611 } else {
612 if (TII->isEXP(Inst)) {
613 // For export the destination registers are really temps that
614 // can be used as the actual source after export patching, so
615 // we need to treat them like sources and set the EXP_CNT
616 // score.
617 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
618 MachineOperand &DefMO = Inst.getOperand(I);
619 if (DefMO.isReg() && DefMO.isDef() &&
620 TRI->isVGPR(MRIA, DefMO.getReg())) {
621 setRegScore(TRI->getEncodingValue(DefMO.getReg()), EXP_CNT,
622 CurrScore);
623 }
624 }
625 }
626 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
627 MachineOperand &MO = Inst.getOperand(I);
628 if (MO.isReg() && !MO.isDef() && TRI->isVGPR(MRIA, MO.getReg())) {
629 setExpScore(&Inst, TII, TRI, MRI, I, CurrScore);
630 }
631 }
632 }
633#if 0 // TODO: check if this is handled by MUBUF code above.
634 } else if (Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORD ||
Evgeny Mankovbf975172017-08-16 16:47:29 +0000635 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX2 ||
636 Inst.getOpcode() == AMDGPU::BUFFER_STORE_DWORDX4) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000637 MachineOperand *MO = TII->getNamedOperand(Inst, AMDGPU::OpName::data);
638 unsigned OpNo;//TODO: find the OpNo for this operand;
639 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, OpNo, false);
640 for (signed RegNo = Interval.first; RegNo < Interval.second;
Evgeny Mankovbf975172017-08-16 16:47:29 +0000641 ++RegNo) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000642 setRegScore(RegNo + NUM_ALL_VGPRS, t, CurrScore);
643 }
644#endif
645 } else {
646 // Match the score to the destination registers.
647 for (unsigned I = 0, E = Inst.getNumOperands(); I != E; ++I) {
648 RegInterval Interval = getRegInterval(&Inst, TII, MRI, TRI, I, true);
649 if (T == VM_CNT && Interval.first >= NUM_ALL_VGPRS)
650 continue;
651 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
652 setRegScore(RegNo, T, CurrScore);
653 }
654 }
655 if (TII->isDS(Inst) && Inst.mayStore()) {
656 setRegScore(SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS, T, CurrScore);
657 }
658 }
659}
660
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000661void WaitcntBrackets::print(raw_ostream &OS) {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000662 OS << '\n';
Nicolai Haehnleae369d72018-11-29 11:06:11 +0000663 for (auto T : inst_counter_types()) {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000664 uint32_t LB = getScoreLB(T);
665 uint32_t UB = getScoreUB(T);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000666
667 switch (T) {
668 case VM_CNT:
669 OS << " VM_CNT(" << UB - LB << "): ";
670 break;
671 case LGKM_CNT:
672 OS << " LGKM_CNT(" << UB - LB << "): ";
673 break;
674 case EXP_CNT:
675 OS << " EXP_CNT(" << UB - LB << "): ";
676 break;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000677 case VS_CNT:
678 OS << " VS_CNT(" << UB - LB << "): ";
679 break;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000680 default:
681 OS << " UNKNOWN(" << UB - LB << "): ";
682 break;
683 }
684
685 if (LB < UB) {
686 // Print vgpr scores.
687 for (int J = 0; J <= getMaxVGPR(); J++) {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000688 uint32_t RegScore = getRegScore(J, T);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000689 if (RegScore <= LB)
690 continue;
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000691 uint32_t RelScore = RegScore - LB - 1;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000692 if (J < SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS) {
693 OS << RelScore << ":v" << J << " ";
694 } else {
695 OS << RelScore << ":ds ";
696 }
697 }
698 // Also need to print sgpr scores for lgkm_cnt.
699 if (T == LGKM_CNT) {
700 for (int J = 0; J <= getMaxSGPR(); J++) {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000701 uint32_t RegScore = getRegScore(J + NUM_ALL_VGPRS, LGKM_CNT);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000702 if (RegScore <= LB)
703 continue;
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000704 uint32_t RelScore = RegScore - LB - 1;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000705 OS << RelScore << ":s" << J << " ";
706 }
707 }
708 }
709 OS << '\n';
710 }
711 OS << '\n';
Kannan Narayananacb089e2017-04-12 03:25:12 +0000712}
713
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000714/// Simplify the waitcnt, in the sense of removing redundant counts, and return
715/// whether a waitcnt instruction is needed at all.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000716bool WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000717 return simplifyWaitcnt(VM_CNT, Wait.VmCnt) |
718 simplifyWaitcnt(EXP_CNT, Wait.ExpCnt) |
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000719 simplifyWaitcnt(LGKM_CNT, Wait.LgkmCnt) |
720 simplifyWaitcnt(VS_CNT, Wait.VsCnt);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000721}
722
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000723bool WaitcntBrackets::simplifyWaitcnt(InstCounterType T,
724 unsigned &Count) const {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000725 const uint32_t LB = getScoreLB(T);
726 const uint32_t UB = getScoreUB(T);
727 if (Count < UB && UB - Count > LB)
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000728 return true;
729
730 Count = ~0u;
731 return false;
732}
733
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000734void WaitcntBrackets::determineWait(InstCounterType T, uint32_t ScoreToWait,
735 AMDGPU::Waitcnt &Wait) const {
Kannan Narayananacb089e2017-04-12 03:25:12 +0000736 // If the score of src_operand falls within the bracket, we need an
737 // s_waitcnt instruction.
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000738 const uint32_t LB = getScoreLB(T);
739 const uint32_t UB = getScoreUB(T);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000740 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
Mark Searlesf0b93f12018-06-04 16:51:59 +0000741 if ((T == VM_CNT || T == LGKM_CNT) &&
742 hasPendingFlat() &&
743 !ST->hasFlatLgkmVMemCountInOrder()) {
744 // If there is a pending FLAT operation, and this is a VMem or LGKM
745 // waitcnt and the target can report early completion, then we need
746 // to force a waitcnt 0.
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000747 addWait(Wait, T, 0);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000748 } else if (counterOutOfOrder(T)) {
749 // Counter can get decremented out-of-order when there
Mark Searlesc3c02bd2018-03-14 22:04:32 +0000750 // are multiple types event in the bracket. Also emit an s_wait counter
Kannan Narayananacb089e2017-04-12 03:25:12 +0000751 // with a conservative value of 0 for the counter.
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000752 addWait(Wait, T, 0);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000753 } else {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000754 addWait(Wait, T, UB - ScoreToWait);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000755 }
756 }
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000757}
Kannan Narayananacb089e2017-04-12 03:25:12 +0000758
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000759void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000760 applyWaitcnt(VM_CNT, Wait.VmCnt);
761 applyWaitcnt(EXP_CNT, Wait.ExpCnt);
762 applyWaitcnt(LGKM_CNT, Wait.LgkmCnt);
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000763 applyWaitcnt(VS_CNT, Wait.VsCnt);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000764}
765
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000766void WaitcntBrackets::applyWaitcnt(InstCounterType T, unsigned Count) {
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000767 const uint32_t UB = getScoreUB(T);
768 if (Count >= UB)
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000769 return;
770 if (Count != 0) {
771 if (counterOutOfOrder(T))
772 return;
Nicolai Haehnleab43bf62018-11-29 11:06:21 +0000773 setScoreLB(T, std::max(getScoreLB(T), UB - Count));
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000774 } else {
775 setScoreLB(T, UB);
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000776 MixedPendingEvents[T] = false;
777 PendingEvents &= ~WaitEventMaskForInst[T];
778 }
779}
780
Kannan Narayananacb089e2017-04-12 03:25:12 +0000781// Where there are multiple types of event in the bracket of a counter,
782// the decrement may go out of order.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000783bool WaitcntBrackets::counterOutOfOrder(InstCounterType T) const {
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000784 // Scalar memory read always can go out of order.
785 if (T == LGKM_CNT && hasPendingEvent(SMEM_ACCESS))
786 return true;
787 return MixedPendingEvents[T];
Kannan Narayananacb089e2017-04-12 03:25:12 +0000788}
789
790INITIALIZE_PASS_BEGIN(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
791 false)
792INITIALIZE_PASS_END(SIInsertWaitcnts, DEBUG_TYPE, "SI Insert Waitcnts", false,
793 false)
794
795char SIInsertWaitcnts::ID = 0;
796
797char &llvm::SIInsertWaitcntsID = SIInsertWaitcnts::ID;
798
799FunctionPass *llvm::createSIInsertWaitcntsPass() {
800 return new SIInsertWaitcnts();
801}
802
803static bool readsVCCZ(const MachineInstr &MI) {
804 unsigned Opc = MI.getOpcode();
805 return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
806 !MI.getOperand(1).isUndef();
807}
808
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000809/// \returns true if the callee inserts an s_waitcnt 0 on function entry.
810static bool callWaitsOnFunctionEntry(const MachineInstr &MI) {
811 // Currently all conventions wait, but this may not always be the case.
812 //
813 // TODO: If IPRA is enabled, and the callee is isSafeForNoCSROpt, it may make
814 // senses to omit the wait and do it in the caller.
815 return true;
816}
817
818/// \returns true if the callee is expected to wait for any outstanding waits
819/// before returning.
820static bool callWaitsOnFunctionReturn(const MachineInstr &MI) {
821 return true;
822}
823
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000824/// Generate s_waitcnt instruction to be placed before cur_Inst.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000825/// Instructions of a given type are returned in order,
826/// but instructions of different types can complete out of order.
827/// We rely on this in-order completion
828/// and simply assign a score to the memory access instructions.
829/// We keep track of the active "score bracket" to determine
830/// if an access of a memory read requires an s_waitcnt
831/// and if so what the value of each counter is.
832/// The "score bracket" is bound by the lower bound and upper bound
833/// scores (*_score_LB and *_score_ub respectively).
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000834bool SIInsertWaitcnts::generateWaitcntInstBefore(
835 MachineInstr &MI, WaitcntBrackets &ScoreBrackets,
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000836 MachineInstr *OldWaitcntInstr) {
Mark Searles4a0f2c52018-05-07 14:43:28 +0000837 setForceEmitWaitcnt();
Mark Searlesec581832018-04-25 19:21:26 +0000838 bool IsForceEmitWaitcnt = isForceEmitWaitcnt();
839
Nicolai Haehnle61396ff2018-11-07 21:53:36 +0000840 if (MI.isDebugInstr())
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000841 return false;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000842
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000843 AMDGPU::Waitcnt Wait;
844
Kannan Narayananacb089e2017-04-12 03:25:12 +0000845 // See if this instruction has a forced S_WAITCNT VM.
846 // TODO: Handle other cases of NeedsWaitcntVmBefore()
Nicolai Haehnlef96456c2018-11-29 11:06:18 +0000847 if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000848 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000849 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL ||
850 MI.getOpcode() == AMDGPU::BUFFER_GL0_INV ||
851 MI.getOpcode() == AMDGPU::BUFFER_GL1_INV) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000852 Wait.VmCnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000853 }
854
855 // All waits must be resolved at call return.
856 // NOTE: this could be improved with knowledge of all call sites or
857 // with knowledge of the called routines.
Tom Stellardc5a154d2018-06-28 23:47:12 +0000858 if (MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000859 MI.getOpcode() == AMDGPU::S_SETPC_B64_return ||
860 (MI.isReturn() && MI.isCall() && !callWaitsOnFunctionEntry(MI))) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +0000861 Wait = Wait.combined(AMDGPU::Waitcnt::allZero(IV));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000862 }
863 // Resolve vm waits before gs-done.
864 else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
865 MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
866 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_) ==
867 AMDGPU::SendMsg::ID_GS_DONE)) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +0000868 Wait.VmCnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +0000869 }
870#if 0 // TODO: the following blocks of logic when we have fence.
871 else if (MI.getOpcode() == SC_FENCE) {
872 const unsigned int group_size =
873 context->shader_info->GetMaxThreadGroupSize();
874 // group_size == 0 means thread group size is unknown at compile time
875 const bool group_is_multi_wave =
876 (group_size == 0 || group_size > target_info->GetWaveFrontSize());
877 const bool fence_is_global = !((SCInstInternalMisc*)Inst)->IsGroupFence();
878
879 for (unsigned int i = 0; i < Inst->NumSrcOperands(); i++) {
880 SCRegType src_type = Inst->GetSrcType(i);
881 switch (src_type) {
882 case SCMEM_LDS:
883 if (group_is_multi_wave ||
Evgeny Mankovbf975172017-08-16 16:47:29 +0000884 context->OptFlagIsOn(OPT_R1100_LDSMEM_FENCE_CHICKEN_BIT)) {
Mark Searles70901b92018-04-24 15:59:59 +0000885 EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
Kannan Narayananacb089e2017-04-12 03:25:12 +0000886 ScoreBrackets->getScoreUB(LGKM_CNT));
887 // LDS may have to wait for VM_CNT after buffer load to LDS
888 if (target_info->HasBufferLoadToLDS()) {
Mark Searles70901b92018-04-24 15:59:59 +0000889 EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
Kannan Narayananacb089e2017-04-12 03:25:12 +0000890 ScoreBrackets->getScoreUB(VM_CNT));
891 }
892 }
893 break;
894
895 case SCMEM_GDS:
896 if (group_is_multi_wave || fence_is_global) {
Mark Searles70901b92018-04-24 15:59:59 +0000897 EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000898 ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +0000899 EmitWaitcnt |= ScoreBrackets->updateByWait(LGKM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000900 ScoreBrackets->getScoreUB(LGKM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000901 }
902 break;
903
904 case SCMEM_UAV:
905 case SCMEM_TFBUF:
906 case SCMEM_RING:
907 case SCMEM_SCATTER:
908 if (group_is_multi_wave || fence_is_global) {
Mark Searles70901b92018-04-24 15:59:59 +0000909 EmitWaitcnt |= ScoreBrackets->updateByWait(EXP_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000910 ScoreBrackets->getScoreUB(EXP_CNT));
Mark Searles70901b92018-04-24 15:59:59 +0000911 EmitWaitcnt |= ScoreBrackets->updateByWait(VM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +0000912 ScoreBrackets->getScoreUB(VM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +0000913 }
914 break;
915
916 case SCMEM_SCRATCH:
917 default:
918 break;
919 }
920 }
921 }
922#endif
923
924 // Export & GDS instructions do not read the EXEC mask until after the export
925 // is granted (which can occur well after the instruction is issued).
926 // The shader program must flush all EXP operations on the export-count
927 // before overwriting the EXEC mask.
928 else {
929 if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
930 // Export and GDS are tracked individually, either may trigger a waitcnt
931 // for EXEC.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000932 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
933 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
934 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
935 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
Nicolai Haehnled1f45da2018-11-29 11:06:14 +0000936 Wait.ExpCnt = 0;
937 }
Kannan Narayananacb089e2017-04-12 03:25:12 +0000938 }
939
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000940 if (MI.isCall() && callWaitsOnFunctionEntry(MI)) {
Austin Kerbowd11b93e2019-10-28 09:39:20 -0700941 // The function is going to insert a wait on everything in its prolog.
942 // This still needs to be careful if the call target is a load (e.g. a GOT
943 // load). We also need to check WAW depenancy with saved PC.
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000944 Wait = AMDGPU::Waitcnt();
Kannan Narayananacb089e2017-04-12 03:25:12 +0000945
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000946 int CallAddrOpIdx =
947 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
Austin Kerbowd11b93e2019-10-28 09:39:20 -0700948 RegInterval CallAddrOpInterval = ScoreBrackets.getRegInterval(
949 &MI, TII, MRI, TRI, CallAddrOpIdx, false);
950
951 for (signed RegNo = CallAddrOpInterval.first;
952 RegNo < CallAddrOpInterval.second; ++RegNo)
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000953 ScoreBrackets.determineWait(
954 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
Austin Kerbowd11b93e2019-10-28 09:39:20 -0700955
956 int RtnAddrOpIdx =
957 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::dst);
958 if (RtnAddrOpIdx != -1) {
959 RegInterval RtnAddrOpInterval = ScoreBrackets.getRegInterval(
960 &MI, TII, MRI, TRI, RtnAddrOpIdx, false);
961
962 for (signed RegNo = RtnAddrOpInterval.first;
963 RegNo < RtnAddrOpInterval.second; ++RegNo)
964 ScoreBrackets.determineWait(
965 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000966 }
Austin Kerbowd11b93e2019-10-28 09:39:20 -0700967
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000968 } else {
Matt Arsenault0ed39d32017-07-21 18:54:54 +0000969 // FIXME: Should not be relying on memoperands.
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000970 // Look at the source operands of every instruction to see if
971 // any of them results from a previous memory operation that affects
972 // its current usage. If so, an s_waitcnt instruction needs to be
973 // emitted.
974 // If the source operand was defined by a load, add the s_waitcnt
975 // instruction.
Kannan Narayananacb089e2017-04-12 03:25:12 +0000976 for (const MachineMemOperand *Memop : MI.memoperands()) {
977 unsigned AS = Memop->getAddrSpace();
Matt Arsenault0da63502018-08-31 05:49:54 +0000978 if (AS != AMDGPUAS::LOCAL_ADDRESS)
Kannan Narayananacb089e2017-04-12 03:25:12 +0000979 continue;
980 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000981 // VM_CNT is only relevant to vgpr or LDS.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +0000982 ScoreBrackets.determineWait(
983 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +0000984 }
Matt Arsenaultaa41e922019-06-14 21:52:26 +0000985
986 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
987 const MachineOperand &Op = MI.getOperand(I);
988 const MachineRegisterInfo &MRIA = *MRI;
989 RegInterval Interval =
990 ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, I, false);
991 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
992 if (TRI->isVGPR(MRIA, Op.getReg())) {
993 // VM_CNT is only relevant to vgpr or LDS.
994 ScoreBrackets.determineWait(
995 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
996 }
997 ScoreBrackets.determineWait(
998 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
999 }
1000 }
1001 // End of for loop that looks at all source operands to decide vm_wait_cnt
1002 // and lgk_wait_cnt.
1003
1004 // Two cases are handled for destination operands:
1005 // 1) If the destination operand was defined by a load, add the s_waitcnt
1006 // instruction to guarantee the right WAW order.
1007 // 2) If a destination operand that was used by a recent export/store ins,
1008 // add s_waitcnt on exp_cnt to guarantee the WAR order.
1009 if (MI.mayStore()) {
1010 // FIXME: Should not be relying on memoperands.
1011 for (const MachineMemOperand *Memop : MI.memoperands()) {
1012 unsigned AS = Memop->getAddrSpace();
1013 if (AS != AMDGPUAS::LOCAL_ADDRESS)
1014 continue;
1015 unsigned RegNo = SQ_MAX_PGM_VGPRS + EXTRA_VGPR_LDS;
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001016 ScoreBrackets.determineWait(
1017 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1018 ScoreBrackets.determineWait(
1019 EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001020 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001021 }
Matt Arsenaultaa41e922019-06-14 21:52:26 +00001022 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1023 MachineOperand &Def = MI.getOperand(I);
1024 const MachineRegisterInfo &MRIA = *MRI;
1025 RegInterval Interval =
1026 ScoreBrackets.getRegInterval(&MI, TII, MRI, TRI, I, true);
1027 for (signed RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1028 if (TRI->isVGPR(MRIA, Def.getReg())) {
1029 ScoreBrackets.determineWait(
1030 VM_CNT, ScoreBrackets.getRegScore(RegNo, VM_CNT), Wait);
1031 ScoreBrackets.determineWait(
1032 EXP_CNT, ScoreBrackets.getRegScore(RegNo, EXP_CNT), Wait);
1033 }
1034 ScoreBrackets.determineWait(
1035 LGKM_CNT, ScoreBrackets.getRegScore(RegNo, LGKM_CNT), Wait);
1036 }
1037 } // End of for loop that looks at all dest operands.
1038 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001039 }
1040
Kannan Narayananacb089e2017-04-12 03:25:12 +00001041 // Check to see if this is an S_BARRIER, and if an implicit S_WAITCNT 0
1042 // occurs before the instruction. Doing it here prevents any additional
1043 // S_WAITCNTs from being emitted if the instruction was marked as
1044 // requiring a WAITCNT beforehand.
Konstantin Zhuravlyovbe6c0ca2017-06-02 17:40:26 +00001045 if (MI.getOpcode() == AMDGPU::S_BARRIER &&
1046 !ST->hasAutoWaitcntBeforeBarrier()) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001047 Wait = Wait.combined(AMDGPU::Waitcnt::allZero(IV));
Kannan Narayananacb089e2017-04-12 03:25:12 +00001048 }
1049
1050 // TODO: Remove this work-around, enable the assert for Bug 457939
1051 // after fixing the scheduler. Also, the Shader Compiler code is
1052 // independent of target.
Matt Arsenaulte4c2e9b2019-06-19 23:54:58 +00001053 if (readsVCCZ(MI) && ST->hasReadVCCZBug()) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001054 if (ScoreBrackets.getScoreLB(LGKM_CNT) <
1055 ScoreBrackets.getScoreUB(LGKM_CNT) &&
1056 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001057 Wait.LgkmCnt = 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001058 }
1059 }
1060
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001061 // Early-out if no wait is indicated.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001062 if (!ScoreBrackets.simplifyWaitcnt(Wait) && !IsForceEmitWaitcnt) {
1063 bool Modified = false;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001064 if (OldWaitcntInstr) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001065 for (auto II = OldWaitcntInstr->getIterator(), NextI = std::next(II);
1066 &*II != &MI; II = NextI, ++NextI) {
1067 if (II->isDebugInstr())
1068 continue;
1069
1070 if (TrackedWaitcntSet.count(&*II)) {
1071 TrackedWaitcntSet.erase(&*II);
1072 II->eraseFromParent();
1073 Modified = true;
1074 } else if (II->getOpcode() == AMDGPU::S_WAITCNT) {
1075 int64_t Imm = II->getOperand(0).getImm();
1076 ScoreBrackets.applyWaitcnt(AMDGPU::decodeWaitcnt(IV, Imm));
1077 } else {
1078 assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT);
1079 assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1080 ScoreBrackets.applyWaitcnt(
1081 AMDGPU::Waitcnt(0, 0, 0, II->getOperand(1).getImm()));
1082 }
Stanislav Mekhanoshindb39b4b2018-02-08 00:18:35 +00001083 }
Nicolai Haehnle61396ff2018-11-07 21:53:36 +00001084 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001085 return Modified;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001086 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001087
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001088 if (ForceEmitZeroWaitcnts)
Stanislav Mekhanoshin956b0be2019-04-25 18:53:41 +00001089 Wait = AMDGPU::Waitcnt::allZero(IV);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001090
1091 if (ForceEmitWaitcnt[VM_CNT])
1092 Wait.VmCnt = 0;
1093 if (ForceEmitWaitcnt[EXP_CNT])
1094 Wait.ExpCnt = 0;
1095 if (ForceEmitWaitcnt[LGKM_CNT])
1096 Wait.LgkmCnt = 0;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001097 if (ForceEmitWaitcnt[VS_CNT])
1098 Wait.VsCnt = 0;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001099
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001100 ScoreBrackets.applyWaitcnt(Wait);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001101
1102 AMDGPU::Waitcnt OldWait;
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001103 bool Modified = false;
1104
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001105 if (OldWaitcntInstr) {
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001106 for (auto II = OldWaitcntInstr->getIterator(), NextI = std::next(II);
1107 &*II != &MI; II = NextI, NextI++) {
1108 if (II->isDebugInstr())
1109 continue;
1110
1111 if (II->getOpcode() == AMDGPU::S_WAITCNT) {
1112 unsigned IEnc = II->getOperand(0).getImm();
1113 AMDGPU::Waitcnt IWait = AMDGPU::decodeWaitcnt(IV, IEnc);
1114 OldWait = OldWait.combined(IWait);
1115 if (!TrackedWaitcntSet.count(&*II))
1116 Wait = Wait.combined(IWait);
1117 unsigned NewEnc = AMDGPU::encodeWaitcnt(IV, Wait);
1118 if (IEnc != NewEnc) {
1119 II->getOperand(0).setImm(NewEnc);
1120 Modified = true;
1121 }
1122 Wait.VmCnt = ~0u;
1123 Wait.LgkmCnt = ~0u;
1124 Wait.ExpCnt = ~0u;
1125 } else {
1126 assert(II->getOpcode() == AMDGPU::S_WAITCNT_VSCNT);
1127 assert(II->getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1128
1129 unsigned ICnt = II->getOperand(1).getImm();
1130 OldWait.VsCnt = std::min(OldWait.VsCnt, ICnt);
1131 if (!TrackedWaitcntSet.count(&*II))
1132 Wait.VsCnt = std::min(Wait.VsCnt, ICnt);
1133 if (Wait.VsCnt != ICnt) {
1134 II->getOperand(1).setImm(Wait.VsCnt);
1135 Modified = true;
1136 }
1137 Wait.VsCnt = ~0u;
1138 }
1139
1140 LLVM_DEBUG(dbgs() << "updateWaitcntInBlock\n"
1141 << "Old Instr: " << MI << '\n'
1142 << "New Instr: " << *II << '\n');
1143
1144 if (!Wait.hasWait())
1145 return Modified;
1146 }
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001147 }
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001148
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001149 if (Wait.VmCnt != ~0u || Wait.LgkmCnt != ~0u || Wait.ExpCnt != ~0u) {
1150 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001151 auto SWaitInst = BuildMI(*MI.getParent(), MI.getIterator(),
1152 MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1153 .addImm(Enc);
1154 TrackedWaitcntSet.insert(SWaitInst);
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001155 Modified = true;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001156
1157 LLVM_DEBUG(dbgs() << "insertWaitcntInBlock\n"
1158 << "Old Instr: " << MI << '\n'
1159 << "New Instr: " << *SWaitInst << '\n');
Kannan Narayananacb089e2017-04-12 03:25:12 +00001160 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001161
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001162 if (Wait.VsCnt != ~0u) {
1163 assert(ST->hasVscnt());
1164
1165 auto SWaitInst =
1166 BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
1167 TII->get(AMDGPU::S_WAITCNT_VSCNT))
1168 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1169 .addImm(Wait.VsCnt);
1170 TrackedWaitcntSet.insert(SWaitInst);
1171 Modified = true;
1172
1173 LLVM_DEBUG(dbgs() << "insertWaitcntInBlock\n"
1174 << "Old Instr: " << MI << '\n'
1175 << "New Instr: " << *SWaitInst << '\n');
1176 }
1177
1178 return Modified;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001179}
1180
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001181// This is a flat memory operation. Check to see if it has memory
1182// tokens for both LDS and Memory, and if so mark it as a flat.
1183bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
1184 if (MI.memoperands_empty())
1185 return true;
1186
1187 for (const MachineMemOperand *Memop : MI.memoperands()) {
1188 unsigned AS = Memop->getAddrSpace();
Matt Arsenault0da63502018-08-31 05:49:54 +00001189 if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS)
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001190 return true;
1191 }
1192
1193 return false;
1194}
1195
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001196void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
1197 WaitcntBrackets *ScoreBrackets) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001198 // Now look at the instruction opcode. If it is a memory access
1199 // instruction, update the upper-bound of the appropriate counter's
1200 // bracket and the destination operand scores.
1201 // TODO: Use the (TSFlags & SIInstrFlags::LGKM_CNT) property everywhere.
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001202 if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
Marek Olsakc5cec5e2019-01-16 15:43:53 +00001203 if (TII->isAlwaysGDS(Inst.getOpcode()) ||
1204 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001205 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
1206 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
1207 } else {
1208 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
1209 }
1210 } else if (TII->isFLAT(Inst)) {
1211 assert(Inst.mayLoad() || Inst.mayStore());
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001212
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001213 if (TII->usesVM_CNT(Inst)) {
1214 if (!ST->hasVscnt())
1215 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1216 else if (Inst.mayLoad() &&
1217 AMDGPU::getAtomicRetOp(Inst.getOpcode()) == -1)
1218 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1219 else
1220 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1221 }
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001222
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001223 if (TII->usesLGKM_CNT(Inst)) {
Matt Arsenault6ab9ea92017-07-21 18:34:51 +00001224 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001225
Matt Arsenault0ed39d32017-07-21 18:54:54 +00001226 // This is a flat memory operation, so note it - it will require
1227 // that both the VM and LGKM be flushed to zero if it is pending when
1228 // a VM or LGKM dependency occurs.
1229 if (mayAccessLDSThroughFlat(Inst))
1230 ScoreBrackets->setPendingFlat();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001231 }
1232 } else if (SIInstrInfo::isVMEM(Inst) &&
1233 // TODO: get a better carve out.
1234 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1 &&
1235 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_SC &&
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001236 Inst.getOpcode() != AMDGPU::BUFFER_WBINVL1_VOL &&
1237 Inst.getOpcode() != AMDGPU::BUFFER_GL0_INV &&
1238 Inst.getOpcode() != AMDGPU::BUFFER_GL1_INV) {
1239 if (!ST->hasVscnt())
1240 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_ACCESS, Inst);
1241 else if ((Inst.mayLoad() &&
1242 AMDGPU::getAtomicRetOp(Inst.getOpcode()) == -1) ||
1243 /* IMAGE_GET_RESINFO / IMAGE_GET_LOD */
1244 (TII->isMIMG(Inst) && !Inst.mayLoad() && !Inst.mayStore()))
1245 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_READ_ACCESS, Inst);
1246 else if (Inst.mayStore())
1247 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_WRITE_ACCESS, Inst);
1248
Mark Searles2a19af62018-04-26 16:11:19 +00001249 if (ST->vmemWriteNeedsExpWaitcnt() &&
Mark Searles11d0a042017-05-31 16:44:23 +00001250 (Inst.mayStore() || AMDGPU::getAtomicNoRetOp(Inst.getOpcode()) != -1)) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001251 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
1252 }
1253 } else if (TII->isSMRD(Inst)) {
1254 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
Matt Arsenaultaa41e922019-06-14 21:52:26 +00001255 } else if (Inst.isCall()) {
1256 if (callWaitsOnFunctionReturn(Inst)) {
1257 // Act as a wait on everything
1258 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt::allZero(IV));
1259 } else {
1260 // May need to way wait for anything.
1261 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
1262 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001263 } else {
1264 switch (Inst.getOpcode()) {
1265 case AMDGPU::S_SENDMSG:
1266 case AMDGPU::S_SENDMSGHALT:
1267 ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
1268 break;
1269 case AMDGPU::EXP:
1270 case AMDGPU::EXP_DONE: {
1271 int Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
1272 if (Imm >= 32 && Imm <= 63)
1273 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
1274 else if (Imm >= 12 && Imm <= 15)
1275 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
1276 else
1277 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
1278 break;
1279 }
1280 case AMDGPU::S_MEMTIME:
1281 case AMDGPU::S_MEMREALTIME:
1282 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
1283 break;
1284 default:
1285 break;
1286 }
1287 }
1288}
1289
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001290bool WaitcntBrackets::mergeScore(const MergeInfo &M, uint32_t &Score,
1291 uint32_t OtherScore) {
1292 uint32_t MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
1293 uint32_t OtherShifted =
1294 OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
1295 Score = std::max(MyShifted, OtherShifted);
1296 return OtherShifted > MyShifted;
1297}
Kannan Narayananacb089e2017-04-12 03:25:12 +00001298
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001299/// Merge the pending events and associater score brackets of \p Other into
1300/// this brackets status.
1301///
1302/// Returns whether the merge resulted in a change that requires tighter waits
1303/// (i.e. the merged brackets strictly dominate the original brackets).
1304bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
1305 bool StrictDom = false;
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001306
Nicolai Haehnleae369d72018-11-29 11:06:11 +00001307 for (auto T : inst_counter_types()) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001308 // Merge event flags for this counter
1309 const bool OldOutOfOrder = counterOutOfOrder(T);
1310 const uint32_t OldEvents = PendingEvents & WaitEventMaskForInst[T];
1311 const uint32_t OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T];
1312 if (OtherEvents & ~OldEvents)
1313 StrictDom = true;
1314 if (Other.MixedPendingEvents[T] ||
1315 (OldEvents && OtherEvents && OldEvents != OtherEvents))
1316 MixedPendingEvents[T] = true;
1317 PendingEvents |= OtherEvents;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001318
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001319 // Merge scores for this counter
1320 const uint32_t MyPending = ScoreUBs[T] - ScoreLBs[T];
1321 const uint32_t OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
1322 MergeInfo M;
1323 M.OldLB = ScoreLBs[T];
1324 M.OtherLB = Other.ScoreLBs[T];
1325 M.MyShift = OtherPending > MyPending ? OtherPending - MyPending : 0;
1326 M.OtherShift = ScoreUBs[T] - Other.ScoreUBs[T] + M.MyShift;
1327
1328 const uint32_t NewUB = ScoreUBs[T] + M.MyShift;
1329 if (NewUB < ScoreUBs[T])
1330 report_fatal_error("waitcnt score overflow");
1331 ScoreUBs[T] = NewUB;
1332 ScoreLBs[T] = std::min(M.OldLB + M.MyShift, M.OtherLB + M.OtherShift);
1333
1334 StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
1335
1336 bool RegStrictDom = false;
1337 for (int J = 0, E = std::max(getMaxVGPR(), Other.getMaxVGPR()) + 1; J != E;
1338 J++) {
1339 RegStrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001340 }
1341
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001342 if (T == LGKM_CNT) {
1343 for (int J = 0, E = std::max(getMaxSGPR(), Other.getMaxSGPR()) + 1;
1344 J != E; J++) {
1345 RegStrictDom |= mergeScore(M, SgprScores[J], Other.SgprScores[J]);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001346 }
1347 }
1348
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001349 if (RegStrictDom && !OldOutOfOrder)
1350 StrictDom = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001351 }
Mark Searlesc3c02bd2018-03-14 22:04:32 +00001352
Carl Ritsonc521ac32018-12-19 10:17:49 +00001353 VgprUB = std::max(getMaxVGPR(), Other.getMaxVGPR());
1354 SgprUB = std::max(getMaxSGPR(), Other.getMaxSGPR());
1355
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001356 return StrictDom;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001357}
1358
1359// Generate s_waitcnt instructions where needed.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001360bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
1361 MachineBasicBlock &Block,
1362 WaitcntBrackets &ScoreBrackets) {
1363 bool Modified = false;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001364
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001365 LLVM_DEBUG({
Mark Searlesec581832018-04-25 19:21:26 +00001366 dbgs() << "*** Block" << Block.getNumber() << " ***";
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001367 ScoreBrackets.dump();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001368 });
1369
Kannan Narayananacb089e2017-04-12 03:25:12 +00001370 // Walk over the instructions.
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001371 MachineInstr *OldWaitcntInstr = nullptr;
1372
Matt Arsenaultc04aab92019-07-03 00:30:44 +00001373 for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(),
1374 E = Block.instr_end();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001375 Iter != E;) {
1376 MachineInstr &Inst = *Iter;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001377
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001378 // Track pre-existing waitcnts from earlier iterations.
1379 if (Inst.getOpcode() == AMDGPU::S_WAITCNT ||
1380 (Inst.getOpcode() == AMDGPU::S_WAITCNT_VSCNT &&
1381 Inst.getOperand(0).isReg() &&
1382 Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL)) {
1383 if (!OldWaitcntInstr)
1384 OldWaitcntInstr = &Inst;
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001385 ++Iter;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001386 continue;
1387 }
1388
Kannan Narayananacb089e2017-04-12 03:25:12 +00001389 bool VCCZBugWorkAround = false;
Jay Foade5972f22019-10-30 13:47:32 +00001390 if (readsVCCZ(Inst)) {
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001391 if (ScoreBrackets.getScoreLB(LGKM_CNT) <
1392 ScoreBrackets.getScoreUB(LGKM_CNT) &&
1393 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
Jay Foadb5922532019-10-29 17:11:21 +00001394 if (ST->hasReadVCCZBug())
Kannan Narayananacb089e2017-04-12 03:25:12 +00001395 VCCZBugWorkAround = true;
1396 }
1397 }
1398
1399 // Generate an s_waitcnt instruction to be placed before
1400 // cur_Inst, if needed.
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001401 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr);
Nicolai Haehnle1a94cbb2018-11-29 11:06:06 +00001402 OldWaitcntInstr = nullptr;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001403
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001404 updateEventWaitcntAfter(Inst, &ScoreBrackets);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001405
1406#if 0 // TODO: implement resource type check controlled by options with ub = LB.
1407 // If this instruction generates a S_SETVSKIP because it is an
1408 // indexed resource, and we are on Tahiti, then it will also force
1409 // an S_WAITCNT vmcnt(0)
1410 if (RequireCheckResourceType(Inst, context)) {
1411 // Force the score to as if an S_WAITCNT vmcnt(0) is emitted.
1412 ScoreBrackets->setScoreLB(VM_CNT,
Evgeny Mankovbf975172017-08-16 16:47:29 +00001413 ScoreBrackets->getScoreUB(VM_CNT));
Kannan Narayananacb089e2017-04-12 03:25:12 +00001414 }
1415#endif
1416
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001417 LLVM_DEBUG({
Mark Searles94ae3b22018-01-30 17:17:06 +00001418 Inst.print(dbgs());
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001419 ScoreBrackets.dump();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001420 });
1421
Kannan Narayananacb089e2017-04-12 03:25:12 +00001422 // 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(),
Stanislav Mekhanoshin52500212019-06-16 17:13:09 +00001429 TII->get(ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
1430 TRI->getVCC())
1431 .addReg(TRI->getVCC());
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001432 Modified = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001433 }
1434
Kannan Narayananacb089e2017-04-12 03:25:12 +00001435 ++Iter;
1436 }
1437
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001438 return Modified;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001439}
1440
1441bool SIInsertWaitcnts::runOnMachineFunction(MachineFunction &MF) {
Tom Stellard5bfbae52018-07-11 20:59:01 +00001442 ST = &MF.getSubtarget<GCNSubtarget>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001443 TII = ST->getInstrInfo();
1444 TRI = &TII->getRegisterInfo();
1445 MRI = &MF.getRegInfo();
Konstantin Zhuravlyov71e43ee2018-09-12 18:50:47 +00001446 IV = AMDGPU::getIsaVersion(ST->getCPU());
Mark Searles11d0a042017-05-31 16:44:23 +00001447 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
Kannan Narayananacb089e2017-04-12 03:25:12 +00001448
Mark Searles4a0f2c52018-05-07 14:43:28 +00001449 ForceEmitZeroWaitcnts = ForceEmitZeroFlag;
Nicolai Haehnleae369d72018-11-29 11:06:11 +00001450 for (auto T : inst_counter_types())
Mark Searlesec581832018-04-25 19:21:26 +00001451 ForceEmitWaitcnt[T] = false;
1452
Kannan Narayananacb089e2017-04-12 03:25:12 +00001453 HardwareLimits.VmcntMax = AMDGPU::getVmcntBitMask(IV);
1454 HardwareLimits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
1455 HardwareLimits.LgkmcntMax = AMDGPU::getLgkmcntBitMask(IV);
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001456 HardwareLimits.VscntMax = ST->hasVscnt() ? 63 : 0;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001457
1458 HardwareLimits.NumVGPRsMax = ST->getAddressableNumVGPRs();
1459 HardwareLimits.NumSGPRsMax = ST->getAddressableNumSGPRs();
1460 assert(HardwareLimits.NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
1461 assert(HardwareLimits.NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
1462
1463 RegisterEncoding.VGPR0 = TRI->getEncodingValue(AMDGPU::VGPR0);
1464 RegisterEncoding.VGPRL =
1465 RegisterEncoding.VGPR0 + HardwareLimits.NumVGPRsMax - 1;
1466 RegisterEncoding.SGPR0 = TRI->getEncodingValue(AMDGPU::SGPR0);
1467 RegisterEncoding.SGPRL =
1468 RegisterEncoding.SGPR0 + HardwareLimits.NumSGPRsMax - 1;
1469
Mark Searles24c92ee2018-02-07 02:21:21 +00001470 TrackedWaitcntSet.clear();
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001471 RpotIdxMap.clear();
1472 BlockInfos.clear();
Mark Searles24c92ee2018-02-07 02:21:21 +00001473
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001474 // Keep iterating over the blocks in reverse post order, inserting and
1475 // updating s_waitcnt where needed, until a fix point is reached.
1476 for (MachineBasicBlock *MBB :
1477 ReversePostOrderTraversal<MachineFunction *>(&MF)) {
1478 RpotIdxMap[MBB] = BlockInfos.size();
1479 BlockInfos.emplace_back(MBB);
1480 }
1481
1482 std::unique_ptr<WaitcntBrackets> Brackets;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001483 bool Modified = false;
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001484 bool Repeat;
1485 do {
1486 Repeat = false;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001487
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001488 for (BlockInfo &BI : BlockInfos) {
1489 if (!BI.Dirty)
1490 continue;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001491
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001492 unsigned Idx = std::distance(&*BlockInfos.begin(), &BI);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001493
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001494 if (BI.Incoming) {
1495 if (!Brackets)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001496 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001497 else
1498 *Brackets = *BI.Incoming;
1499 } else {
1500 if (!Brackets)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001501 Brackets = std::make_unique<WaitcntBrackets>(ST);
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001502 else
1503 Brackets->clear();
Mark Searles1bc6e712018-04-19 15:42:30 +00001504 }
Kannan Narayananacb089e2017-04-12 03:25:12 +00001505
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001506 Modified |= insertWaitcntInBlock(MF, *BI.MBB, *Brackets);
1507 BI.Dirty = false;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001508
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001509 if (Brackets->hasPending()) {
1510 BlockInfo *MoveBracketsToSucc = nullptr;
1511 for (MachineBasicBlock *Succ : BI.MBB->successors()) {
1512 unsigned SuccIdx = RpotIdxMap[Succ];
1513 BlockInfo &SuccBI = BlockInfos[SuccIdx];
1514 if (!SuccBI.Incoming) {
1515 SuccBI.Dirty = true;
1516 if (SuccIdx <= Idx)
1517 Repeat = true;
1518 if (!MoveBracketsToSucc) {
1519 MoveBracketsToSucc = &SuccBI;
1520 } else {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001521 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001522 }
1523 } else if (SuccBI.Incoming->merge(*Brackets)) {
1524 SuccBI.Dirty = true;
1525 if (SuccIdx <= Idx)
1526 Repeat = true;
Kannan Narayananacb089e2017-04-12 03:25:12 +00001527 }
1528 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001529 if (MoveBracketsToSucc)
1530 MoveBracketsToSucc->Incoming = std::move(Brackets);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001531 }
1532 }
Nicolai Haehnle7bed6962018-11-29 11:06:26 +00001533 } while (Repeat);
Kannan Narayananacb089e2017-04-12 03:25:12 +00001534
1535 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
1536
1537 bool HaveScalarStores = false;
1538
1539 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE;
1540 ++BI) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001541 MachineBasicBlock &MBB = *BI;
1542
1543 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;
1544 ++I) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001545 if (!HaveScalarStores && TII->isScalarStore(*I))
1546 HaveScalarStores = true;
1547
1548 if (I->getOpcode() == AMDGPU::S_ENDPGM ||
1549 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
1550 EndPgmBlocks.push_back(&MBB);
1551 }
1552 }
1553
1554 if (HaveScalarStores) {
1555 // If scalar writes are used, the cache must be flushed or else the next
1556 // wave to reuse the same scratch memory can be clobbered.
1557 //
1558 // Insert s_dcache_wb at wave termination points if there were any scalar
1559 // stores, and only if the cache hasn't already been flushed. This could be
1560 // improved by looking across blocks for flushes in postdominating blocks
1561 // from the stores but an explicitly requested flush is probably very rare.
1562 for (MachineBasicBlock *MBB : EndPgmBlocks) {
1563 bool SeenDCacheWB = false;
1564
1565 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
1566 ++I) {
Kannan Narayananacb089e2017-04-12 03:25:12 +00001567 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
1568 SeenDCacheWB = true;
1569 else if (TII->isScalarStore(*I))
1570 SeenDCacheWB = false;
1571
1572 // FIXME: It would be better to insert this before a waitcnt if any.
1573 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
1574 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
1575 !SeenDCacheWB) {
1576 Modified = true;
1577 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
1578 }
1579 }
1580 }
1581 }
1582
Mark Searles11d0a042017-05-31 16:44:23 +00001583 if (!MFI->isEntryFunction()) {
1584 // Wait for any outstanding memory operations that the input registers may
Hiroshi Inouec8e92452018-01-29 05:17:03 +00001585 // depend on. We can't track them and it's better to the wait after the
Mark Searles11d0a042017-05-31 16:44:23 +00001586 // costly call sequence.
1587
1588 // TODO: Could insert earlier and schedule more liberally with operations
1589 // that only use caller preserved registers.
1590 MachineBasicBlock &EntryBB = MF.front();
Stanislav Mekhanoshind9dcf392019-05-03 21:53:53 +00001591 if (ST->hasVscnt())
1592 BuildMI(EntryBB, EntryBB.getFirstNonPHI(), DebugLoc(),
1593 TII->get(AMDGPU::S_WAITCNT_VSCNT))
1594 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1595 .addImm(0);
Mark Searlesed54ff12018-05-30 16:27:57 +00001596 BuildMI(EntryBB, EntryBB.getFirstNonPHI(), DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
1597 .addImm(0);
Mark Searles11d0a042017-05-31 16:44:23 +00001598
1599 Modified = true;
1600 }
1601
Kannan Narayananacb089e2017-04-12 03:25:12 +00001602 return Modified;
1603}