LLVM 24.0.0git
SIInsertHardClauses.cpp
Go to the documentation of this file.
1//===- SIInsertHardClauses.cpp - Insert Hard Clauses ----------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Insert s_clause instructions to form hard clauses.
11///
12/// Clausing load instructions can give cache coherency benefits. Before gfx10,
13/// the hardware automatically detected "soft clauses", which were sequences of
14/// memory instructions of the same type. In gfx10 this detection was removed,
15/// and the s_clause instruction was introduced to explicitly mark "hard
16/// clauses".
17///
18/// It's the scheduler's job to form the clauses by putting similar memory
19/// instructions next to each other. Our job is just to insert an s_clause
20/// instruction to mark the start of each clause.
21///
22/// Note that hard clauses are very similar to, but logically distinct from, the
23/// groups of instructions that have to be restartable when XNACK is enabled.
24/// The rules are slightly different in each case. For example an s_nop
25/// instruction breaks a restartable group, but can appear in the middle of a
26/// hard clause. (Before gfx10 there wasn't a distinction, and both were called
27/// "soft clauses" or just "clauses".)
28///
29/// The SIFormMemoryClauses pass and GCNHazardRecognizer deal with restartable
30/// groups, not hard clauses.
31//
32//===----------------------------------------------------------------------===//
33
34#include "AMDGPU.h"
35#include "GCNSubtarget.h"
39
40using namespace llvm;
41
42#define DEBUG_TYPE "si-insert-hard-clauses"
43
45 HardClauseLengthLimit("amdgpu-hard-clause-length-limit",
46 cl::desc("Maximum number of memory instructions to "
47 "place in the same hard clause"),
49
50namespace {
51
52enum HardClauseType {
53 // For GFX10 and GFX1250:
54
55 // Texture, buffer, global or scratch memory instructions.
56 HARDCLAUSE_VMEM,
57 // Flat (not global or scratch) memory instructions.
58 HARDCLAUSE_FLAT,
59
60 // For GFX11:
61
62 // Texture memory instructions.
63 HARDCLAUSE_MIMG_LOAD,
64 HARDCLAUSE_MIMG_STORE,
65 HARDCLAUSE_MIMG_ATOMIC,
66 HARDCLAUSE_MIMG_SAMPLE,
67 // Buffer, global or scratch memory instructions.
68 HARDCLAUSE_VMEM_LOAD,
69 HARDCLAUSE_VMEM_STORE,
70 HARDCLAUSE_VMEM_ATOMIC,
71 // Flat (not global or scratch) memory instructions.
72 HARDCLAUSE_FLAT_LOAD,
73 HARDCLAUSE_FLAT_STORE,
74 HARDCLAUSE_FLAT_ATOMIC,
75 // BVH instructions.
76 HARDCLAUSE_BVH,
77
78 // Common:
79
80 // Instructions that access LDS.
81 HARDCLAUSE_LDS,
82 // Scalar memory instructions.
83 HARDCLAUSE_SMEM,
84 // VALU instructions.
85 HARDCLAUSE_VALU,
86 LAST_REAL_HARDCLAUSE_TYPE = HARDCLAUSE_VALU,
87
88 // Internal instructions, which are allowed in the middle of a hard clause,
89 // except for s_waitcnt.
90 HARDCLAUSE_INTERNAL,
91 // Meta instructions that do not result in any ISA like KILL.
92 HARDCLAUSE_IGNORE,
93 // Instructions that are not allowed in a hard clause: SALU, export, branch,
94 // message, GDS, s_waitcnt and anything else not mentioned above.
95 HARDCLAUSE_ILLEGAL,
96};
97
98class SIInsertHardClauses {
99public:
100 const GCNSubtarget *ST = nullptr;
101
102 HardClauseType getHardClauseType(const MachineInstr &MI) {
103 if (MI.mayLoad() || (MI.mayStore() && ST->shouldClusterStores())) {
104 if (ST->getGeneration() == AMDGPUSubtarget::GFX10 ||
105 ST->hasGFX1250Insts()) {
108 if (ST->hasNSAClauseBug()) {
109 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(MI.getOpcode());
110 if (Info && Info->MIMGEncoding == AMDGPU::MIMGEncGfx10NSA)
111 return HARDCLAUSE_ILLEGAL;
112 }
113 return HARDCLAUSE_VMEM;
114 }
116 return HARDCLAUSE_FLAT;
117 } else {
118 if (SIInstrInfo::isMIMG(MI)) {
119 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(MI.getOpcode());
120 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
122 if (BaseInfo->BVH)
123 return HARDCLAUSE_BVH;
124 if (BaseInfo->Sampler || BaseInfo->MSAA)
125 return HARDCLAUSE_MIMG_SAMPLE;
126 return MI.mayLoad() ? MI.mayStore() ? HARDCLAUSE_MIMG_ATOMIC
127 : HARDCLAUSE_MIMG_LOAD
128 : HARDCLAUSE_MIMG_STORE;
129 }
132 return MI.mayLoad() ? MI.mayStore() ? HARDCLAUSE_VMEM_ATOMIC
133 : HARDCLAUSE_VMEM_LOAD
134 : HARDCLAUSE_VMEM_STORE;
135 }
136 if (SIInstrInfo::isFLAT(MI)) {
137 return MI.mayLoad() ? MI.mayStore() ? HARDCLAUSE_FLAT_ATOMIC
138 : HARDCLAUSE_FLAT_LOAD
139 : HARDCLAUSE_FLAT_STORE;
140 }
141 }
142 // TODO: LDS
144 return HARDCLAUSE_SMEM;
145 }
146
147 // Don't form VALU clauses. It's not clear what benefit they give, if any.
148
149 // In practice s_nop is the only internal instruction we're likely to see.
150 // It's safe to treat the rest as illegal.
151 if (MI.getOpcode() == AMDGPU::S_NOP)
152 return HARDCLAUSE_INTERNAL;
153 if (MI.isMetaInstruction())
154 return HARDCLAUSE_IGNORE;
155 return HARDCLAUSE_ILLEGAL;
156 }
157
158 // Track information about a clause as we discover it.
159 struct ClauseInfo {
160 // The type of all (non-internal) instructions in the clause.
161 HardClauseType Type = HARDCLAUSE_ILLEGAL;
162 // The first (necessarily non-internal) instruction in the clause.
163 MachineInstr *First = nullptr;
164 // The last non-internal instruction in the clause.
165 MachineInstr *Last = nullptr;
166 // The length of the clause including any internal instructions in the
167 // middle (but not at the end) of the clause.
168 unsigned Length = 0;
169 // Internal instructions at the and of a clause should not be included in
170 // the clause. Count them in TrailingInternalLength until a new memory
171 // instruction is added.
172 unsigned TrailingInternalLength = 0;
173 // The base operands of *Last.
175 };
176
177 bool emitClause(const ClauseInfo &CI, const SIInstrInfo *SII) {
178 if (CI.First == CI.Last)
179 return false;
180 assert(CI.Length <= ST->maxHardClauseLength() &&
181 "Hard clause is too long!");
182
183 auto &MBB = *CI.First->getParent();
184 auto ClauseMI =
185 BuildMI(MBB, *CI.First, DebugLoc(), SII->get(AMDGPU::S_CLAUSE))
186 .addImm(CI.Length - 1);
187 finalizeBundle(MBB, ClauseMI->getIterator(),
188 std::next(CI.Last->getIterator()));
189 return true;
190 }
191
192 // \return if scopes are different on gfx1250 and disallowed to be claused.
193 bool isIncompatibleScope(const MachineInstr &MI1, const MachineInstr &MI2,
194 const SIInstrInfo *SII) const {
195 assert(ST->getGeneration() == AMDGPUSubtarget::GFX12 &&
196 ST->hasGFX1250Insts());
197 int CPol1 = 0, CPol2 = 0;
198 if (const MachineOperand *Op =
199 SII->getNamedOperand(MI1, AMDGPU::OpName::cpol)) {
200 CPol1 = Op->getImm() & AMDGPU::CPol::SCOPE;
201 }
202 if (const MachineOperand *Op =
203 SII->getNamedOperand(MI2, AMDGPU::OpName::cpol)) {
204 CPol2 = Op->getImm() & AMDGPU::CPol::SCOPE;
205 }
206 return CPol1 != CPol2;
207 }
208
209 bool run(MachineFunction &MF) {
210 ST = &MF.getSubtarget<GCNSubtarget>();
211 if (!ST->hasHardClauses())
212 return false;
213
214 unsigned MaxClauseLength = MF.getFunction().getFnAttributeAsParsedInteger(
215 "amdgpu-hard-clause-length-limit", 255);
216 if (HardClauseLengthLimit.getNumOccurrences())
217 MaxClauseLength = HardClauseLengthLimit;
218 MaxClauseLength = std::min(MaxClauseLength, ST->maxHardClauseLength());
219 if (MaxClauseLength <= 1)
220 return false;
221
222 const SIInstrInfo *SII = ST->getInstrInfo();
223 const TargetRegisterInfo *TRI = ST->getRegisterInfo();
224
225 bool Changed = false;
226 for (auto &MBB : MF) {
227 ClauseInfo CI;
228 unsigned ExistingClauseRemaining = 0;
229 for (auto &MI : MBB) {
230 HardClauseType Type;
231 if (ExistingClauseRemaining) {
232 if (!MI.isMetaInstruction())
233 ExistingClauseRemaining--;
234 Type = HARDCLAUSE_ILLEGAL;
235 } else if (MI.getOpcode() == AMDGPU::S_CLAUSE) {
236 // Respect existing explicit clauses. Re-clausing instructions that
237 // are already covered by an S_CLAUSE can create nested clauses.
238 ExistingClauseRemaining = (MI.getOperand(0).getImm() & 63) + 1;
239 Type = HARDCLAUSE_ILLEGAL;
240 } else {
241 Type = getHardClauseType(MI);
242 }
243
244 int64_t Dummy1;
245 bool Dummy2;
246 LocationSize Dummy3 = LocationSize::precise(0);
248 if (Type <= LAST_REAL_HARDCLAUSE_TYPE) {
249 if (!SII->getMemOperandsWithOffsetWidth(MI, BaseOps, Dummy1, Dummy2,
250 Dummy3, TRI)) {
251 // We failed to get the base operands, so we'll never clause this
252 // instruction with any other, so pretend it's illegal.
253 Type = HARDCLAUSE_ILLEGAL;
254 }
255 }
256
257 if (CI.Length == MaxClauseLength ||
258 (CI.Length && Type != HARDCLAUSE_INTERNAL &&
259 Type != HARDCLAUSE_IGNORE &&
260 (Type != CI.Type ||
261 // Note that we lie to shouldClusterMemOps about the size of the
262 // cluster. When shouldClusterMemOps is called from the machine
263 // scheduler it limits the size of the cluster to avoid increasing
264 // register pressure too much, but this pass runs after register
265 // allocation so there is no need for that kind of limit.
266 // We also lie about the Offset and OffsetIsScalable parameters,
267 // as they aren't used in the SIInstrInfo implementation.
268 !SII->shouldClusterMemOps(CI.BaseOps, 0, false, BaseOps, 0, false,
269 2, 2))) ||
270 (CI.Length && ST->hasGFX1250_STRICT() &&
271 isIncompatibleScope(MI, *CI.Last, SII))) {
272 // Finish the current clause.
273 Changed |= emitClause(CI, SII);
274 CI = ClauseInfo();
275 }
276
277 if (CI.Length) {
278 // Extend the current clause.
279 if (Type != HARDCLAUSE_IGNORE) {
280 if (Type == HARDCLAUSE_INTERNAL) {
281 ++CI.TrailingInternalLength;
282 } else {
283 ++CI.Length;
284 CI.Length += CI.TrailingInternalLength;
285 CI.TrailingInternalLength = 0;
286 CI.Last = &MI;
287 CI.BaseOps = std::move(BaseOps);
288 }
289 }
290 } else if (Type <= LAST_REAL_HARDCLAUSE_TYPE) {
291 // Start a new clause.
292 CI = ClauseInfo{Type, &MI, &MI, 1, 0, std::move(BaseOps)};
293 }
294 }
295
296 // Finish the last clause in the basic block if any.
297 if (CI.Length)
298 Changed |= emitClause(CI, SII);
299 }
300
301 return Changed;
302 }
303};
304
305class SIInsertHardClausesLegacy : public MachineFunctionPass {
306public:
307 static char ID;
308 SIInsertHardClausesLegacy() : MachineFunctionPass(ID) {}
309
310 bool runOnMachineFunction(MachineFunction &MF) override {
311 if (skipFunction(MF.getFunction()))
312 return false;
313
314 return SIInsertHardClauses().run(MF);
315 }
316
317 void getAnalysisUsage(AnalysisUsage &AU) const override {
318 AU.setPreservesCFG();
320 }
321};
322
323} // namespace
324
328 if (!SIInsertHardClauses().run(MF))
329 return PreservedAnalyses::all();
330
332 PA.preserveSet<CFGAnalyses>();
333 return PA;
334}
335
336char SIInsertHardClausesLegacy::ID = 0;
337
338char &llvm::SIInsertHardClausesID = SIInsertHardClausesLegacy::ID;
339
340INITIALIZE_PASS(SIInsertHardClausesLegacy, DEBUG_TYPE, "SI Insert Hard Clauses",
341 false, false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static cl::opt< unsigned > HardClauseLengthLimit("amdgpu-hard-clause-length-limit", cl::desc("Maximum number of memory instructions to " "place in the same hard clause"), cl::Hidden)
This file defines the SmallVector class.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:278
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:777
static LocationSize precise(uint64_t Value)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static bool isVMEM(const MachineInstr &MI)
bool getMemOperandsWithOffsetWidth(const MachineInstr &LdSt, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width, const TargetRegisterInfo *TRI) const final
static bool isSMRD(const MachineInstr &MI)
bool shouldClusterMemOps(ArrayRef< const MachineOperand * > BaseOps1, int64_t Offset1, bool OffsetIsScalable1, ArrayRef< const MachineOperand * > BaseOps2, int64_t Offset2, bool OffsetIsScalable2, unsigned ClusterSize, unsigned NumBytes) const override
static bool isSegmentSpecificFLAT(const MachineInstr &MI)
static bool isMIMG(const MachineInstr &MI)
static bool isFLAT(const MachineInstr &MI)
LLVM_READONLY MachineOperand * getNamedOperand(MachineInstr &MI, AMDGPU::OpName OperandName) const
Returns the operand named Op.
self_iterator getIterator()
Definition ilist_node.h:123
Changed
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
DXILDebugInfoMap run(Module &M)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DWARFExpression::Operation Op
char & SIInsertHardClausesID