LLVM 24.0.0git
SIPostRA16BitMovFolding.cpp
Go to the documentation of this file.
1//===-- SIPostRA16BitMovFolding.cpp ------------------------------------===//
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/// This pass performs the post RA 16bit Mov folding
11///
12//===----------------------------------------------------------------------===//
13
14#include "AMDGPU.h"
15#include "GCNSubtarget.h"
21using namespace llvm;
22
23#define DEBUG_TYPE "si-post-ra-16bit-mov-folding"
24
25namespace {
26
27class SIPostRA16BitMovFolding {
28private:
29 const SIInstrInfo *TII = nullptr;
30 const SIRegisterInfo *TRI = nullptr;
31
32 void getMovB16Info(const MachineInstr &MI, const SIRegisterInfo *TRI,
33 MCRegister &SrcReg16, bool &SrcIsVGPR,
34 MCRegister &SrcReg32, bool &SrcIsHi, bool &SrcIsImm,
35 int64_t &ImmVal) const;
36
37 void clearKillsBetween(MachineInstr &Begin, MachineInstr &End,
38 MCRegister Reg) const;
39 bool mergeSingleMovB16Pair(MachineInstr &Lo, MachineInstr &Hi,
40 bool IsHiFirst) const;
41 bool mergeMovB16Pairs(MachineFunction &MF) const;
42
43public:
44 bool run(MachineFunction &MF);
45};
46
47class SIPostRA16BitMovFoldingLegacy : public MachineFunctionPass {
48public:
49 static char ID;
50
51 SIPostRA16BitMovFoldingLegacy() : MachineFunctionPass(ID) {}
52
53 StringRef getPassName() const override {
54 return "SI post-RA 16bit Mov Folding";
55 }
56
57 void getAnalysisUsage(AnalysisUsage &AU) const override {
58 AU.setPreservesAll();
60 }
61
62 bool runOnMachineFunction(MachineFunction &MF) override {
63 return SIPostRA16BitMovFolding().run(MF);
64 }
65};
66
67} // End anonymous namespace.
68
69INITIALIZE_PASS(SIPostRA16BitMovFoldingLegacy, DEBUG_TYPE,
70 "SI Post RA 16bit Mov Folding", false, false)
71
72char SIPostRA16BitMovFoldingLegacy::ID = 0;
73
74char &llvm::SIPostRA16BitMovFoldingLegacyID = SIPostRA16BitMovFoldingLegacy::ID;
75
76// Helper: extract the src operand and whether it is from the hi16 half.
77// Post-RA, both V_MOV_B16_t16_e32 and V_MOV_B16_t16_e64 use VGPR_16 dst
78// physical registers whose encoding already encodes hi/lo (IS_HI16 bit).
79void SIPostRA16BitMovFolding::getMovB16Info(
81 bool &SrcIsVGPR, MCRegister &SrcReg32, bool &SrcIsHi, bool &SrcIsImm,
82 int64_t &ImmVal) const {
83 SrcIsImm = false;
84 SrcIsHi = false;
85 SrcIsVGPR = false;
86 SrcReg16 = MCRegister();
87 SrcReg32 = MCRegister();
88
89 const MachineOperand *SrcOp = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
90
91 if (SrcOp->isImm()) {
92 SrcIsImm = true;
93 ImmVal = SrcOp->getImm();
94 return;
95 }
96
97 SrcReg16 = SrcOp->getReg().asMCReg();
98 SrcIsVGPR = AMDGPU::VGPR_16RegClass.contains(SrcReg16);
99 if (SrcIsVGPR) {
100 SrcIsHi = AMDGPU::isHi16Reg(SrcReg16, *TRI);
101 SrcReg32 = TRI->get32BitRegister(SrcReg16);
102 } else {
103 SrcIsHi = false;
104 SrcReg32 = SrcReg16;
105 }
106}
107
108void SIPostRA16BitMovFolding::clearKillsBetween(MachineInstr &Begin,
110 MCRegister Reg) const {
111 assert(Reg && "Expected a register source");
112 for (MachineInstr &MI : make_range(std::next(End.getReverseIterator()),
113 Begin.getReverseIterator())) {
114 if (MI.isDebugInstr())
115 continue;
116
117 bool ReadsReg = false;
118 for (MachineOperand &MO : MI.uses()) {
119 if (!MO.isReg() || !MO.readsReg() || !TRI->regsOverlap(MO.getReg(), Reg))
120 continue;
121 ReadsReg = true;
122 MO.setIsKill(false);
123 }
124
125 if (ReadsReg)
126 return;
127 }
128}
129
130// clang-format off
131// Try to merge a pair of v_mov_b16 instructions targeting the lo16 and hi16
132// halves of the same VGPR into a single 32-bit instruction.
133//
134// Caller guarantee the pair to be two v_mov_b16 and targets the same dst32
135//
136// Patterns:
137// v_mov_b16 v0.h, 0 v_mov_b16 v0.l, v2.l/s2 => v_and_b32 v0,0xffff,v2/s2
138// v_mov_b16 v0.h, 0 v_mov_b16 v0.l, v2.h => v_lshrrev_b32 v0,16,v2
139// v_mov_b16 v0.l, 0 v_mov_b16 v0.h, v2.l/s2 => v_lshlrev_b32 v0,16,v2/s2
140// v_mov_b16 v0.l, 0 v_mov_b16 v0.h, v2.h => v_and_b32 v0,0xffff0000,v2
141// v_mov_b16 v0.l, v.x/s v_mov_b16 v0.h, v.y/s => v_perm_b32_e64 v0, v.x/s, v.y/s, mask
142// v_mov_b16 v0.l, imm0 v_mov_b16 v0.h, imm1 => v_mov_b32 v0, (imm1<<16)|imm0
143//
144// A second mov reading the half the first wrote is rewritten to read the first
145// mov's source before matching.
146// clang-format on
147bool SIPostRA16BitMovFolding::mergeSingleMovB16Pair(MachineInstr &Lo,
148 MachineInstr &Hi,
149 bool IsHiFirst) const {
150 // Lo and Hi share the same Dst32
151 MCRegister LoDst = Lo.getOperand(0).getReg().asMCReg();
152 MCRegister HiDst = Hi.getOperand(0).getReg().asMCReg();
153 MCRegister Dst32 = TRI->get32BitRegister(LoDst);
154
155 // Extract source info for Lo and Hi.
156 MCRegister LoSrc16, LoSrc32, HiSrc16, HiSrc32;
157 bool LoSrcIsHi, HiSrcIsHi, LoSrcIsImm, HiSrcIsImm, LoSrcIsVGPR, HiSrcIsVGPR;
158 int64_t LoImm = 0, HiImm = 0;
159
160 getMovB16Info(Lo, TRI, LoSrc16, LoSrcIsVGPR, LoSrc32, LoSrcIsHi, LoSrcIsImm,
161 LoImm);
162 getMovB16Info(Hi, TRI, HiSrc16, HiSrcIsVGPR, HiSrc32, HiSrcIsHi, HiSrcIsImm,
163 HiImm);
164
165 MachineInstr &FirstMI = IsHiFirst ? Hi : Lo;
166 MachineInstr &SecondMI = IsHiFirst ? Lo : Hi;
167
168 // Data Conflict counter
169 MachineBasicBlock::iterator UpperBound = SecondMI.getIterator();
171 unsigned LoopCnt = 0, UpperBoundCnt = UINT_MAX, LowerBoundCnt = 0;
172
173 MachineBasicBlock &MBB = *Lo.getParent();
174
175 // Check that between Lo and Hi, there are no instructions that:
176 // - modify Dst32
177 // - modify LoSrc16 or HiSrc16 depending on order (data dependency)
178 // We scan from the instruction after the first mov up to (but not including)
179 // the second mov.
180 MCRegister FirstSrc16 = IsHiFirst ? HiSrc16 : LoSrc16;
181 MCRegister FirstDst16 = IsHiFirst ? HiDst : LoDst;
182 MCRegister SecondSrc16 = IsHiFirst ? LoSrc16 : HiSrc16;
183 MCRegister SecondDst16 = IsHiFirst ? LoDst : HiDst;
184
185 // The merged instruction reads both sources before writing Dst32, so the
186 // second mov cannot read the half the first wrote. Forward the first mov's
187 // source into it instead.
188 if (SecondSrc16 && TRI->regsOverlap(SecondSrc16, FirstDst16)) {
189 // Overlap is always exact here; only that is forwardable.
190 if (SecondSrc16 != FirstDst16)
191 return false;
192 if (IsHiFirst) {
193 getMovB16Info(FirstMI, TRI, LoSrc16, LoSrcIsVGPR, LoSrc32, LoSrcIsHi,
194 LoSrcIsImm, LoImm);
195 } else {
196 getMovB16Info(FirstMI, TRI, HiSrc16, HiSrcIsVGPR, HiSrc32, HiSrcIsHi,
197 HiSrcIsImm, HiImm);
198 }
199 }
200
201 for (MachineInstr &Scan :
202 drop_begin(make_range(FirstMI.getIterator(), SecondMI.getIterator()))) {
203 if (Scan.isDebugInstr())
204 continue;
205 if (Scan.modifiesRegister(Dst32, TRI))
206 return false;
207 LoopCnt++;
208 if (LoopCnt < UpperBoundCnt &&
209 ((FirstSrc16 && Scan.modifiesRegister(FirstSrc16, TRI)) ||
210 Scan.readsRegister(FirstDst16, TRI))) {
211 UpperBound = Scan.getIterator();
212 UpperBoundCnt = LoopCnt;
213 }
214 if (LoopCnt > LowerBoundCnt &&
215 ((SecondSrc16 && Scan.modifiesRegister(SecondSrc16, TRI)) ||
216 Scan.readsRegister(SecondDst16, TRI))) {
217 LowerBound = Scan.getIterator();
218 LowerBoundCnt = LoopCnt;
219 }
220 }
221
222 // No spot maintains data dependency
223 if (LowerBoundCnt >= UpperBoundCnt)
224 return false;
225
226 // Insert MI before selected. Any spots between (LowerBound, UpperBound] would
227 // work
228 MachineInstr &Selected = *UpperBound;
229 const DebugLoc &DL = Selected.getDebugLoc();
230
231 // Now match patterns and emit the replacement instruction.
232 // Insert on Selected MI location, then remove both mov.
233
234 // Pattern: v_mov_b16 v0.l, v2.x/s2 + v_mov_b16 v0.h, v3.y/s3
235 // => v_perm_b32_e64 v0,v3.y/s3,v2.x/s2, mask
236 if (!HiSrcIsImm && !LoSrcIsImm) {
237 // Violate constant bus restriction
238 if (!LoSrcIsVGPR && !HiSrcIsVGPR && HiSrc32 != LoSrc32)
239 return false;
240 unsigned MaskHiSrc = HiSrcIsHi ? 0x0706 : 0x0504;
241 unsigned MaskLoSrc = LoSrcIsHi ? 0x0302 : 0x0100;
242 clearKillsBetween(FirstMI, Selected, FirstSrc16);
243 BuildMI(MBB, Selected, DL, TII->get(AMDGPU::V_PERM_B32_e64), Dst32)
244 .addReg(HiSrc32)
245 .addReg(LoSrc32)
246 .addImm((MaskHiSrc << 16) | MaskLoSrc);
248 Hi.eraseFromParent();
249 return true;
250 }
251
252 bool Usevop2 =
253 AMDGPU::VGPR_32_Lo128RegClass.contains(Dst32) &&
254 (LoSrcIsImm ||
255 (LoSrcIsVGPR && AMDGPU::VGPR_32_Lo128RegClass.contains(LoSrc32))) &&
256 (HiSrcIsImm ||
257 (HiSrcIsVGPR && AMDGPU::VGPR_32_Lo128RegClass.contains(HiSrc32)));
258
259 // Pattern: v_mov_b16 v0.l, imm0 + v_mov_b16 v0.h, imm1
260 // => v_mov_b32 v0, (imm1 << 16) | imm0
261 if (LoSrcIsImm && HiSrcIsImm) {
262 BuildMI(MBB, Selected, DL,
263 TII->get(Usevop2 ? AMDGPU::V_MOV_B32_e32 : AMDGPU::V_MOV_B32_e64),
264 Dst32)
265 .addImm(((HiImm & 0xffff) << 16) | (LoImm & 0xffff));
267 Hi.eraseFromParent();
268 return true;
269 }
270
271 // Pattern: v_mov_b16 v0.h, 0 + v_mov_b16 v0.l, v2.l/s2
272 // => v_and_b32 v0, 0x0000ffff, v2/s2
273 if (HiSrcIsImm && HiImm == 0 && !LoSrcIsImm && !LoSrcIsHi) {
274 if (FirstSrc16)
275 clearKillsBetween(FirstMI, Selected, FirstSrc16);
276 BuildMI(MBB, Selected, DL,
277 TII->get(Usevop2 ? AMDGPU::V_AND_B32_e32 : AMDGPU::V_AND_B32_e64),
278 Dst32)
279 .addImm(0x0000ffff)
280 .addReg(LoSrc32);
282 Hi.eraseFromParent();
283 return true;
284 }
285
286 // Pattern: v_mov_b16 v0.h, 0 + v_mov_b16 v0.l, v2.h
287 // => v_lshrrev_b32 v0, 16, v2
288 if (HiSrcIsImm && HiImm == 0 && !LoSrcIsImm && LoSrcIsHi) {
289 if (FirstSrc16)
290 clearKillsBetween(FirstMI, Selected, FirstSrc16);
291 BuildMI(MBB, Selected, DL,
292 TII->get(Usevop2 ? AMDGPU::V_LSHRREV_B32_e32
293 : AMDGPU::V_LSHRREV_B32_e64),
294 Dst32)
295 .addImm(16)
296 .addReg(LoSrc32);
298 Hi.eraseFromParent();
299 return true;
300 }
301
302 // Pattern: v_mov_b16 v0.l, 0 + v_mov_b16 v0.h, v2.l/s2
303 // => v_lshlrev_b32 v0, 16, v2/s2
304 if (LoSrcIsImm && LoImm == 0 && !HiSrcIsImm && !HiSrcIsHi) {
305 if (FirstSrc16)
306 clearKillsBetween(FirstMI, Selected, FirstSrc16);
307 BuildMI(MBB, Selected, DL,
308 TII->get(Usevop2 ? AMDGPU::V_LSHLREV_B32_e32
309 : AMDGPU::V_LSHLREV_B32_e64),
310 Dst32)
311 .addImm(16)
312 .addReg(HiSrc32);
314 Hi.eraseFromParent();
315 return true;
316 }
317
318 // Pattern: v_mov_b16 v0.l, 0 + v_mov_b16 v0.h, v2.h
319 // => v_and_b32 v0, 0xffff0000, v2
320 if (LoSrcIsImm && LoImm == 0 && !HiSrcIsImm && HiSrcIsHi) {
321 if (FirstSrc16)
322 clearKillsBetween(FirstMI, Selected, FirstSrc16);
323 BuildMI(MBB, Selected, DL,
324 TII->get(Usevop2 ? AMDGPU::V_AND_B32_e32 : AMDGPU::V_AND_B32_e64),
325 Dst32)
326 .addImm(0xffff0000)
327 .addReg(HiSrc32);
329 Hi.eraseFromParent();
330 return true;
331 }
332
333 return false;
334}
335
336// Merge pairs of v_mov_b16 targeting the lo16 and hi16 halves of the same
337// VGPR into a single 32-bit instruction (true16 mode only).
338bool SIPostRA16BitMovFolding::mergeMovB16Pairs(MachineFunction &MF) const {
339 bool Changed = false;
340 for (MachineBasicBlock &MBB : MF) {
341 // Map from 32-bit VGPR to the pending v_mov_b16 and its age.
342 // Tracks how many non-mov-b16 instructions have passed since the
343 // 16-bit write using a fixed size circular buffer
344 struct Pending {
345 MCRegister Dst32;
346 MachineInstr *MI;
347 unsigned IsHi;
348 };
349 // Search window size
350 const unsigned ScanLimit = 16;
351 std::array<Pending, ScanLimit> CirBuf = {};
352 SmallDenseMap<MCRegister, unsigned> PendingWrites;
353 unsigned Head = 0;
354
355 for (MachineInstr &MI : make_early_inc_range(MBB)) {
356 if (MI.isDebugInstr())
357 continue;
358
359 unsigned Opc = MI.getOpcode();
360 bool IsMovB16 = (Opc == AMDGPU::V_MOV_B16_t16_e32 ||
361 Opc == AMDGPU::V_MOV_B16_t16_e64);
362
363 if (++Head == ScanLimit)
364 Head = 0;
365
366 // Expire the last one
367 PendingWrites.erase(CirBuf[Head].Dst32);
368
369 if (!IsMovB16) {
370 CirBuf[Head] = {MCRegister(), nullptr, false};
371 continue;
372 }
373
374 LLVM_DEBUG(dbgs() << "Checking MI:" << MI << "\n");
375 MCRegister DstReg = MI.getOperand(0).getReg().asMCReg();
376 bool DstIsHi = AMDGPU::isHi16Reg(DstReg, *TRI);
377 MCRegister Dst32 = TRI->get32BitRegister(DstReg);
378
379 // Insert new one
380 CirBuf[Head] = {Dst32, &MI, DstIsHi};
381
382 auto [It, Inserted] = PendingWrites.insert({Dst32, Head});
383 if (!Inserted) {
384 if (CirBuf[It->second].IsHi == DstIsHi) {
385 It->second = Head;
386 continue;
387 }
388
389 // Look for a matching pending write.
390 MachineInstr &LoMI = !DstIsHi ? MI : *CirBuf[It->second].MI;
391 MachineInstr &HiMI = DstIsHi ? MI : *CirBuf[It->second].MI;
392 bool IsHiFirst = CirBuf[It->second].IsHi;
393 if (mergeSingleMovB16Pair(LoMI, HiMI, IsHiFirst)) {
394 Changed = true;
395 PendingWrites.erase(It);
396 } else {
397 It->second = Head;
398 }
399 }
400 }
401 }
402
403 return Changed;
404}
405
406PreservedAnalyses
409 SIPostRA16BitMovFolding().run(MF);
410 return PreservedAnalyses::all();
411}
412
413bool SIPostRA16BitMovFolding::run(MachineFunction &MF) {
414 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
415 TRI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();
416 TII = ST.getInstrInfo();
417 bool Changed = false;
418
419 // Try merge B16 Pair in true16 mode
420 if (ST.useRealTrue16Insts())
421 Changed |= mergeMovB16Pairs(MF);
422
423 return Changed;
424}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Register Reg
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineInstr *& Lo
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool erase(const KeyT &Val)
Definition DenseMap.h:930
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
MachineInstrBundleIterator< MachineInstr > iterator
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 & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
Register getReg() const
getReg - Returns the register number.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
int64_t getImm() const
Register getReg() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
self_iterator getIterator()
Definition ilist_node.h:123
bool isHi16Reg(MCRegister Reg, const MCRegisterInfo &MRI)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
char & SIPostRA16BitMovFoldingLegacyID
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320