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
29#include "MCTargetDesc/R600MCTargetDesc.h"
30#include "R600.h"
31#include "R600Defines.h"
32#include "R600Subtarget.h"
33#include "llvm/CodeGen/MachineDominators.h"
34#include "llvm/CodeGen/MachineLoopInfo.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE "vec-merger"
39
40static bool isImplicitlyDef(MachineRegisterInfo &MRI, Register Reg) {
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: i + 1).getImm();
60 if (isImplicitlyDef(MRI, Reg: MO.getReg()))
61 UndefReg.emplace_back(args&: 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 MachineFunctionPass::getAnalysisUsage(AU);
107 }
108
109 MachineFunctionProperties getRequiredProperties() const override {
110 return MachineFunctionProperties().setIsSSA();
111 }
112
113 StringRef getPassName() const override {
114 return "R600 Vector Registers Merge Pass";
115 }
116
117 bool runOnMachineFunction(MachineFunction &Fn) override;
118};
119
120} // end anonymous namespace
121
122INITIALIZE_PASS_BEGIN(R600VectorRegMerger, DEBUG_TYPE,
123 "R600 Vector Reg Merger", false, false)
124INITIALIZE_PASS_END(R600VectorRegMerger, DEBUG_TYPE,
125 "R600 Vector Reg Merger", false, false)
126
127char R600VectorRegMerger::ID = 0;
128
129char &llvm::R600VectorRegMergerID = R600VectorRegMerger::ID;
130
131bool R600VectorRegMerger::canSwizzle(const MachineInstr &MI)
132 const {
133 if (TII->get(Opcode: MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)
134 return true;
135 switch (MI.getOpcode()) {
136 case R600::R600_ExportSwz:
137 case R600::EG_ExportSwz:
138 return true;
139 default:
140 return false;
141 }
142}
143
144bool R600VectorRegMerger::tryMergeVector(const RegSeqInfo *Untouched,
145 RegSeqInfo *ToMerge, std::vector< std::pair<unsigned, unsigned>> &Remap)
146 const {
147 unsigned CurrentUndexIdx = 0;
148 for (auto &It : ToMerge->RegToChan) {
149 auto PosInUntouched = Untouched->RegToChan.find(Val: It.first);
150 if (PosInUntouched != Untouched->RegToChan.end()) {
151 Remap.emplace_back(args&: It.second, args: (*PosInUntouched).second);
152 continue;
153 }
154 if (CurrentUndexIdx >= Untouched->UndefReg.size())
155 return false;
156 Remap.emplace_back(args&: It.second, args: Untouched->UndefReg[CurrentUndexIdx++]);
157 }
158
159 return true;
160}
161
162static
163unsigned getReassignedChan(
164 const std::vector<std::pair<unsigned, unsigned>> &RemapChan,
165 unsigned Chan) {
166 for (const auto &J : RemapChan) {
167 if (J.first == Chan)
168 return J.second;
169 }
170 llvm_unreachable("Chan wasn't reassigned");
171}
172
173MachineInstr *R600VectorRegMerger::RebuildVector(
174 RegSeqInfo *RSI, const RegSeqInfo *BaseRSI,
175 const std::vector<std::pair<unsigned, unsigned>> &RemapChan) const {
176 Register Reg = RSI->Instr->getOperand(i: 0).getReg();
177 MachineBasicBlock::iterator Pos = RSI->Instr;
178 MachineBasicBlock &MBB = *Pos->getParent();
179 const DebugLoc &DL = Pos->getDebugLoc();
180
181 Register SrcVec = BaseRSI->Instr->getOperand(i: 0).getReg();
182 DenseMap<Register, unsigned> UpdatedRegToChan = BaseRSI->RegToChan;
183 std::vector<Register> UpdatedUndef = BaseRSI->UndefReg;
184 for (const auto &It : RSI->RegToChan) {
185 Register DstReg = MRI->createVirtualRegister(RegClass: &R600::R600_Reg128RegClass);
186 unsigned SubReg = It.first;
187 unsigned Swizzle = It.second;
188 unsigned Chan = getReassignedChan(RemapChan, Chan: Swizzle);
189
190 MachineInstr *Tmp = BuildMI(BB&: MBB, I: Pos, MIMD: DL, MCID: TII->get(Opcode: R600::INSERT_SUBREG),
191 DestReg: DstReg)
192 .addReg(RegNo: SrcVec)
193 .addReg(RegNo: SubReg)
194 .addImm(Val: Chan);
195 UpdatedRegToChan[SubReg] = Chan;
196 std::vector<Register>::iterator ChanPos = llvm::find(Range&: UpdatedUndef, Val: Chan);
197 if (ChanPos != UpdatedUndef.end())
198 UpdatedUndef.erase(position: ChanPos);
199 assert(!is_contained(UpdatedUndef, Chan) &&
200 "UpdatedUndef shouldn't contain Chan more than once!");
201 LLVM_DEBUG(dbgs() << " ->"; Tmp->dump(););
202 (void)Tmp;
203 SrcVec = DstReg;
204 }
205 MachineInstr *NewMI =
206 BuildMI(BB&: MBB, I: Pos, MIMD: DL, MCID: TII->get(Opcode: R600::COPY), DestReg: Reg).addReg(RegNo: SrcVec);
207 LLVM_DEBUG(dbgs() << " ->"; NewMI->dump(););
208
209 LLVM_DEBUG(dbgs() << " Updating Swizzle:\n");
210 for (MachineRegisterInfo::use_instr_iterator It = MRI->use_instr_begin(RegNo: Reg),
211 E = MRI->use_instr_end(); It != E; ++It) {
212 LLVM_DEBUG(dbgs() << " "; (*It).dump(); dbgs() << " ->");
213 SwizzleInput(*It, RemapChan);
214 LLVM_DEBUG((*It).dump());
215 }
216 RSI->Instr->eraseFromParent();
217
218 // Update RSI
219 RSI->Instr = NewMI;
220 RSI->RegToChan = std::move(UpdatedRegToChan);
221 RSI->UndefReg = std::move(UpdatedUndef);
222
223 return NewMI;
224}
225
226void R600VectorRegMerger::RemoveMI(MachineInstr *MI) {
227 for (auto &It : PreviousRegSeqByReg) {
228 std::vector<MachineInstr *> &MIs = It.second;
229 MIs.erase(first: llvm::find(Range&: MIs, Val: MI), last: MIs.end());
230 }
231 for (auto &It : PreviousRegSeqByUndefCount) {
232 std::vector<MachineInstr *> &MIs = It.second;
233 MIs.erase(first: llvm::find(Range&: MIs, Val: MI), last: MIs.end());
234 }
235}
236
237void R600VectorRegMerger::SwizzleInput(MachineInstr &MI,
238 const std::vector<std::pair<unsigned, unsigned>> &RemapChan) const {
239 unsigned Offset;
240 if (TII->get(Opcode: MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)
241 Offset = 2;
242 else
243 Offset = 3;
244 for (unsigned i = 0; i < 4; i++) {
245 unsigned Swizzle = MI.getOperand(i: i + Offset).getImm() + 1;
246 for (const auto &J : RemapChan) {
247 if (J.first == Swizzle) {
248 MI.getOperand(i: i + Offset).setImm(J.second - 1);
249 break;
250 }
251 }
252 }
253}
254
255bool R600VectorRegMerger::areAllUsesSwizzeable(Register Reg) const {
256 return llvm::all_of(Range: MRI->use_instructions(Reg),
257 P: [&](const MachineInstr &MI) { return canSwizzle(MI); });
258}
259
260bool R600VectorRegMerger::tryMergeUsingCommonSlot(RegSeqInfo &RSI,
261 RegSeqInfo &CompatibleRSI,
262 std::vector<std::pair<unsigned, unsigned>> &RemapChan) {
263 for (MachineInstr::mop_iterator MOp = RSI.Instr->operands_begin(),
264 MOE = RSI.Instr->operands_end(); MOp != MOE; ++MOp) {
265 if (!MOp->isReg())
266 continue;
267 auto &Insts = PreviousRegSeqByReg[MOp->getReg()];
268 if (Insts.empty())
269 continue;
270 for (MachineInstr *MI : Insts) {
271 CompatibleRSI = PreviousRegSeq[MI];
272 if (RSI == CompatibleRSI)
273 continue;
274 if (tryMergeVector(Untouched: &CompatibleRSI, ToMerge: &RSI, Remap&: RemapChan))
275 return true;
276 }
277 }
278 return false;
279}
280
281bool R600VectorRegMerger::tryMergeUsingFreeSlot(RegSeqInfo &RSI,
282 RegSeqInfo &CompatibleRSI,
283 std::vector<std::pair<unsigned, unsigned>> &RemapChan) {
284 unsigned NeededUndefs = 4 - RSI.UndefReg.size();
285 std::vector<MachineInstr *> &MIs =
286 PreviousRegSeqByUndefCount[NeededUndefs];
287 if (MIs.empty())
288 return false;
289 CompatibleRSI = PreviousRegSeq[MIs.back()];
290 tryMergeVector(Untouched: &CompatibleRSI, ToMerge: &RSI, Remap&: RemapChan);
291 return true;
292}
293
294void R600VectorRegMerger::trackRSI(const RegSeqInfo &RSI) {
295 for (DenseMap<Register, unsigned>::const_iterator
296 It = RSI.RegToChan.begin(), E = RSI.RegToChan.end(); It != E; ++It) {
297 PreviousRegSeqByReg[(*It).first].push_back(x: RSI.Instr);
298 }
299 PreviousRegSeqByUndefCount[RSI.UndefReg.size()].push_back(x: RSI.Instr);
300 PreviousRegSeq[RSI.Instr] = RSI;
301}
302
303bool R600VectorRegMerger::runOnMachineFunction(MachineFunction &Fn) {
304 if (skipFunction(F: Fn.getFunction()))
305 return false;
306
307 const R600Subtarget &ST = Fn.getSubtarget<R600Subtarget>();
308 TII = ST.getInstrInfo();
309 MRI = &Fn.getRegInfo();
310
311 for (MachineBasicBlock &MB : Fn) {
312 PreviousRegSeq.clear();
313 PreviousRegSeqByReg.clear();
314 PreviousRegSeqByUndefCount.clear();
315
316 for (MachineBasicBlock::iterator MII = MB.begin(), MIIE = MB.end();
317 MII != MIIE; ++MII) {
318 MachineInstr &MI = *MII;
319 if (MI.getOpcode() != R600::REG_SEQUENCE) {
320 if (TII->get(Opcode: MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST) {
321 Register Reg = MI.getOperand(i: 1).getReg();
322 for (MachineInstr &DefMI : MRI->def_instructions(Reg))
323 RemoveMI(MI: &DefMI);
324 }
325 continue;
326 }
327
328 RegSeqInfo RSI(*MRI, &MI);
329
330 // All uses of MI are swizzeable ?
331 Register Reg = MI.getOperand(i: 0).getReg();
332 if (!areAllUsesSwizzeable(Reg))
333 continue;
334
335 LLVM_DEBUG({
336 dbgs() << "Trying to optimize ";
337 MI.dump();
338 });
339
340 RegSeqInfo CandidateRSI;
341 std::vector<std::pair<unsigned, unsigned>> RemapChan;
342 LLVM_DEBUG(dbgs() << "Using common slots...\n";);
343 if (tryMergeUsingCommonSlot(RSI, CompatibleRSI&: CandidateRSI, RemapChan)) {
344 // Remove CandidateRSI mapping
345 RemoveMI(MI: CandidateRSI.Instr);
346 MII = RebuildVector(RSI: &RSI, BaseRSI: &CandidateRSI, RemapChan);
347 trackRSI(RSI);
348 continue;
349 }
350 LLVM_DEBUG(dbgs() << "Using free slots...\n";);
351 RemapChan.clear();
352 if (tryMergeUsingFreeSlot(RSI, CompatibleRSI&: CandidateRSI, RemapChan)) {
353 RemoveMI(MI: CandidateRSI.Instr);
354 MII = RebuildVector(RSI: &RSI, BaseRSI: &CandidateRSI, RemapChan);
355 trackRSI(RSI);
356 continue;
357 }
358 //Failed to merge
359 trackRSI(RSI);
360 }
361 }
362 return false;
363}
364
365llvm::FunctionPass *llvm::createR600VectorRegMerger() {
366 return new R600VectorRegMerger();
367}
368