LLVM 22.0.0git
AMDGPULowerVGPREncoding.cpp
Go to the documentation of this file.
1//===- AMDGPULowerVGPREncoding.cpp - lower VGPRs above v255 ---------------===//
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/// Lower VGPRs above first 256 on gfx1250.
11///
12/// The pass scans used VGPRs and inserts S_SET_VGPR_MSB instructions to switch
13/// VGPR addressing mode. The mode change is effective until the next change.
14/// This instruction provides high bits of a VGPR address for four of the
15/// operands: vdst, src0, src1, and src2, or other 4 operands depending on the
16/// instruction encoding. If bits are set they are added as MSB to the
17/// corresponding operand VGPR number.
18///
19/// There is no need to replace actual register operands because encoding of the
20/// high and low VGPRs is the same. I.e. v0 has the encoding 0x100, so does
21/// v256. v1 has the encoding 0x101 and v257 has the same encoding. So high
22/// VGPRs will survive until actual encoding and will result in a same actual
23/// bit encoding.
24///
25/// As a result the pass only inserts S_SET_VGPR_MSB to provide an actual offset
26/// to a VGPR address of the subseqent instructions. The InstPrinter will take
27/// care of the printing a low VGPR instead of a high one. In prinicple this
28/// shall be viable to print actual high VGPR numbers, but that would disagree
29/// with a disasm printing and create a situation where asm text is not
30/// deterministic.
31///
32/// This pass creates a convention where non-fall through basic blocks shall
33/// start with all 4 MSBs zero. Otherwise a disassembly would not be readable.
34/// An optimization here is possible but deemed not desirable because of the
35/// readbility concerns.
36///
37/// Consequentially the ABI is set to expect all 4 MSBs to be zero on entry.
38/// The pass must run very late in the pipeline to make sure no changes to VGPR
39/// operands will be made after it.
40//
41//===----------------------------------------------------------------------===//
42
44#include "AMDGPU.h"
45#include "GCNSubtarget.h"
47#include "SIInstrInfo.h"
49
50using namespace llvm;
51
52#define DEBUG_TYPE "amdgpu-lower-vgpr-encoding"
53
54namespace {
55
56class AMDGPULowerVGPREncoding {
57 static constexpr unsigned OpNum = 4;
58 static constexpr unsigned BitsPerField = 2;
59 static constexpr unsigned NumFields = 4;
60 static constexpr unsigned FieldMask = (1 << BitsPerField) - 1;
61 using ModeType = PackedVector<unsigned, BitsPerField,
62 std::bitset<BitsPerField * NumFields>>;
63
64 class ModeTy : public ModeType {
65 public:
66 // bitset constructor will set all bits to zero
67 ModeTy() : ModeType(0) {}
68
69 operator int64_t() const { return raw_bits().to_ulong(); }
70
71 static ModeTy fullMask() {
72 ModeTy M;
73 M.raw_bits().flip();
74 return M;
75 }
76 };
77
78public:
79 bool run(MachineFunction &MF);
80
81private:
82 const SIInstrInfo *TII;
83 const SIRegisterInfo *TRI;
84
85 /// Most recent s_set_* instruction.
86 MachineInstr *MostRecentModeSet;
87
88 /// Whether the current mode is known.
89 bool CurrentModeKnown;
90
91 /// Current mode bits.
92 ModeTy CurrentMode;
93
94 /// Current mask of mode bits that instructions since MostRecentModeSet care
95 /// about.
96 ModeTy CurrentMask;
97
98 /// Number of current hard clause instructions.
99 unsigned ClauseLen;
100
101 /// Number of hard clause instructions remaining.
102 unsigned ClauseRemaining;
103
104 /// Clause group breaks.
105 unsigned ClauseBreaks;
106
107 /// Last hard clause instruction.
109
110 /// Insert mode change before \p I. \returns true if mode was changed.
111 bool setMode(ModeTy NewMode, ModeTy Mask, MachineInstr *I);
112
113 /// Reset mode to default.
114 void resetMode(MachineInstr *I) { setMode(ModeTy(), ModeTy::fullMask(), I); }
115
116 /// If \p MO references VGPRs, return the MSBs. Otherwise, return nullopt.
117 std::optional<unsigned> getMSBs(const MachineOperand &MO) const;
118
119 /// Handle single \p MI. \return true if changed.
120 bool runOnMachineInstr(MachineInstr &MI);
121
122 /// Compute the mode and mode mask for a single \p MI given \p Ops operands
123 /// bit mapping. Optionally takes second array \p Ops2 for VOPD.
124 /// If provided and an operand from \p Ops is not a VGPR, then \p Ops2
125 /// is checked.
126 void computeMode(ModeTy &NewMode, ModeTy &Mask, MachineInstr &MI,
127 const AMDGPU::OpName Ops[OpNum],
128 const AMDGPU::OpName *Ops2 = nullptr);
129
130 /// Check if an instruction \p I is within a clause and returns a suitable
131 /// iterator to insert mode change. It may also modify the S_CLAUSE
132 /// instruction to extend it or drop the clause if it cannot be adjusted.
133 MachineInstr *handleClause(MachineInstr *I);
134};
135
136bool AMDGPULowerVGPREncoding::setMode(ModeTy NewMode, ModeTy Mask,
137 MachineInstr *I) {
138 assert((NewMode.raw_bits() & ~Mask.raw_bits()).none());
139
140 if (CurrentModeKnown) {
141 auto Delta = NewMode.raw_bits() ^ CurrentMode.raw_bits();
142
143 if ((Delta & Mask.raw_bits()).none()) {
144 CurrentMask |= Mask;
145 return false;
146 }
147
148 if (MostRecentModeSet && (Delta & CurrentMask.raw_bits()).none()) {
149 CurrentMode |= NewMode;
150 CurrentMask |= Mask;
151
152 MostRecentModeSet->getOperand(0).setImm(CurrentMode);
153 return true;
154 }
155 }
156
157 I = handleClause(I);
158 MostRecentModeSet =
159 BuildMI(*I->getParent(), I, {}, TII->get(AMDGPU::S_SET_VGPR_MSB))
160 .addImm(NewMode);
161
162 CurrentMode = NewMode;
163 CurrentMask = Mask;
164 CurrentModeKnown = true;
165 return true;
166}
167
168std::optional<unsigned>
169AMDGPULowerVGPREncoding::getMSBs(const MachineOperand &MO) const {
170 if (!MO.isReg())
171 return std::nullopt;
172
173 MCRegister Reg = MO.getReg();
174 const TargetRegisterClass *RC = TRI->getPhysRegBaseClass(Reg);
175 if (!RC || !TRI->isVGPRClass(RC))
176 return std::nullopt;
177
178 unsigned Idx = TRI->getHWRegIndex(Reg);
179 return Idx >> 8;
180}
181
182void AMDGPULowerVGPREncoding::computeMode(ModeTy &NewMode, ModeTy &Mask,
184 const AMDGPU::OpName Ops[OpNum],
185 const AMDGPU::OpName *Ops2) {
186 NewMode = {};
187 Mask = {};
188
189 for (unsigned I = 0; I < OpNum; ++I) {
190 MachineOperand *Op = TII->getNamedOperand(MI, Ops[I]);
191
192 std::optional<unsigned> MSBits;
193 if (Op)
194 MSBits = getMSBs(*Op);
195
196#if !defined(NDEBUG)
197 if (MSBits.has_value() && Ops2) {
198 auto Op2 = TII->getNamedOperand(MI, Ops2[I]);
199 if (Op2) {
200 std::optional<unsigned> MSBits2;
201 MSBits2 = getMSBs(*Op2);
202 if (MSBits2.has_value() && MSBits != MSBits2)
203 llvm_unreachable("Invalid VOPD pair was created");
204 }
205 }
206#endif
207
208 if (!MSBits.has_value() && Ops2) {
209 Op = TII->getNamedOperand(MI, Ops2[I]);
210 if (Op)
211 MSBits = getMSBs(*Op);
212 }
213
214 if (!MSBits.has_value())
215 continue;
216
217 // Skip tied uses of src2 of VOP2, these will be handled along with defs and
218 // only vdst bit affects these operands. We cannot skip tied uses of VOP3,
219 // these uses are real even if must match the vdst.
220 if (Ops[I] == AMDGPU::OpName::src2 && !Op->isDef() && Op->isTied() &&
223 TII->hasVALU32BitEncoding(MI.getOpcode()))))
224 continue;
225
226 NewMode[I] = MSBits.value();
227 Mask[I] = FieldMask;
228 }
229}
230
231bool AMDGPULowerVGPREncoding::runOnMachineInstr(MachineInstr &MI) {
233 if (Ops.first) {
234 ModeTy NewMode, Mask;
235 computeMode(NewMode, Mask, MI, Ops.first, Ops.second);
236 return setMode(NewMode, Mask, &MI);
237 }
238 assert(!TII->hasVGPRUses(MI) || MI.isMetaInstruction() || MI.isPseudo());
239
240 return false;
241}
242
243MachineInstr *AMDGPULowerVGPREncoding::handleClause(MachineInstr *I) {
244 if (!ClauseRemaining)
245 return I;
246
247 // A clause cannot start with a special instruction, place it right before
248 // the clause.
249 if (ClauseRemaining == ClauseLen) {
250 I = Clause->getPrevNode();
251 assert(I->isBundle());
252 return I;
253 }
254
255 // If a clause defines breaks each group cannot start with a mode change.
256 // just drop the clause.
257 if (ClauseBreaks) {
258 Clause->eraseFromBundle();
259 ClauseRemaining = 0;
260 return I;
261 }
262
263 // Otherwise adjust a number of instructions in the clause if it fits.
264 // If it does not clause will just become shorter. Since the length
265 // recorded in the clause is one less, increment the length after the
266 // update. Note that SIMM16[5:0] must be 1-62, not 0 or 63.
267 if (ClauseLen < 63)
268 Clause->getOperand(0).setImm(ClauseLen | (ClauseBreaks << 8));
269
270 ++ClauseLen;
271
272 return I;
273}
274
275bool AMDGPULowerVGPREncoding::run(MachineFunction &MF) {
276 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
277 if (!ST.has1024AddressableVGPRs())
278 return false;
279
280 TII = ST.getInstrInfo();
281 TRI = ST.getRegisterInfo();
282
283 bool Changed = false;
284 ClauseLen = ClauseRemaining = 0;
285 CurrentMode.reset();
286 CurrentMask.reset();
287 CurrentModeKnown = true;
288 for (auto &MBB : MF) {
289 MostRecentModeSet = nullptr;
290
291 for (auto &MI : llvm::make_early_inc_range(MBB.instrs())) {
292 if (MI.isMetaInstruction())
293 continue;
294
295 if (MI.isTerminator() || MI.isCall()) {
296 if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
297 MI.getOpcode() == AMDGPU::S_ENDPGM_SAVED) {
298 CurrentMode.reset();
299 CurrentModeKnown = true;
300 } else
301 resetMode(&MI);
302 continue;
303 }
304
305 if (MI.isInlineAsm()) {
306 if (TII->hasVGPRUses(MI))
307 resetMode(&MI);
308 continue;
309 }
310
311 if (MI.getOpcode() == AMDGPU::S_CLAUSE) {
312 assert(!ClauseRemaining && "Nested clauses are not supported");
313 ClauseLen = MI.getOperand(0).getImm();
314 ClauseBreaks = (ClauseLen >> 8) & 15;
315 ClauseLen = ClauseRemaining = (ClauseLen & 63) + 1;
316 Clause = &MI;
317 continue;
318 }
319
320 Changed |= runOnMachineInstr(MI);
321
322 if (ClauseRemaining)
323 --ClauseRemaining;
324 }
325
326 // If we're falling through to a block that has at least one other
327 // predecessor, we no longer know the mode.
328 MachineBasicBlock *Next = MBB.getNextNode();
329 if (Next && Next->pred_size() >= 2 &&
330 llvm::is_contained(Next->predecessors(), &MBB)) {
331 if (CurrentMode.raw_bits().any())
332 CurrentModeKnown = false;
333 }
334 }
335
336 return Changed;
337}
338
339class AMDGPULowerVGPREncodingLegacy : public MachineFunctionPass {
340public:
341 static char ID;
342
343 AMDGPULowerVGPREncodingLegacy() : MachineFunctionPass(ID) {}
344
345 bool runOnMachineFunction(MachineFunction &MF) override {
346 return AMDGPULowerVGPREncoding().run(MF);
347 }
348
349 void getAnalysisUsage(AnalysisUsage &AU) const override {
350 AU.setPreservesCFG();
352 }
353};
354
355} // namespace
356
357char AMDGPULowerVGPREncodingLegacy::ID = 0;
358
359char &llvm::AMDGPULowerVGPREncodingLegacyID = AMDGPULowerVGPREncodingLegacy::ID;
360
361INITIALIZE_PASS(AMDGPULowerVGPREncodingLegacy, DEBUG_TYPE,
362 "AMDGPU Lower VGPR Encoding", false, false)
363
367 if (!AMDGPULowerVGPREncoding().run(MF))
368 return PreservedAnalyses::all();
369
372 return PA;
373}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:58
Register Reg
Register const TargetRegisterInfo * TRI
This file implements the PackedVector class.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
Interface definition for SIInstrInfo.
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:33
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.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Representation of each machine instruction.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
Store a vector of values using a specific number of bits for each value.
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 & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
static bool isVOP2(const MachineInstr &MI)
static bool isVOP3(const MCInstrDesc &Desc)
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::pair< const AMDGPU::OpName *, const AMDGPU::OpName * > getVGPRLoweringOperandTables(const MCInstrDesc &Desc)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:646
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
DWARFExpression::Operation Op
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1899
char & AMDGPULowerVGPREncodingLegacyID