blob: c814e55e844fd7df82447dc35658e6b2139fd4cd [file] [log] [blame]
Tom Stellardc4cabef2013-01-18 21:15:53 +00001//===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// \brief Insert wait instructions for memory reads and writes.
12///
13/// Memory reads and writes are issued asynchronously, so we need to insert
14/// S_WAITCNT instructions when we want to access any of their results or
15/// overwrite any register that's used asynchronously.
16//
17//===----------------------------------------------------------------------===//
18
19#include "AMDGPU.h"
Eric Christopherd9134482014-08-04 21:25:23 +000020#include "AMDGPUSubtarget.h"
Matt Arsenault9783e002014-09-29 15:50:26 +000021#include "SIDefines.h"
Matt Arsenault1fd0c622014-09-29 15:53:15 +000022#include "SIInstrInfo.h"
Tom Stellardc4cabef2013-01-18 21:15:53 +000023#include "SIMachineFunctionInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000024#include "SIRegisterInfo.h"
Konstantin Zhuravlyov836cbff2016-09-30 17:01:40 +000025#include "Utils/AMDGPUBaseInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000026#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/CodeGen/MachineBasicBlock.h"
Tom Stellardc4cabef2013-01-18 21:15:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000031#include "llvm/CodeGen/MachineInstr.h"
Tom Stellardc4cabef2013-01-18 21:15:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000033#include "llvm/CodeGen/MachineOperand.h"
Tom Stellardc4cabef2013-01-18 21:15:53 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko66203762017-01-21 00:53:49 +000035#include "llvm/IR/DebugLoc.h"
36#include "llvm/Pass.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/Target/TargetRegisterInfo.h"
40#include <algorithm>
41#include <cassert>
42#include <cstdint>
43#include <cstring>
44#include <new>
45#include <utility>
Tom Stellardc4cabef2013-01-18 21:15:53 +000046
Tom Stellard6e1967e2016-02-05 17:42:38 +000047#define DEBUG_TYPE "si-insert-waits"
48
Tom Stellardc4cabef2013-01-18 21:15:53 +000049using namespace llvm;
Konstantin Zhuravlyov836cbff2016-09-30 17:01:40 +000050using namespace llvm::AMDGPU;
Tom Stellardc4cabef2013-01-18 21:15:53 +000051
52namespace {
53
54/// \brief One variable for each of the hardware counters
55typedef union {
56 struct {
57 unsigned VM;
58 unsigned EXP;
59 unsigned LGKM;
60 } Named;
61 unsigned Array[3];
Tom Stellardc4cabef2013-01-18 21:15:53 +000062} Counters;
63
Marek Olsakfa58e5e2014-12-07 17:17:43 +000064typedef enum {
65 OTHER,
66 SMEM,
67 VMEM
68} InstType;
69
Tom Stellardc4cabef2013-01-18 21:15:53 +000070typedef Counters RegCounters[512];
71typedef std::pair<unsigned, unsigned> RegInterval;
72
73class SIInsertWaits : public MachineFunctionPass {
Tom Stellardc4cabef2013-01-18 21:15:53 +000074private:
Eugene Zelenko66203762017-01-21 00:53:49 +000075 const SISubtarget *ST = nullptr;
76 const SIInstrInfo *TII = nullptr;
77 const SIRegisterInfo *TRI = nullptr;
Tom Stellardc4cabef2013-01-18 21:15:53 +000078 const MachineRegisterInfo *MRI;
Konstantin Zhuravlyov836cbff2016-09-30 17:01:40 +000079 IsaVersion IV;
Tom Stellardc4cabef2013-01-18 21:15:53 +000080
Tom Stellardc4cabef2013-01-18 21:15:53 +000081 /// \brief Constant zero value
82 static const Counters ZeroCounts;
83
Konstantin Zhuravlyovcdd45472016-10-11 18:58:22 +000084 /// \brief Hardware limits
85 Counters HardwareLimits;
86
Tom Stellardc4cabef2013-01-18 21:15:53 +000087 /// \brief Counter values we have already waited on.
88 Counters WaitedOn;
89
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +000090 /// \brief Counter values that we must wait on before the next counter
91 /// increase.
92 Counters DelayedWaitOn;
93
Tom Stellardc4cabef2013-01-18 21:15:53 +000094 /// \brief Counter values for last instruction issued.
95 Counters LastIssued;
96
97 /// \brief Registers used by async instructions.
98 RegCounters UsedRegs;
99
100 /// \brief Registers defined by async instructions.
101 RegCounters DefinedRegs;
102
103 /// \brief Different export instruction types seen since last wait.
Eugene Zelenko66203762017-01-21 00:53:49 +0000104 unsigned ExpInstrTypesSeen = 0;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000105
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000106 /// \brief Type of the last opcode.
107 InstType LastOpcodeType;
108
Marek Olsak1bd24632015-02-03 17:37:52 +0000109 bool LastInstWritesM0;
110
Tom Stellard6695ba02016-10-28 23:53:48 +0000111 /// Whether or not we have flat operations outstanding.
112 bool IsFlatOutstanding;
113
Marek Olsak8e9cc632016-01-13 17:23:09 +0000114 /// \brief Whether the machine function returns void
115 bool ReturnsVoid;
116
Tom Stellard30961762016-02-08 19:49:20 +0000117 /// Whether the VCCZ bit is possibly corrupt
Eugene Zelenko66203762017-01-21 00:53:49 +0000118 bool VCCZCorrupt = false;
Tom Stellard30961762016-02-08 19:49:20 +0000119
Tom Stellardc4cabef2013-01-18 21:15:53 +0000120 /// \brief Get increment/decrement amount for this instruction.
121 Counters getHwCounts(MachineInstr &MI);
122
123 /// \brief Is operand relevant for async execution?
124 bool isOpRelevant(MachineOperand &Op);
125
126 /// \brief Get register interval an operand affects.
Matt Arsenaultd1d499a2015-10-01 21:43:15 +0000127 RegInterval getRegInterval(const TargetRegisterClass *RC,
128 const MachineOperand &Reg) const;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000129
130 /// \brief Handle instructions async components
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000131 void pushInstruction(MachineBasicBlock &MBB,
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000132 MachineBasicBlock::iterator I,
133 const Counters& Increment);
Tom Stellardc4cabef2013-01-18 21:15:53 +0000134
135 /// \brief Insert the actual wait instruction
136 bool insertWait(MachineBasicBlock &MBB,
137 MachineBasicBlock::iterator I,
138 const Counters &Counts);
139
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000140 /// \brief Handle existing wait instructions (from intrinsics)
141 void handleExistingWait(MachineBasicBlock::iterator I);
142
Christian Konig862fd9f2013-03-01 09:46:04 +0000143 /// \brief Do we need def2def checks?
144 bool unorderedDefines(MachineInstr &MI);
145
Tom Stellardc4cabef2013-01-18 21:15:53 +0000146 /// \brief Resolve all operand dependencies to counter requirements
147 Counters handleOperands(MachineInstr &MI);
148
Marek Olsak1bd24632015-02-03 17:37:52 +0000149 /// \brief Insert S_NOP between an instruction writing M0 and S_SENDMSG.
150 void handleSendMsg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I);
151
Tom Stellard30961762016-02-08 19:49:20 +0000152 /// Return true if there are LGKM instrucitons that haven't been waited on
153 /// yet.
154 bool hasOutstandingLGKM() const;
155
Tom Stellardc4cabef2013-01-18 21:15:53 +0000156public:
Tom Stellard6e1967e2016-02-05 17:42:38 +0000157 static char ID;
158
Eugene Zelenko66203762017-01-21 00:53:49 +0000159 SIInsertWaits() : MachineFunctionPass(ID) {}
Tom Stellardc4cabef2013-01-18 21:15:53 +0000160
Craig Topper5656db42014-04-29 07:57:24 +0000161 bool runOnMachineFunction(MachineFunction &MF) override;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000162
Mehdi Amini117296c2016-10-01 02:56:57 +0000163 StringRef getPassName() const override {
Matt Arsenault0cb85172015-09-25 17:21:28 +0000164 return "SI insert wait instructions";
Tom Stellardc4cabef2013-01-18 21:15:53 +0000165 }
166
Matt Arsenault0cb85172015-09-25 17:21:28 +0000167 void getAnalysisUsage(AnalysisUsage &AU) const override {
168 AU.setPreservesCFG();
169 MachineFunctionPass::getAnalysisUsage(AU);
170 }
Tom Stellardc4cabef2013-01-18 21:15:53 +0000171};
172
Eugene Zelenko66203762017-01-21 00:53:49 +0000173} // end anonymous namespace
Tom Stellardc4cabef2013-01-18 21:15:53 +0000174
Tom Stellard6e1967e2016-02-05 17:42:38 +0000175INITIALIZE_PASS_BEGIN(SIInsertWaits, DEBUG_TYPE,
176 "SI Insert Waits", false, false)
177INITIALIZE_PASS_END(SIInsertWaits, DEBUG_TYPE,
178 "SI Insert Waits", false, false)
179
Tom Stellardc4cabef2013-01-18 21:15:53 +0000180char SIInsertWaits::ID = 0;
181
Tom Stellard6e1967e2016-02-05 17:42:38 +0000182char &llvm::SIInsertWaitsID = SIInsertWaits::ID;
183
184FunctionPass *llvm::createSIInsertWaitsPass() {
185 return new SIInsertWaits();
186}
187
Tom Stellardc4cabef2013-01-18 21:15:53 +0000188const Counters SIInsertWaits::ZeroCounts = { { 0, 0, 0 } };
189
Matt Arsenault52f14ec2016-11-07 19:09:27 +0000190static bool readsVCCZ(const MachineInstr &MI) {
191 unsigned Opc = MI.getOpcode();
192 return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
193 !MI.getOperand(1).isUndef();
Tom Stellard30961762016-02-08 19:49:20 +0000194}
195
196bool SIInsertWaits::hasOutstandingLGKM() const {
197 return WaitedOn.Named.LGKM != LastIssued.Named.LGKM;
198}
Tom Stellardc4cabef2013-01-18 21:15:53 +0000199
200Counters SIInsertWaits::getHwCounts(MachineInstr &MI) {
Matt Arsenaultd1d499a2015-10-01 21:43:15 +0000201 uint64_t TSFlags = MI.getDesc().TSFlags;
Matt Arsenaulte66621b2015-09-24 19:52:27 +0000202 Counters Result = { { 0, 0, 0 } };
Tom Stellardc4cabef2013-01-18 21:15:53 +0000203
204 Result.Named.VM = !!(TSFlags & SIInstrFlags::VM_CNT);
205
206 // Only consider stores or EXP for EXP_CNT
Matt Arsenault7bee6ac2016-12-05 20:23:10 +0000207 Result.Named.EXP = !!(TSFlags & SIInstrFlags::EXP_CNT) && MI.mayStore();
Tom Stellardc4cabef2013-01-18 21:15:53 +0000208
209 // LGKM may uses larger values
210 if (TSFlags & SIInstrFlags::LGKM_CNT) {
211
Matt Arsenault3add6432015-10-20 04:35:43 +0000212 if (TII->isSMRD(MI)) {
Tom Stellardc4cabef2013-01-18 21:15:53 +0000213
Matt Arsenaulte66621b2015-09-24 19:52:27 +0000214 if (MI.getNumOperands() != 0) {
Matt Arsenaultb733f002015-10-01 22:40:35 +0000215 assert(MI.getOperand(0).isReg() &&
216 "First LGKM operand must be a register!");
Michel Danzer20680b12013-08-16 16:19:24 +0000217
Matt Arsenaulte66621b2015-09-24 19:52:27 +0000218 // XXX - What if this is a write into a super register?
Matt Arsenaultd1d499a2015-10-01 21:43:15 +0000219 const TargetRegisterClass *RC = TII->getOpRegClass(MI, 0);
220 unsigned Size = RC->getSize();
Matt Arsenaulte66621b2015-09-24 19:52:27 +0000221 Result.Named.LGKM = Size > 4 ? 2 : 1;
222 } else {
223 // s_dcache_inv etc. do not have a a destination register. Assume we
224 // want a wait on these.
225 // XXX - What is the right value?
226 Result.Named.LGKM = 1;
227 }
Michel Danzer20680b12013-08-16 16:19:24 +0000228 } else {
229 // DS
230 Result.Named.LGKM = 1;
231 }
Tom Stellardc4cabef2013-01-18 21:15:53 +0000232
233 } else {
234 Result.Named.LGKM = 0;
235 }
236
237 return Result;
238}
239
240bool SIInsertWaits::isOpRelevant(MachineOperand &Op) {
Tom Stellardc4cabef2013-01-18 21:15:53 +0000241 // Constants are always irrelevant
Matt Arsenaultd1d499a2015-10-01 21:43:15 +0000242 if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()))
Tom Stellardc4cabef2013-01-18 21:15:53 +0000243 return false;
244
245 // Defines are always relevant
246 if (Op.isDef())
247 return true;
248
Matt Arsenault7bee6ac2016-12-05 20:23:10 +0000249 // For exports all registers are relevant.
250 // TODO: Skip undef/disabled registers.
Tom Stellardc4cabef2013-01-18 21:15:53 +0000251 MachineInstr &MI = *Op.getParent();
Matt Arsenault7bee6ac2016-12-05 20:23:10 +0000252 if (TII->isEXP(MI))
Tom Stellardc4cabef2013-01-18 21:15:53 +0000253 return true;
254
255 // For stores the stored value is also relevant
256 if (!MI.getDesc().mayStore())
257 return false;
258
Tom Stellardb3931b82015-01-06 19:52:04 +0000259 // Check if this operand is the value being stored.
Tom Stellard2d26fe72016-02-19 15:33:13 +0000260 // Special case for DS/FLAT instructions, since the address
Tom Stellardb3931b82015-01-06 19:52:04 +0000261 // operand comes before the value operand and it may have
262 // multiple data operands.
263
Tom Stellard2d26fe72016-02-19 15:33:13 +0000264 if (TII->isDS(MI)) {
Tom Stellardb3931b82015-01-06 19:52:04 +0000265 MachineOperand *Data0 = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
266 if (Data0 && Op.isIdenticalTo(*Data0))
267 return true;
268
269 MachineOperand *Data1 = TII->getNamedOperand(MI, AMDGPU::OpName::data1);
Matt Arsenault8226fc42016-03-02 23:00:21 +0000270 return Data1 && Op.isIdenticalTo(*Data1);
Tom Stellardb3931b82015-01-06 19:52:04 +0000271 }
272
Matt Arsenault97279a82016-11-29 19:30:44 +0000273 if (TII->isFLAT(MI)) {
274 MachineOperand *Data = TII->getNamedOperand(MI, AMDGPU::OpName::vdata);
275 if (Data && Op.isIdenticalTo(*Data))
276 return true;
277 }
278
Tom Stellardb3931b82015-01-06 19:52:04 +0000279 // NOTE: This assumes that the value operand is before the
280 // address operand, and that there is only one value operand.
Tom Stellardc4cabef2013-01-18 21:15:53 +0000281 for (MachineInstr::mop_iterator I = MI.operands_begin(),
282 E = MI.operands_end(); I != E; ++I) {
283
284 if (I->isReg() && I->isUse())
285 return Op.isIdenticalTo(*I);
286 }
287
288 return false;
289}
290
Matt Arsenaultd1d499a2015-10-01 21:43:15 +0000291RegInterval SIInsertWaits::getRegInterval(const TargetRegisterClass *RC,
292 const MachineOperand &Reg) const {
293 unsigned Size = RC->getSize();
Tom Stellardc4cabef2013-01-18 21:15:53 +0000294 assert(Size >= 4);
295
296 RegInterval Result;
Matt Arsenaultd1d499a2015-10-01 21:43:15 +0000297 Result.first = TRI->getEncodingValue(Reg.getReg());
Tom Stellardc4cabef2013-01-18 21:15:53 +0000298 Result.second = Result.first + Size / 4;
299
300 return Result;
301}
302
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000303void SIInsertWaits::pushInstruction(MachineBasicBlock &MBB,
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000304 MachineBasicBlock::iterator I,
305 const Counters &Increment) {
Tom Stellardc4cabef2013-01-18 21:15:53 +0000306 // Get the hardware counter increments and sum them up
Tom Stellardbd8a0852015-08-21 22:47:27 +0000307 Counters Limit = ZeroCounts;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000308 unsigned Sum = 0;
309
Tom Stellard6695ba02016-10-28 23:53:48 +0000310 if (TII->mayAccessFlatAddressSpace(*I))
311 IsFlatOutstanding = true;
312
Tom Stellardc4cabef2013-01-18 21:15:53 +0000313 for (unsigned i = 0; i < 3; ++i) {
314 LastIssued.Array[i] += Increment.Array[i];
Tom Stellardbd8a0852015-08-21 22:47:27 +0000315 if (Increment.Array[i])
316 Limit.Array[i] = LastIssued.Array[i];
Tom Stellardc4cabef2013-01-18 21:15:53 +0000317 Sum += Increment.Array[i];
318 }
319
320 // If we don't increase anything then that's it
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000321 if (Sum == 0) {
322 LastOpcodeType = OTHER;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000323 return;
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000324 }
325
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000326 if (ST->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000327 // Any occurrence of consecutive VMEM or SMEM instructions forms a VMEM
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000328 // or SMEM clause, respectively.
329 //
330 // The temporary workaround is to break the clauses with S_NOP.
331 //
332 // The proper solution would be to allocate registers such that all source
333 // and destination registers don't overlap, e.g. this is illegal:
334 // r0 = load r2
335 // r2 = load r0
Tom Stellard1f520e52016-05-02 17:39:06 +0000336 if (LastOpcodeType == VMEM && Increment.Named.VM) {
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000337 // Insert a NOP to break the clause.
338 BuildMI(MBB, I, DebugLoc(), TII->get(AMDGPU::S_NOP))
339 .addImm(0);
Marek Olsak1bd24632015-02-03 17:37:52 +0000340 LastInstWritesM0 = false;
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000341 }
342
Matt Arsenault3add6432015-10-20 04:35:43 +0000343 if (TII->isSMRD(*I))
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000344 LastOpcodeType = SMEM;
345 else if (Increment.Named.VM)
346 LastOpcodeType = VMEM;
347 }
Tom Stellardc4cabef2013-01-18 21:15:53 +0000348
349 // Remember which export instructions we have seen
350 if (Increment.Named.EXP) {
Matt Arsenault7bee6ac2016-12-05 20:23:10 +0000351 ExpInstrTypesSeen |= TII->isEXP(*I) ? 1 : 2;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000352 }
353
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000354 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000355 MachineOperand &Op = I->getOperand(i);
Tom Stellardc4cabef2013-01-18 21:15:53 +0000356 if (!isOpRelevant(Op))
357 continue;
358
Matt Arsenaultd1d499a2015-10-01 21:43:15 +0000359 const TargetRegisterClass *RC = TII->getOpRegClass(*I, i);
360 RegInterval Interval = getRegInterval(RC, Op);
Tom Stellardc4cabef2013-01-18 21:15:53 +0000361 for (unsigned j = Interval.first; j < Interval.second; ++j) {
362
363 // Remember which registers we define
364 if (Op.isDef())
Tom Stellardbd8a0852015-08-21 22:47:27 +0000365 DefinedRegs[j] = Limit;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000366
367 // and which one we are using
368 if (Op.isUse())
Tom Stellardbd8a0852015-08-21 22:47:27 +0000369 UsedRegs[j] = Limit;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000370 }
371 }
372}
373
374bool SIInsertWaits::insertWait(MachineBasicBlock &MBB,
375 MachineBasicBlock::iterator I,
376 const Counters &Required) {
Tom Stellardc4cabef2013-01-18 21:15:53 +0000377 // End of program? No need to wait on anything
Marek Olsak8e9cc632016-01-13 17:23:09 +0000378 // A function not returning void needs to wait, because other bytecode will
379 // be appended after it and we don't know what it will be.
380 if (I != MBB.end() && I->getOpcode() == AMDGPU::S_ENDPGM && ReturnsVoid)
Tom Stellardc4cabef2013-01-18 21:15:53 +0000381 return false;
382
383 // Figure out if the async instructions execute in order
384 bool Ordered[3];
385
Tom Stellard6695ba02016-10-28 23:53:48 +0000386 // VM_CNT is always ordered except when there are flat instructions, which
387 // can return out of order.
388 Ordered[0] = !IsFlatOutstanding;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000389
390 // EXP_CNT is unordered if we have both EXP & VM-writes
391 Ordered[1] = ExpInstrTypesSeen == 3;
392
393 // LGKM_CNT is handled as always unordered. TODO: Handle LDS and GDS
394 Ordered[2] = false;
395
396 // The values we are going to put into the S_WAITCNT instruction
Konstantin Zhuravlyovcdd45472016-10-11 18:58:22 +0000397 Counters Counts = HardwareLimits;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000398
399 // Do we really need to wait?
400 bool NeedWait = false;
401
402 for (unsigned i = 0; i < 3; ++i) {
Tom Stellardc4cabef2013-01-18 21:15:53 +0000403 if (Required.Array[i] <= WaitedOn.Array[i])
404 continue;
405
406 NeedWait = true;
Matt Arsenault97483692014-07-17 17:50:22 +0000407
Tom Stellardc4cabef2013-01-18 21:15:53 +0000408 if (Ordered[i]) {
409 unsigned Value = LastIssued.Array[i] - Required.Array[i];
410
Matt Arsenault97483692014-07-17 17:50:22 +0000411 // Adjust the value to the real hardware possibilities.
Konstantin Zhuravlyovcdd45472016-10-11 18:58:22 +0000412 Counts.Array[i] = std::min(Value, HardwareLimits.Array[i]);
Tom Stellardc4cabef2013-01-18 21:15:53 +0000413
414 } else
415 Counts.Array[i] = 0;
416
Matt Arsenault97483692014-07-17 17:50:22 +0000417 // Remember on what we have waited on.
Tom Stellardc4cabef2013-01-18 21:15:53 +0000418 WaitedOn.Array[i] = LastIssued.Array[i] - Counts.Array[i];
419 }
420
421 if (!NeedWait)
422 return false;
423
424 // Reset EXP_CNT instruction types
425 if (Counts.Named.EXP == 0)
426 ExpInstrTypesSeen = 0;
427
428 // Build the wait instruction
429 BuildMI(MBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT))
Konstantin Zhuravlyovcdd45472016-10-11 18:58:22 +0000430 .addImm(encodeWaitcnt(IV,
431 Counts.Named.VM,
432 Counts.Named.EXP,
433 Counts.Named.LGKM));
Tom Stellardc4cabef2013-01-18 21:15:53 +0000434
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000435 LastOpcodeType = OTHER;
Marek Olsak1bd24632015-02-03 17:37:52 +0000436 LastInstWritesM0 = false;
Tom Stellard6695ba02016-10-28 23:53:48 +0000437 IsFlatOutstanding = false;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000438 return true;
439}
440
441/// \brief helper function for handleOperands
442static void increaseCounters(Counters &Dst, const Counters &Src) {
Tom Stellardc4cabef2013-01-18 21:15:53 +0000443 for (unsigned i = 0; i < 3; ++i)
444 Dst.Array[i] = std::max(Dst.Array[i], Src.Array[i]);
445}
446
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000447/// \brief check whether any of the counters is non-zero
448static bool countersNonZero(const Counters &Counter) {
449 for (unsigned i = 0; i < 3; ++i)
450 if (Counter.Array[i])
451 return true;
452 return false;
453}
454
455void SIInsertWaits::handleExistingWait(MachineBasicBlock::iterator I) {
456 assert(I->getOpcode() == AMDGPU::S_WAITCNT);
457
458 unsigned Imm = I->getOperand(0).getImm();
459 Counters Counts, WaitOn;
460
Konstantin Zhuravlyovcdd45472016-10-11 18:58:22 +0000461 Counts.Named.VM = decodeVmcnt(IV, Imm);
462 Counts.Named.EXP = decodeExpcnt(IV, Imm);
463 Counts.Named.LGKM = decodeLgkmcnt(IV, Imm);
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000464
465 for (unsigned i = 0; i < 3; ++i) {
466 if (Counts.Array[i] <= LastIssued.Array[i])
467 WaitOn.Array[i] = LastIssued.Array[i] - Counts.Array[i];
468 else
469 WaitOn.Array[i] = 0;
470 }
471
472 increaseCounters(DelayedWaitOn, WaitOn);
473}
474
Tom Stellardc4cabef2013-01-18 21:15:53 +0000475Counters SIInsertWaits::handleOperands(MachineInstr &MI) {
Tom Stellardc4cabef2013-01-18 21:15:53 +0000476 Counters Result = ZeroCounts;
477
Matt Arsenaultd1d499a2015-10-01 21:43:15 +0000478 // For each register affected by this instruction increase the result
479 // sequence.
480 //
481 // TODO: We could probably just look at explicit operands if we removed VCC /
482 // EXEC from SMRD dest reg classes.
Tom Stellardc4cabef2013-01-18 21:15:53 +0000483 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
Tom Stellardc4cabef2013-01-18 21:15:53 +0000484 MachineOperand &Op = MI.getOperand(i);
Matt Arsenaultd1d499a2015-10-01 21:43:15 +0000485 if (!Op.isReg() || !TRI->isInAllocatableClass(Op.getReg()))
486 continue;
487
488 const TargetRegisterClass *RC = TII->getOpRegClass(MI, i);
489 RegInterval Interval = getRegInterval(RC, Op);
Tom Stellardc4cabef2013-01-18 21:15:53 +0000490 for (unsigned j = Interval.first; j < Interval.second; ++j) {
Christian Konig862fd9f2013-03-01 09:46:04 +0000491 if (Op.isDef()) {
Tom Stellardc4cabef2013-01-18 21:15:53 +0000492 increaseCounters(Result, UsedRegs[j]);
Christian Konigf1fd5fa2013-03-18 11:33:45 +0000493 increaseCounters(Result, DefinedRegs[j]);
Christian Konig862fd9f2013-03-01 09:46:04 +0000494 }
Tom Stellardc4cabef2013-01-18 21:15:53 +0000495
496 if (Op.isUse())
497 increaseCounters(Result, DefinedRegs[j]);
498 }
499 }
500
501 return Result;
502}
503
Marek Olsak1bd24632015-02-03 17:37:52 +0000504void SIInsertWaits::handleSendMsg(MachineBasicBlock &MBB,
505 MachineBasicBlock::iterator I) {
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000506 if (ST->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
Marek Olsak1bd24632015-02-03 17:37:52 +0000507 return;
508
509 // There must be "S_NOP 0" between an instruction writing M0 and S_SENDMSG.
Jan Veselyd48445d2017-01-04 18:06:55 +0000510 if (LastInstWritesM0 && (I->getOpcode() == AMDGPU::S_SENDMSG || I->getOpcode() == AMDGPU::S_SENDMSGHALT)) {
Marek Olsak1bd24632015-02-03 17:37:52 +0000511 BuildMI(MBB, I, DebugLoc(), TII->get(AMDGPU::S_NOP)).addImm(0);
512 LastInstWritesM0 = false;
513 return;
514 }
515
516 // Set whether this instruction sets M0
517 LastInstWritesM0 = false;
518
519 unsigned NumOperands = I->getNumOperands();
520 for (unsigned i = 0; i < NumOperands; i++) {
521 const MachineOperand &Op = I->getOperand(i);
522
523 if (Op.isReg() && Op.isDef() && Op.getReg() == AMDGPU::M0)
524 LastInstWritesM0 = true;
525 }
526}
527
Matt Arsenaulta0050b02014-06-19 01:19:19 +0000528// FIXME: Insert waits listed in Table 4.2 "Required User-Inserted Wait States"
529// around other non-memory instructions.
Tom Stellardc4cabef2013-01-18 21:15:53 +0000530bool SIInsertWaits::runOnMachineFunction(MachineFunction &MF) {
Tom Stellardc4cabef2013-01-18 21:15:53 +0000531 bool Changes = false;
532
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000533 ST = &MF.getSubtarget<SISubtarget>();
534 TII = ST->getInstrInfo();
535 TRI = &TII->getRegisterInfo();
Tom Stellardc4cabef2013-01-18 21:15:53 +0000536 MRI = &MF.getRegInfo();
Konstantin Zhuravlyov836cbff2016-09-30 17:01:40 +0000537 IV = getIsaVersion(ST->getFeatureBits());
Marek Olsak79c05872016-11-25 17:37:09 +0000538 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
Tom Stellardc4cabef2013-01-18 21:15:53 +0000539
Konstantin Zhuravlyovcdd45472016-10-11 18:58:22 +0000540 HardwareLimits.Named.VM = getVmcntBitMask(IV);
541 HardwareLimits.Named.EXP = getExpcntBitMask(IV);
542 HardwareLimits.Named.LGKM = getLgkmcntBitMask(IV);
543
Tom Stellardc4cabef2013-01-18 21:15:53 +0000544 WaitedOn = ZeroCounts;
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000545 DelayedWaitOn = ZeroCounts;
Tom Stellardc4cabef2013-01-18 21:15:53 +0000546 LastIssued = ZeroCounts;
Marek Olsakfa58e5e2014-12-07 17:17:43 +0000547 LastOpcodeType = OTHER;
Marek Olsak1bd24632015-02-03 17:37:52 +0000548 LastInstWritesM0 = false;
Tom Stellard6695ba02016-10-28 23:53:48 +0000549 IsFlatOutstanding = false;
Marek Olsak79c05872016-11-25 17:37:09 +0000550 ReturnsVoid = MFI->returnsVoid();
Tom Stellardc4cabef2013-01-18 21:15:53 +0000551
552 memset(&UsedRegs, 0, sizeof(UsedRegs));
553 memset(&DefinedRegs, 0, sizeof(DefinedRegs));
554
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000555 SmallVector<MachineInstr *, 4> RemoveMI;
Marek Olsak79c05872016-11-25 17:37:09 +0000556 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
557
558 bool HaveScalarStores = false;
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000559
Tom Stellardc4cabef2013-01-18 21:15:53 +0000560 for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
561 BI != BE; ++BI) {
562
563 MachineBasicBlock &MBB = *BI;
Marek Olsak79c05872016-11-25 17:37:09 +0000564
Tom Stellardc4cabef2013-01-18 21:15:53 +0000565 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
566 I != E; ++I) {
567
Marek Olsak79c05872016-11-25 17:37:09 +0000568 if (!HaveScalarStores && TII->isScalarStore(*I))
569 HaveScalarStores = true;
570
Matt Arsenault43e92fe2016-06-24 06:30:11 +0000571 if (ST->getGeneration() <= SISubtarget::SEA_ISLANDS) {
Tom Stellard30961762016-02-08 19:49:20 +0000572 // There is a hardware bug on CI/SI where SMRD instruction may corrupt
573 // vccz bit, so when we detect that an instruction may read from a
574 // corrupt vccz bit, we need to:
575 // 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD operations to
576 // complete.
577 // 2. Restore the correct value of vccz by writing the current value
578 // of vcc back to vcc.
579
580 if (TII->isSMRD(I->getOpcode())) {
581 VCCZCorrupt = true;
582 } else if (!hasOutstandingLGKM() && I->modifiesRegister(AMDGPU::VCC, TRI)) {
583 // FIXME: We only care about SMRD instructions here, not LDS or GDS.
584 // Whenever we store a value in vcc, the correct value of vccz is
585 // restored.
586 VCCZCorrupt = false;
587 }
588
589 // Check if we need to apply the bug work-around
Matt Arsenault52f14ec2016-11-07 19:09:27 +0000590 if (VCCZCorrupt && readsVCCZ(*I)) {
Tom Stellard30961762016-02-08 19:49:20 +0000591 DEBUG(dbgs() << "Inserting vccz bug work-around before: " << *I << '\n');
592
593 // Wait on everything, not just LGKM. vccz reads usually come from
594 // terminators, and we always wait on everything at the end of the
595 // block, so if we only wait on LGKM here, we might end up with
596 // another s_waitcnt inserted right after this if there are non-LGKM
597 // instructions still outstanding.
598 insertWait(MBB, I, LastIssued);
599
600 // Restore the vccz bit. Any time a value is written to vcc, the vcc
601 // bit is updated, so we can restore the bit by reading the value of
602 // vcc and then writing it back to the register.
603 BuildMI(MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
604 AMDGPU::VCC)
Matt Arsenault52f14ec2016-11-07 19:09:27 +0000605 .addReg(AMDGPU::VCC);
Tom Stellard30961762016-02-08 19:49:20 +0000606 }
607 }
608
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000609 // Record pre-existing, explicitly requested waits
610 if (I->getOpcode() == AMDGPU::S_WAITCNT) {
611 handleExistingWait(*I);
Duncan P. N. Exon Smith4d295112016-07-08 19:16:05 +0000612 RemoveMI.push_back(&*I);
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000613 continue;
614 }
Marek Olsak1bd24632015-02-03 17:37:52 +0000615
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000616 Counters Required;
617
618 // Wait for everything before a barrier.
619 //
620 // S_SENDMSG implicitly waits for all outstanding LGKM transfers to finish,
621 // but we also want to wait for any other outstanding transfers before
622 // signalling other hardware blocks
Konstantin Zhuravlyovd7bdf242016-09-30 16:50:36 +0000623 if ((I->getOpcode() == AMDGPU::S_BARRIER &&
624 ST->needWaitcntBeforeBarrier()) ||
Jan Veselyd48445d2017-01-04 18:06:55 +0000625 I->getOpcode() == AMDGPU::S_SENDMSG ||
626 I->getOpcode() == AMDGPU::S_SENDMSGHALT)
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000627 Required = LastIssued;
628 else
629 Required = handleOperands(*I);
630
631 Counters Increment = getHwCounts(*I);
632
633 if (countersNonZero(Required) || countersNonZero(Increment))
634 increaseCounters(Required, DelayedWaitOn);
635
636 Changes |= insertWait(MBB, I, Required);
637
638 pushInstruction(MBB, I, Increment);
Marek Olsak1bd24632015-02-03 17:37:52 +0000639 handleSendMsg(MBB, I);
Marek Olsak79c05872016-11-25 17:37:09 +0000640
641 if (I->getOpcode() == AMDGPU::S_ENDPGM ||
642 I->getOpcode() == AMDGPU::SI_RETURN)
643 EndPgmBlocks.push_back(&MBB);
Tom Stellardc4cabef2013-01-18 21:15:53 +0000644 }
645
646 // Wait for everything at the end of the MBB
647 Changes |= insertWait(MBB, MBB.getFirstTerminator(), LastIssued);
Tom Stellardc4cabef2013-01-18 21:15:53 +0000648 }
649
Marek Olsak79c05872016-11-25 17:37:09 +0000650 if (HaveScalarStores) {
651 // If scalar writes are used, the cache must be flushed or else the next
652 // wave to reuse the same scratch memory can be clobbered.
653 //
654 // Insert s_dcache_wb at wave termination points if there were any scalar
655 // stores, and only if the cache hasn't already been flushed. This could be
656 // improved by looking across blocks for flushes in postdominating blocks
657 // from the stores but an explicitly requested flush is probably very rare.
658 for (MachineBasicBlock *MBB : EndPgmBlocks) {
659 bool SeenDCacheWB = false;
660
661 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
662 I != E; ++I) {
663
664 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
665 SeenDCacheWB = true;
666 else if (TII->isScalarStore(*I))
667 SeenDCacheWB = false;
668
669 // FIXME: It would be better to insert this before a waitcnt if any.
670 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
671 I->getOpcode() == AMDGPU::SI_RETURN) && !SeenDCacheWB) {
672 Changes = true;
673 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
674 }
675 }
676 }
677 }
678
Nicolai Haehnlef66bdb52016-04-27 15:46:01 +0000679 for (MachineInstr *I : RemoveMI)
680 I->eraseFromParent();
681
Tom Stellardc4cabef2013-01-18 21:15:53 +0000682 return Changes;
683}