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"
17#include "llvm/ADT/SetVector.h"
24using namespace llvm;
25
26#define DEBUG_TYPE "si-post-ra-16bit-mov-folding"
27
28namespace {
29
30class SIPostRA16BitMovFolding {
31private:
32 const SIInstrInfo *TII = nullptr;
33 const SIRegisterInfo *TRI = nullptr;
34
35 void getMovB16Info(const MachineInstr &MI, const SIRegisterInfo *TRI,
36 MCRegister &SrcReg16, bool &SrcIsVGPR,
37 MCRegister &SrcReg32, bool &SrcIsHi, bool &SrcIsImm,
38 int64_t &ImmVal) const;
39
40 bool mergeSingleMovB16Pair(MachineInstr &Lo, MachineInstr &Hi,
41 bool IsHiFirst) const;
42 bool mergeMovB16Pairs(MachineFunction &MF) const;
43
44public:
45 bool run(MachineFunction &MF);
46};
47
48class SIPostRA16BitMovFoldingLegacy : public MachineFunctionPass {
49public:
50 static char ID;
51
52 SIPostRA16BitMovFoldingLegacy() : MachineFunctionPass(ID) {}
53
54 StringRef getPassName() const override {
55 return "SI post-RA 16bit Mov Folding";
56 }
57
58 void getAnalysisUsage(AnalysisUsage &AU) const override {
59 AU.setPreservesAll();
61 }
62
63 bool runOnMachineFunction(MachineFunction &MF) override {
64 return SIPostRA16BitMovFolding().run(MF);
65 }
66};
67
68} // End anonymous namespace.
69
70INITIALIZE_PASS(SIPostRA16BitMovFoldingLegacy, DEBUG_TYPE,
71 "SI Post RA 16bit Mov Folding", false, false)
72
73char SIPostRA16BitMovFoldingLegacy::ID = 0;
74
75char &llvm::SIPostRA16BitMovFoldingLegacyID = SIPostRA16BitMovFoldingLegacy::ID;
76
77// Helper: extract the src operand and whether it is from the hi16 half.
78// Post-RA, both V_MOV_B16_t16_e32 and V_MOV_B16_t16_e64 use VGPR_16 dst
79// physical registers whose encoding already encodes hi/lo (IS_HI16 bit).
80void SIPostRA16BitMovFolding::getMovB16Info(
82 bool &SrcIsVGPR, MCRegister &SrcReg32, bool &SrcIsHi, bool &SrcIsImm,
83 int64_t &ImmVal) const {
84 SrcIsImm = false;
85 SrcIsHi = false;
86 SrcIsVGPR = false;
87 SrcReg16 = MCRegister();
88 SrcReg32 = MCRegister();
89
90 const MachineOperand *SrcOp = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
91
92 if (SrcOp->isImm()) {
93 SrcIsImm = true;
94 ImmVal = SrcOp->getImm();
95 return;
96 }
97
98 SrcReg16 = SrcOp->getReg().asMCReg();
99 SrcIsVGPR = AMDGPU::VGPR_16RegClass.contains(SrcReg16);
100 if (SrcIsVGPR) {
101 SrcIsHi = AMDGPU::isHi16Reg(SrcReg16, *TRI);
102 SrcReg32 = TRI->get32BitRegister(SrcReg16);
103 } else {
104 SrcIsHi = false;
105 SrcReg32 = SrcReg16;
106 }
107}
108
109// clang-format off
110// Try to merge a pair of v_mov_b16 instructions targeting the lo16 and hi16
111// halves of the same VGPR into a single 32-bit instruction.
112//
113// Caller guarantee the pair to be two v_mov_b16 and targets the same dst32
114//
115// Patterns:
116// v_mov_b16 v0.h, 0 v_mov_b16 v0.l, v2.l/s2 => v_and_b32 v0,0xffff,v2/s2
117// v_mov_b16 v0.h, 0 v_mov_b16 v0.l, v2.h => v_lshrrev_b32 v0,16,v2
118// v_mov_b16 v0.l, 0 v_mov_b16 v0.h, v2.l/s2 => v_lshlrev_b32 v0,16,v2/s2
119// v_mov_b16 v0.l, 0 v_mov_b16 v0.h, v2.h => v_and_b32 v0,0xffff0000,v2
120// 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
121// clang-format on
122bool SIPostRA16BitMovFolding::mergeSingleMovB16Pair(MachineInstr &Lo,
124 bool IsHiFirst) const {
125 // Lo and Hi share the same Dst32
126 MCRegister LoDst = Lo.getOperand(0).getReg().asMCReg();
127 MCRegister HiDst = Hi.getOperand(0).getReg().asMCReg();
128 MCRegister Dst32 = TRI->get32BitRegister(LoDst);
129
130 // Extract source info for Lo and Hi.
131 MCRegister LoSrc16, LoSrc32, HiSrc16, HiSrc32;
132 bool LoSrcIsHi, HiSrcIsHi, LoSrcIsImm, HiSrcIsImm, LoSrcIsVGPR, HiSrcIsVGPR;
133 int64_t LoImm = 0, HiImm = 0;
134
135 getMovB16Info(Lo, TRI, LoSrc16, LoSrcIsVGPR, LoSrc32, LoSrcIsHi, LoSrcIsImm,
136 LoImm);
137 getMovB16Info(Hi, TRI, HiSrc16, HiSrcIsVGPR, HiSrc32, HiSrcIsHi, HiSrcIsImm,
138 HiImm);
139
140 MachineInstr &FirstMI = IsHiFirst ? Hi : Lo;
141 MachineInstr &SecondMI = IsHiFirst ? Lo : Hi;
142
143 // Data Conflict counter
144 MachineBasicBlock::iterator UpperBound = SecondMI.getIterator();
146 unsigned LoopCnt = 0, UpperBoundCnt = UINT_MAX, LowerBoundCnt = 0;
147
148 MachineBasicBlock &MBB = *Lo.getParent();
149
150 // Check that between Lo and Hi, there are no instructions that:
151 // - modify Dst32
152 // - modify LoSrc16 or HiSrc16 depending on order (data dependency)
153 // We scan from the instruction after the first mov up to (but not including)
154 // the second mov.
155 MCRegister FirstSrc16 = IsHiFirst ? HiSrc16 : LoSrc16;
156 MCRegister FirstDst16 = IsHiFirst ? HiDst : LoDst;
157 MCRegister SecondSrc16 = IsHiFirst ? LoSrc16 : HiSrc16;
158 MCRegister SecondDst16 = IsHiFirst ? LoDst : HiDst;
159 for (MachineInstr &Scan :
160 drop_begin(make_range(FirstMI.getIterator(), SecondMI.getIterator()))) {
161 if (Scan.isDebugInstr())
162 continue;
163 if (Scan.modifiesRegister(Dst32, TRI))
164 return false;
165 assert(!Scan.modifiesRegister(AMDGPU::EXEC, TRI) &&
166 "Expect no write on EXEC!");
167 LoopCnt++;
168 if (LoopCnt < UpperBoundCnt &&
169 ((FirstSrc16 && Scan.modifiesRegister(FirstSrc16, TRI)) ||
170 Scan.readsRegister(FirstDst16, TRI))) {
171 UpperBound = Scan.getIterator();
172 UpperBoundCnt = LoopCnt;
173 }
174 if (LoopCnt > LowerBoundCnt &&
175 ((SecondSrc16 && Scan.modifiesRegister(SecondSrc16, TRI)) ||
176 Scan.readsRegister(SecondDst16, TRI))) {
177 LowerBound = Scan.getIterator();
178 LowerBoundCnt = LoopCnt;
179 }
180 }
181
182 // No spot maintains data dependency
183 if (LowerBoundCnt >= UpperBoundCnt)
184 return false;
185
186 // Insert MI before selected. Any spots between (LowerBound, UpperBound] would
187 // work
188 MachineInstr &Selected = *UpperBound;
189 const DebugLoc &DL = Selected.getDebugLoc();
190
191 // Now match patterns and emit the replacement instruction.
192 // Insert on Selected MI location, then remove both mov.
193
194 // Pattern: v_mov_b16 v0.l, v2.x/s2 + v_mov_b16 v0.h, v3.y/s3
195 // => v_perm_b32_e64 v0,v3.y/s3,v2.x/s2, mask
196 if (!HiSrcIsImm && !LoSrcIsImm) {
197 // Violate constant bus restriction
198 if (!LoSrcIsVGPR && !HiSrcIsVGPR && HiSrc32 != LoSrc32)
199 return false;
200 unsigned MaskHiSrc = HiSrcIsHi ? 0x0706 : 0x0504;
201 unsigned MaskLoSrc = LoSrcIsHi ? 0x0302 : 0x0100;
202 BuildMI(MBB, Selected, DL, TII->get(AMDGPU::V_PERM_B32_e64), Dst32)
203 .addReg(HiSrc32)
204 .addReg(LoSrc32)
205 .addImm((MaskHiSrc << 16) | MaskLoSrc);
206 Lo.eraseFromParent();
207 Hi.eraseFromParent();
208 return true;
209 }
210
211 bool Usevop2 =
212 AMDGPU::VGPR_32_Lo128RegClass.contains(Dst32) &&
213 (LoSrcIsImm ||
214 (LoSrcIsVGPR && AMDGPU::VGPR_32_Lo128RegClass.contains(LoSrc32))) &&
215 (HiSrcIsImm ||
216 (HiSrcIsVGPR && AMDGPU::VGPR_32_Lo128RegClass.contains(HiSrc32)));
217
218 // Pattern: v_mov_b16 v0.h, 0 + v_mov_b16 v0.l, v2.l/s2
219 // => v_and_b32 v0, 0x0000ffff, v2/s2
220 if (HiSrcIsImm && HiImm == 0 && !LoSrcIsImm && !LoSrcIsHi) {
221 BuildMI(MBB, Selected, DL,
222 TII->get(Usevop2 ? AMDGPU::V_AND_B32_e32 : AMDGPU::V_AND_B32_e64),
223 Dst32)
224 .addImm(0x0000ffff)
225 .addReg(LoSrc32);
226 Lo.eraseFromParent();
227 Hi.eraseFromParent();
228 return true;
229 }
230
231 // Pattern: v_mov_b16 v0.h, 0 + v_mov_b16 v0.l, v2.h
232 // => v_lshrrev_b32 v0, 16, v2
233 if (HiSrcIsImm && HiImm == 0 && !LoSrcIsImm && LoSrcIsHi) {
234 BuildMI(MBB, Selected, DL,
235 TII->get(Usevop2 ? AMDGPU::V_LSHRREV_B32_e32
236 : AMDGPU::V_LSHRREV_B32_e64),
237 Dst32)
238 .addImm(16)
239 .addReg(LoSrc32);
240 Lo.eraseFromParent();
241 Hi.eraseFromParent();
242 return true;
243 }
244
245 // Pattern: v_mov_b16 v0.l, 0 + v_mov_b16 v0.h, v2.l/s2
246 // => v_lshlrev_b32 v0, 16, v2/s2
247 if (LoSrcIsImm && LoImm == 0 && !HiSrcIsImm && !HiSrcIsHi) {
248 BuildMI(MBB, Selected, DL,
249 TII->get(Usevop2 ? AMDGPU::V_LSHLREV_B32_e32
250 : AMDGPU::V_LSHLREV_B32_e64),
251 Dst32)
252 .addImm(16)
253 .addReg(HiSrc32);
254 Lo.eraseFromParent();
255 Hi.eraseFromParent();
256 return true;
257 }
258
259 // Pattern: v_mov_b16 v0.l, 0 + v_mov_b16 v0.h, v2.h
260 // => v_and_b32 v0, 0xffff0000, v2
261 if (LoSrcIsImm && LoImm == 0 && !HiSrcIsImm && HiSrcIsHi) {
262 BuildMI(MBB, Selected, DL,
263 TII->get(Usevop2 ? AMDGPU::V_AND_B32_e32 : AMDGPU::V_AND_B32_e64),
264 Dst32)
265 .addImm(0xffff0000)
266 .addReg(HiSrc32);
267 Lo.eraseFromParent();
268 Hi.eraseFromParent();
269 return true;
270 }
271
272 return false;
273}
274
275// Merge pairs of v_mov_b16 targeting the lo16 and hi16 halves of the same
276// VGPR into a single 32-bit instruction (true16 mode only).
277bool SIPostRA16BitMovFolding::mergeMovB16Pairs(MachineFunction &MF) const {
278 bool Changed = false;
279 for (MachineBasicBlock &MBB : MF) {
280 // Map from 32-bit VGPR to the pending v_mov_b16 and its age.
281 // Tracks how many non-mov-b16 instructions have passed since the
282 // 16-bit write using a fixed size circular buffer
283 struct Pending {
284 MCRegister Dst32;
285 MachineInstr *MI;
286 unsigned IsHi;
287 };
288 // Search window size
289 const unsigned ScanLimit = 16;
290 std::array<Pending, ScanLimit> CirBuf = {};
291 SmallDenseMap<MCRegister, unsigned> PendingWrites;
292 unsigned Head = 0;
293
294 for (MachineInstr &MI : make_early_inc_range(MBB)) {
295 if (MI.isDebugInstr())
296 continue;
297
298 unsigned Opc = MI.getOpcode();
299 bool IsMovB16 = (Opc == AMDGPU::V_MOV_B16_t16_e32 ||
300 Opc == AMDGPU::V_MOV_B16_t16_e64);
301
302 if (++Head == ScanLimit)
303 Head = 0;
304
305 // Expire the last one
306 PendingWrites.erase(CirBuf[Head].Dst32);
307
308 if (!IsMovB16) {
309 CirBuf[Head] = {MCRegister(), nullptr, false};
310 continue;
311 }
312
313 LLVM_DEBUG(dbgs() << "Checking MI:" << MI << "\n");
314 MCRegister DstReg = MI.getOperand(0).getReg().asMCReg();
315 bool DstIsHi = AMDGPU::isHi16Reg(DstReg, *TRI);
316 MCRegister Dst32 = TRI->get32BitRegister(DstReg);
317
318 // Insert new one
319 CirBuf[Head] = {Dst32, &MI, DstIsHi};
320
321 auto [It, Inserted] = PendingWrites.insert({Dst32, Head});
322 if (!Inserted) {
323 if (CirBuf[It->second].IsHi == DstIsHi) {
324 It->second = Head;
325 continue;
326 }
327
328 // Look for a matching pending write.
329 MachineInstr &LoMI = !DstIsHi ? MI : *CirBuf[It->second].MI;
330 MachineInstr &HiMI = DstIsHi ? MI : *CirBuf[It->second].MI;
331 bool IsHiFirst = CirBuf[It->second].IsHi;
332 if (mergeSingleMovB16Pair(LoMI, HiMI, IsHiFirst)) {
333 Changed = true;
334 PendingWrites.erase(It);
335 } else {
336 It->second = Head;
337 }
338 }
339 }
340 }
341
342 return Changed;
343}
344
345PreservedAnalyses
348 SIPostRA16BitMovFolding().run(MF);
349 return PreservedAnalyses::all();
350}
351
352bool SIPostRA16BitMovFolding::run(MachineFunction &MF) {
353 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
354 TRI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();
355 TII = ST.getInstrInfo();
356 bool Changed = false;
357
358 // Try merge B16 Pair in true16 mode
359 if (ST.useRealTrue16Insts())
360 Changed |= mergeMovB16Pairs(MF);
361
362 return Changed;
363}
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 const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file implements a set that has insertion order iteration characteristics.
#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:426
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:319
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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 DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
MachineOperand class - Representation of each machine instruction operand.
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
self_iterator getIterator()
Definition ilist_node.h:123
Changed
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