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);
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
224 bool Changed = false;
225 for (auto &MBB : MF) {
226 ClauseInfo CI;
227 unsigned ExistingClauseRemaining = 0;
228 for (auto &MI : MBB) {
229 HardClauseType Type;
230 if (ExistingClauseRemaining) {
231 if (!MI.isMetaInstruction())
232 ExistingClauseRemaining--;
233 Type = HARDCLAUSE_ILLEGAL;
234 } else if (MI.getOpcode() == AMDGPU::S_CLAUSE) {
235 // Respect existing explicit clauses. Re-clausing instructions that
236 // are already covered by an S_CLAUSE can create nested clauses.
237 ExistingClauseRemaining = (MI.getOperand(0).getImm() & 63) + 1;
238 Type = HARDCLAUSE_ILLEGAL;
239 } else {
240 Type = getHardClauseType(MI);
241 }
242
243 int64_t Dummy1;
244 bool Dummy2;
245 LocationSize Dummy3 = LocationSize::precise(0);
247 if (Type <= LAST_REAL_HARDCLAUSE_TYPE) {
248 if (!SII->getMemOperandsWithOffsetWidth(MI, BaseOps, Dummy1, Dummy2,
249 Dummy3)) {
250 // We failed to get the base operands, so we'll never clause this
251 // instruction with any other, so pretend it's illegal.
252 Type = HARDCLAUSE_ILLEGAL;
253 }
254 }
255
256 if (CI.Length == MaxClauseLength ||
257 (CI.Length && Type != HARDCLAUSE_INTERNAL &&
258 Type != HARDCLAUSE_IGNORE &&
259 (Type != CI.Type ||
260 // Note that we lie to shouldClusterMemOps about the size of the
261 // cluster. When shouldClusterMemOps is called from the machine
262 // scheduler it limits the size of the cluster to avoid increasing
263 // register pressure too much, but this pass runs after register
264 // allocation so there is no need for that kind of limit.
265 // We also lie about the Offset and OffsetIsScalable parameters,
266 // as they aren't used in the SIInstrInfo implementation.
267 !SII->shouldClusterMemOps(CI.BaseOps, 0, false, BaseOps, 0, false,
268 2, 2))) ||
269 (CI.Length && ST->hasGFX1250_STRICT() &&
270 isIncompatibleScope(MI, *CI.Last, SII))) {
271 // Finish the current clause.
272 Changed |= emitClause(CI, SII);
273 CI = ClauseInfo();
274 }
275
276 if (CI.Length) {
277 // Extend the current clause.
278 if (Type != HARDCLAUSE_IGNORE) {
279 if (Type == HARDCLAUSE_INTERNAL) {
280 ++CI.TrailingInternalLength;
281 } else {
282 ++CI.Length;
283 CI.Length += CI.TrailingInternalLength;
284 CI.TrailingInternalLength = 0;
285 CI.Last = &MI;
286 CI.BaseOps = std::move(BaseOps);
287 }
288 }
289 } else if (Type <= LAST_REAL_HARDCLAUSE_TYPE) {
290 // Start a new clause.
291 CI = ClauseInfo{Type, &MI, &MI, 1, 0, std::move(BaseOps)};
292 }
293 }
294
295 // Finish the last clause in the basic block if any.
296 if (CI.Length)
297 Changed |= emitClause(CI, SII);
298 }
299
300 return Changed;
301 }
302};
303
304class SIInsertHardClausesLegacy : public MachineFunctionPass {
305public:
306 static char ID;
307 SIInsertHardClausesLegacy() : MachineFunctionPass(ID) {}
308
309 bool runOnMachineFunction(MachineFunction &MF) override {
310 if (skipFunction(MF.getFunction()))
311 return false;
312
313 return SIInsertHardClauses().run(MF);
314 }
315
316 void getAnalysisUsage(AnalysisUsage &AU) const override {
317 AU.setPreservesCFG();
319 }
320};
321
322} // namespace
323
327 if (!SIInsertHardClauses().run(MF))
328 return PreservedAnalyses::all();
329
331 PA.preserveSet<CFGAnalyses>();
332 return PA;
333}
334
335char SIInsertHardClausesLegacy::ID = 0;
336
337char &llvm::SIInsertHardClausesID = SIInsertHardClausesLegacy::ID;
338
339INITIALIZE_PASS(SIInsertHardClausesLegacy, DEBUG_TYPE, "SI Insert Hard Clauses",
340 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
#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:781
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)
static bool isSMRD(const MachineInstr &MI)
bool getMemOperandsWithOffsetWidth(const MachineInstr &LdSt, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const final
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.
int getNumOccurrences() const
self_iterator getIterator()
Definition ilist_node.h:123
Changed
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the 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