LLVM 23.0.0git
R600OptimizeVectorRegisters.cpp
Go to the documentation of this file.
1//===- R600MergeVectorRegisters.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 merges inputs of swizzeable instructions into vector sharing
11/// common data and/or have enough undef subreg using swizzle abilities.
12///
13/// For instance let's consider the following pseudo code :
14/// %5 = REG_SEQ %1, sub0, %2, sub1, %3, sub2, undef, sub3
15/// ...
16/// %7 = REG_SEQ %1, sub0, %3, sub1, undef, sub2, %4, sub3
17/// (swizzable Inst) %7, SwizzleMask : sub0, sub1, sub2, sub3
18///
19/// is turned into :
20/// %5 = REG_SEQ %1, sub0, %2, sub1, %3, sub2, undef, sub3
21/// ...
22/// %7 = INSERT_SUBREG %4, sub3
23/// (swizzable Inst) %7, SwizzleMask : sub0, sub2, sub1, sub3
24///
25/// This allow regalloc to reduce register pressure for vector registers and
26/// to reduce MOV count.
27//===----------------------------------------------------------------------===//
28
30#include "R600.h"
31#include "R600Defines.h"
32#include "R600Subtarget.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE "vec-merger"
39
41 if (Reg.isPhysical())
42 return false;
43 const MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
44 return MI && MI->isImplicitDef();
45}
46
47namespace {
48
49class RegSeqInfo {
50public:
51 MachineInstr *Instr;
52 DenseMap<Register, unsigned> RegToChan;
53 std::vector<Register> UndefReg;
54
55 RegSeqInfo(MachineRegisterInfo &MRI, MachineInstr *MI) : Instr(MI) {
56 assert(MI->getOpcode() == R600::REG_SEQUENCE);
57 for (unsigned i = 1, e = Instr->getNumOperands(); i < e; i+=2) {
58 MachineOperand &MO = Instr->getOperand(i);
59 unsigned Chan = Instr->getOperand(i + 1).getImm();
60 if (isImplicitlyDef(MRI, MO.getReg()))
61 UndefReg.emplace_back(Chan);
62 else
63 RegToChan[MO.getReg()] = Chan;
64 }
65 }
66
67 RegSeqInfo() = default;
68
69 bool operator==(const RegSeqInfo &RSI) const {
70 return RSI.Instr == Instr;
71 }
72};
73
74class R600VectorRegMerger : public MachineFunctionPass {
75private:
76 using InstructionSetMap = DenseMap<unsigned, std::vector<MachineInstr *>>;
77
78 MachineRegisterInfo *MRI;
79 const R600InstrInfo *TII = nullptr;
80 DenseMap<MachineInstr *, RegSeqInfo> PreviousRegSeq;
81 InstructionSetMap PreviousRegSeqByReg;
82 InstructionSetMap PreviousRegSeqByUndefCount;
83
84 bool canSwizzle(const MachineInstr &MI) const;
85 bool areAllUsesSwizzeable(Register Reg) const;
86 void SwizzleInput(MachineInstr &,
87 const std::vector<std::pair<unsigned, unsigned>> &RemapChan) const;
88 bool tryMergeVector(const RegSeqInfo *Untouched, RegSeqInfo *ToMerge,
89 std::vector<std::pair<unsigned, unsigned>> &Remap) const;
90 bool tryMergeUsingCommonSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,
91 std::vector<std::pair<unsigned, unsigned>> &RemapChan);
92 bool tryMergeUsingFreeSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,
93 std::vector<std::pair<unsigned, unsigned>> &RemapChan);
94 MachineInstr *RebuildVector(RegSeqInfo *MI, const RegSeqInfo *BaseVec,
95 const std::vector<std::pair<unsigned, unsigned>> &RemapChan) const;
96 void RemoveMI(MachineInstr *);
97 void trackRSI(const RegSeqInfo &RSI);
98
99public:
100 static char ID;
101
102 R600VectorRegMerger() : MachineFunctionPass(ID) {}
103
104 void getAnalysisUsage(AnalysisUsage &AU) const override {
105 AU.setPreservesCFG();
106 AU.addRequired<MachineDominatorTreeWrapperPass>();
107 AU.addPreserved<MachineDominatorTreeWrapperPass>();
108 AU.addRequired<MachineLoopInfoWrapperPass>();
109 AU.addPreserved<MachineLoopInfoWrapperPass>();
111 }
112
113 MachineFunctionProperties getRequiredProperties() const override {
114 return MachineFunctionProperties().setIsSSA();
115 }
116
117 StringRef getPassName() const override {
118 return "R600 Vector Registers Merge Pass";
119 }
120
121 bool runOnMachineFunction(MachineFunction &Fn) override;
122};
123
124} // end anonymous namespace
125
127 "R600 Vector Reg Merger", false, false)
128INITIALIZE_PASS_END(R600VectorRegMerger, DEBUG_TYPE,
129 "R600 Vector Reg Merger", false, false)
130
131char R600VectorRegMerger::ID = 0;
132
133char &llvm::R600VectorRegMergerID = R600VectorRegMerger::ID;
134
135bool R600VectorRegMerger::canSwizzle(const MachineInstr &MI)
136 const {
137 if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)
138 return true;
139 switch (MI.getOpcode()) {
140 case R600::R600_ExportSwz:
141 case R600::EG_ExportSwz:
142 return true;
143 default:
144 return false;
145 }
146}
147
148bool R600VectorRegMerger::tryMergeVector(const RegSeqInfo *Untouched,
149 RegSeqInfo *ToMerge, std::vector< std::pair<unsigned, unsigned>> &Remap)
150 const {
151 unsigned CurrentUndexIdx = 0;
152 for (auto &It : ToMerge->RegToChan) {
153 auto PosInUntouched = Untouched->RegToChan.find(It.first);
154 if (PosInUntouched != Untouched->RegToChan.end()) {
155 Remap.emplace_back(It.second, (*PosInUntouched).second);
156 continue;
157 }
158 if (CurrentUndexIdx >= Untouched->UndefReg.size())
159 return false;
160 Remap.emplace_back(It.second, Untouched->UndefReg[CurrentUndexIdx++]);
161 }
162
163 return true;
164}
165
166static
168 const std::vector<std::pair<unsigned, unsigned>> &RemapChan,
169 unsigned Chan) {
170 for (const auto &J : RemapChan) {
171 if (J.first == Chan)
172 return J.second;
173 }
174 llvm_unreachable("Chan wasn't reassigned");
175}
176
177MachineInstr *R600VectorRegMerger::RebuildVector(
178 RegSeqInfo *RSI, const RegSeqInfo *BaseRSI,
179 const std::vector<std::pair<unsigned, unsigned>> &RemapChan) const {
180 Register Reg = RSI->Instr->getOperand(0).getReg();
181 MachineBasicBlock::iterator Pos = RSI->Instr;
182 MachineBasicBlock &MBB = *Pos->getParent();
183 const DebugLoc &DL = Pos->getDebugLoc();
184
185 Register SrcVec = BaseRSI->Instr->getOperand(0).getReg();
186 DenseMap<Register, unsigned> UpdatedRegToChan = BaseRSI->RegToChan;
187 std::vector<Register> UpdatedUndef = BaseRSI->UndefReg;
188 for (const auto &It : RSI->RegToChan) {
189 Register DstReg = MRI->createVirtualRegister(&R600::R600_Reg128RegClass);
190 unsigned SubReg = It.first;
191 unsigned Swizzle = It.second;
192 unsigned Chan = getReassignedChan(RemapChan, Swizzle);
193
194 MachineInstr *Tmp = BuildMI(MBB, Pos, DL, TII->get(R600::INSERT_SUBREG),
195 DstReg)
196 .addReg(SrcVec)
197 .addReg(SubReg)
198 .addImm(Chan);
199 UpdatedRegToChan[SubReg] = Chan;
200 std::vector<Register>::iterator ChanPos = llvm::find(UpdatedUndef, Chan);
201 if (ChanPos != UpdatedUndef.end())
202 UpdatedUndef.erase(ChanPos);
203 assert(!is_contained(UpdatedUndef, Chan) &&
204 "UpdatedUndef shouldn't contain Chan more than once!");
205 LLVM_DEBUG(dbgs() << " ->"; Tmp->dump(););
206 (void)Tmp;
207 SrcVec = DstReg;
208 }
209 MachineInstr *NewMI =
210 BuildMI(MBB, Pos, DL, TII->get(R600::COPY), Reg).addReg(SrcVec);
211 LLVM_DEBUG(dbgs() << " ->"; NewMI->dump(););
212
213 LLVM_DEBUG(dbgs() << " Updating Swizzle:\n");
215 E = MRI->use_instr_end(); It != E; ++It) {
216 LLVM_DEBUG(dbgs() << " "; (*It).dump(); dbgs() << " ->");
217 SwizzleInput(*It, RemapChan);
218 LLVM_DEBUG((*It).dump());
219 }
220 RSI->Instr->eraseFromParent();
221
222 // Update RSI
223 RSI->Instr = NewMI;
224 RSI->RegToChan = std::move(UpdatedRegToChan);
225 RSI->UndefReg = std::move(UpdatedUndef);
226
227 return NewMI;
228}
229
230void R600VectorRegMerger::RemoveMI(MachineInstr *MI) {
231 for (auto &It : PreviousRegSeqByReg) {
232 std::vector<MachineInstr *> &MIs = It.second;
233 MIs.erase(llvm::find(MIs, MI), MIs.end());
234 }
235 for (auto &It : PreviousRegSeqByUndefCount) {
236 std::vector<MachineInstr *> &MIs = It.second;
237 MIs.erase(llvm::find(MIs, MI), MIs.end());
238 }
239}
240
241void R600VectorRegMerger::SwizzleInput(MachineInstr &MI,
242 const std::vector<std::pair<unsigned, unsigned>> &RemapChan) const {
243 unsigned Offset;
244 if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)
245 Offset = 2;
246 else
247 Offset = 3;
248 for (unsigned i = 0; i < 4; i++) {
249 unsigned Swizzle = MI.getOperand(i + Offset).getImm() + 1;
250 for (const auto &J : RemapChan) {
251 if (J.first == Swizzle) {
252 MI.getOperand(i + Offset).setImm(J.second - 1);
253 break;
254 }
255 }
256 }
257}
258
259bool R600VectorRegMerger::areAllUsesSwizzeable(Register Reg) const {
260 return llvm::all_of(MRI->use_instructions(Reg),
261 [&](const MachineInstr &MI) { return canSwizzle(MI); });
262}
263
264bool R600VectorRegMerger::tryMergeUsingCommonSlot(RegSeqInfo &RSI,
265 RegSeqInfo &CompatibleRSI,
266 std::vector<std::pair<unsigned, unsigned>> &RemapChan) {
267 for (MachineInstr::mop_iterator MOp = RSI.Instr->operands_begin(),
268 MOE = RSI.Instr->operands_end(); MOp != MOE; ++MOp) {
269 if (!MOp->isReg())
270 continue;
271 auto &Insts = PreviousRegSeqByReg[MOp->getReg()];
272 if (Insts.empty())
273 continue;
274 for (MachineInstr *MI : Insts) {
275 CompatibleRSI = PreviousRegSeq[MI];
276 if (RSI == CompatibleRSI)
277 continue;
278 if (tryMergeVector(&CompatibleRSI, &RSI, RemapChan))
279 return true;
280 }
281 }
282 return false;
283}
284
285bool R600VectorRegMerger::tryMergeUsingFreeSlot(RegSeqInfo &RSI,
286 RegSeqInfo &CompatibleRSI,
287 std::vector<std::pair<unsigned, unsigned>> &RemapChan) {
288 unsigned NeededUndefs = 4 - RSI.UndefReg.size();
289 std::vector<MachineInstr *> &MIs =
290 PreviousRegSeqByUndefCount[NeededUndefs];
291 if (MIs.empty())
292 return false;
293 CompatibleRSI = PreviousRegSeq[MIs.back()];
294 tryMergeVector(&CompatibleRSI, &RSI, RemapChan);
295 return true;
296}
297
298void R600VectorRegMerger::trackRSI(const RegSeqInfo &RSI) {
299 for (DenseMap<Register, unsigned>::const_iterator
300 It = RSI.RegToChan.begin(), E = RSI.RegToChan.end(); It != E; ++It) {
301 PreviousRegSeqByReg[(*It).first].push_back(RSI.Instr);
302 }
303 PreviousRegSeqByUndefCount[RSI.UndefReg.size()].push_back(RSI.Instr);
304 PreviousRegSeq[RSI.Instr] = RSI;
305}
306
307bool R600VectorRegMerger::runOnMachineFunction(MachineFunction &Fn) {
308 if (skipFunction(Fn.getFunction()))
309 return false;
310
311 const R600Subtarget &ST = Fn.getSubtarget<R600Subtarget>();
312 TII = ST.getInstrInfo();
313 MRI = &Fn.getRegInfo();
314
315 for (MachineBasicBlock &MB : Fn) {
316 PreviousRegSeq.clear();
317 PreviousRegSeqByReg.clear();
318 PreviousRegSeqByUndefCount.clear();
319
320 for (MachineBasicBlock::iterator MII = MB.begin(), MIIE = MB.end();
321 MII != MIIE; ++MII) {
322 MachineInstr &MI = *MII;
323 if (MI.getOpcode() != R600::REG_SEQUENCE) {
324 if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST) {
325 Register Reg = MI.getOperand(1).getReg();
326 for (MachineInstr &DefMI : MRI->def_instructions(Reg))
327 RemoveMI(&DefMI);
328 }
329 continue;
330 }
331
332 RegSeqInfo RSI(*MRI, &MI);
333
334 // All uses of MI are swizzeable ?
335 Register Reg = MI.getOperand(0).getReg();
336 if (!areAllUsesSwizzeable(Reg))
337 continue;
338
339 LLVM_DEBUG({
340 dbgs() << "Trying to optimize ";
341 MI.dump();
342 });
343
344 RegSeqInfo CandidateRSI;
345 std::vector<std::pair<unsigned, unsigned>> RemapChan;
346 LLVM_DEBUG(dbgs() << "Using common slots...\n";);
347 if (tryMergeUsingCommonSlot(RSI, CandidateRSI, RemapChan)) {
348 // Remove CandidateRSI mapping
349 RemoveMI(CandidateRSI.Instr);
350 MII = RebuildVector(&RSI, &CandidateRSI, RemapChan);
351 trackRSI(RSI);
352 continue;
353 }
354 LLVM_DEBUG(dbgs() << "Using free slots...\n";);
355 RemapChan.clear();
356 if (tryMergeUsingFreeSlot(RSI, CandidateRSI, RemapChan)) {
357 RemoveMI(CandidateRSI.Instr);
358 MII = RebuildVector(&RSI, &CandidateRSI, RemapChan);
359 trackRSI(RSI);
360 continue;
361 }
362 //Failed to merge
363 trackRSI(RSI);
364 }
365 }
366 return false;
367}
368
370 return new R600VectorRegMerger();
371}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static std::vector< std::pair< int, unsigned > > Swizzle(std::vector< std::pair< int, unsigned > > Src, R600InstrInfo::BankSwizzle Swz)
Provides R600 specific target descriptions.
static unsigned getReassignedChan(const std::vector< std::pair< unsigned, unsigned > > &RemapChan, unsigned Chan)
static bool isImplicitlyDef(MachineRegisterInfo &MRI, Register Reg)
AMDGPU R600 specific subclass of TargetSubtarget.
#define LLVM_DEBUG(...)
Definition Debug.h:114
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
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.
mop_iterator operands_begin()
mop_iterator operands_end()
MachineOperand * mop_iterator
iterator/begin/end - Iterate over all operands of a machine instruction.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
defusechain_instr_iterator< true, false, false, true > use_instr_iterator
use_instr_iterator/use_instr_begin/use_instr_end - Walk all uses of the specified register,...
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
use_instr_iterator use_instr_begin(Register RegNo) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
static use_instr_iterator use_instr_end()
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
LLVM_ABI MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
void dump() const
Definition Pass.cpp:146
Wrapper class representing virtual and physical registers.
Definition Register.h:20
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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.
@ Offset
Definition DWP.cpp:557
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1764
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1738
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionPass * createR600VectorRegMerger()
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946