LLVM 24.0.0git
PPCVSXFMAMutate.cpp
Go to the documentation of this file.
1//===--------------- PPCVSXFMAMutate.cpp - VSX FMA Mutation ---------------===//
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// This pass mutates the form of VSX FMA instructions to avoid unnecessary
10// copies.
11//
12//===----------------------------------------------------------------------===//
13
14#include "PPC.h"
15#include "PPCInstrInfo.h"
16#include "PPCTargetMachine.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Statistic.h"
32#include "llvm/Support/Debug.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE "ppc-vsx-fma-mutate"
39
40namespace llvm { namespace PPC {
42} }
43
44namespace {
45 // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
46 // (Altivec and scalar floating-point registers), we need to transform the
47 // copies into subregister copies with other restrictions.
48 struct PPCVSXFMAMutate : public MachineFunctionPass {
49 static char ID;
50 PPCVSXFMAMutate() : MachineFunctionPass(ID) {}
51
52 LiveIntervals *LIS;
53 const PPCInstrInfo *TII;
54
55protected:
56 bool processBlock(MachineBasicBlock &MBB) {
57 bool Changed = false;
58
59 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
60 const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
62 I != IE; ++I) {
63 MachineInstr &MI = *I;
64
65 // The default (A-type) VSX FMA form kills the addend (it is taken from
66 // the target register, which is then updated to reflect the result of
67 // the FMA). If the instruction, however, kills one of the registers
68 // used for the product, then we can use the M-form instruction (which
69 // will take that value from the to-be-defined register).
70
71 int AltOpc = PPC::getAltVSXFMAOpcode(MI.getOpcode());
72 if (AltOpc == -1)
73 continue;
74
75 // This pass is run after register coalescing, and so we're looking for
76 // a situation like this:
77 // ...
78 // %5 = COPY %9; VSLRC:%5,%9
79 // %5<def,tied1> = XSMADDADP %5<tied0>, %17, %16,
80 // implicit %rm; VSLRC:%5,%17,%16
81 // ...
82 // %9<def,tied1> = XSMADDADP %9<tied0>, %17, %19,
83 // implicit %rm; VSLRC:%9,%17,%19
84 // ...
85 // Where we can eliminate the copy by changing from the A-type to the
86 // M-type instruction. Specifically, for this example, this means:
87 // %5<def,tied1> = XSMADDADP %5<tied0>, %17, %16,
88 // implicit %rm; VSLRC:%5,%17,%16
89 // is replaced by:
90 // %16<def,tied1> = XSMADDMDP %16<tied0>, %18, %9,
91 // implicit %rm; VSLRC:%16,%18,%9
92 // and we remove: %5 = COPY %9; VSLRC:%5,%9
93
94 SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
95
96 VNInfo *AddendValNo =
97 LIS->getInterval(MI.getOperand(1).getReg()).Query(FMAIdx).valueIn();
98
99 // This can be null if the register is undef.
100 if (!AddendValNo)
101 continue;
102
103 MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
104
105 // The addend and this instruction must be in the same block.
106
107 if (!AddendMI || AddendMI->getParent() != MI.getParent())
108 continue;
109
110 // The addend must be a full copy within the same register class.
111
112 if (!AddendMI->isFullCopy())
113 continue;
114
115 Register AddendSrcReg = AddendMI->getOperand(1).getReg();
116 if (AddendSrcReg.isVirtual()) {
117 if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
118 MRI.getRegClass(AddendSrcReg))
119 continue;
120 } else {
121 // If AddendSrcReg is a physical register, make sure the destination
122 // register class contains it.
123 if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
124 ->contains(AddendSrcReg))
125 continue;
126 }
127
128 // In theory, there could be other uses of the addend copy before this
129 // fma. We could deal with this, but that would require additional
130 // logic below and I suspect it will not occur in any relevant
131 // situations. Additionally, check whether the copy source is killed
132 // prior to the fma. In order to replace the addend here with the
133 // source of the copy, it must still be live here. We can't use
134 // interval testing for a physical register, so as long as we're
135 // walking the MIs we may as well test liveness here.
136 //
137 // FIXME: There is a case that occurs in practice, like this:
138 // %9 = COPY %f1; VSSRC:%9
139 // ...
140 // %6 = COPY %9; VSSRC:%6,%9
141 // %7 = COPY %9; VSSRC:%7,%9
142 // %9<def,tied1> = XSMADDASP %9<tied0>, %1, %4; VSSRC:
143 // %6<def,tied1> = XSMADDASP %6<tied0>, %1, %2; VSSRC:
144 // %7<def,tied1> = XSMADDASP %7<tied0>, %1, %3; VSSRC:
145 // which prevents an otherwise-profitable transformation.
146 bool OtherUsers = false, KillsAddendSrc = false;
147 for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
148 J != JE; --J) {
149 if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
150 OtherUsers = true;
151 break;
152 }
153 if (J->modifiesRegister(AddendSrcReg, TRI) ||
154 J->killsRegister(AddendSrcReg, TRI)) {
155 KillsAddendSrc = true;
156 break;
157 }
158 }
159
160 if (OtherUsers || KillsAddendSrc)
161 continue;
162
163
164 // The transformation doesn't work well with things like:
165 // %5 = A-form-op %5, %11, %5;
166 // unless %11 is also a kill, so skip when it is not,
167 // and check operand 3 to see it is also a kill to handle the case:
168 // %5 = A-form-op %5, %5, %11;
169 // where %5 and %11 are both kills. This case would be skipped
170 // otherwise.
171 Register OldFMAReg = MI.getOperand(0).getReg();
172
173 // Find one of the product operands that is killed by this instruction.
174 unsigned KilledProdOp = 0, OtherProdOp = 0;
175 Register Reg2 = MI.getOperand(2).getReg();
176 Register Reg3 = MI.getOperand(3).getReg();
177 if (LIS->getInterval(Reg2).Query(FMAIdx).isKill()
178 && Reg2 != OldFMAReg) {
179 KilledProdOp = 2;
180 OtherProdOp = 3;
181 } else if (LIS->getInterval(Reg3).Query(FMAIdx).isKill()
182 && Reg3 != OldFMAReg) {
183 KilledProdOp = 3;
184 OtherProdOp = 2;
185 }
186
187 // If there are no usable killed product operands, then this
188 // transformation is likely not profitable.
189 if (!KilledProdOp)
190 continue;
191
192 // If the addend copy is used only by this MI, then the addend source
193 // register is likely not live here. This could be fixed (based on the
194 // legality checks above, the live range for the addend source register
195 // could be extended), but it seems likely that such a trivial copy can
196 // be coalesced away later, and thus is not worth the effort.
197 if (AddendSrcReg.isVirtual() &&
198 !LIS->getInterval(AddendSrcReg).liveAt(FMAIdx))
199 continue;
200
201 // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
202
203 Register KilledProdReg = MI.getOperand(KilledProdOp).getReg();
204 Register OtherProdReg = MI.getOperand(OtherProdOp).getReg();
205
206 unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
207 unsigned KilledProdSubReg = MI.getOperand(KilledProdOp).getSubReg();
208 unsigned OtherProdSubReg = MI.getOperand(OtherProdOp).getSubReg();
209
210 bool AddRegKill = AddendMI->getOperand(1).isKill();
211 bool KilledProdRegKill = MI.getOperand(KilledProdOp).isKill();
212 bool OtherProdRegKill = MI.getOperand(OtherProdOp).isKill();
213
214 bool AddRegUndef = AddendMI->getOperand(1).isUndef();
215 bool KilledProdRegUndef = MI.getOperand(KilledProdOp).isUndef();
216 bool OtherProdRegUndef = MI.getOperand(OtherProdOp).isUndef();
217
218 // If there isn't a class that fits, we can't perform the transform.
219 // This is needed for correctness with a mixture of VSX and Altivec
220 // instructions to make sure that a low VSX register is not assigned to
221 // the Altivec instruction.
222 if (!MRI.constrainRegClass(KilledProdReg,
223 MRI.getRegClass(OldFMAReg)))
224 continue;
225
226 assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
227 "Addend copy not tied to old FMA output!");
228
229 LLVM_DEBUG(dbgs() << "VSX FMA Mutation:\n " << MI);
230
231 MI.getOperand(0).setReg(KilledProdReg);
232 MI.getOperand(1).setReg(KilledProdReg);
233 MI.getOperand(3).setReg(AddendSrcReg);
234
235 MI.getOperand(0).setSubReg(KilledProdSubReg);
236 MI.getOperand(1).setSubReg(KilledProdSubReg);
237 MI.getOperand(3).setSubReg(AddSubReg);
238
239 MI.getOperand(1).setIsKill(KilledProdRegKill);
240 MI.getOperand(3).setIsKill(AddRegKill);
241
242 MI.getOperand(1).setIsUndef(KilledProdRegUndef);
243 MI.getOperand(3).setIsUndef(AddRegUndef);
244
245 MI.setDesc(TII->get(AltOpc));
246
247 // If the addend is also a multiplicand, replace it with the addend
248 // source in both places.
249 if (OtherProdReg == AddendMI->getOperand(0).getReg()) {
250 MI.getOperand(2).setReg(AddendSrcReg);
251 MI.getOperand(2).setSubReg(AddSubReg);
252 MI.getOperand(2).setIsKill(AddRegKill);
253 MI.getOperand(2).setIsUndef(AddRegUndef);
254 } else {
255 MI.getOperand(2).setReg(OtherProdReg);
256 MI.getOperand(2).setSubReg(OtherProdSubReg);
257 MI.getOperand(2).setIsKill(OtherProdRegKill);
258 MI.getOperand(2).setIsUndef(OtherProdRegUndef);
259 }
260
261 LLVM_DEBUG(dbgs() << " -> " << MI);
262
263 // The killed product operand was killed here, so we can reuse it now
264 // for the result of the fma.
265
266 LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
267 VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
268 for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
269 UI != UE;) {
270 MachineOperand &UseMO = *UI;
271 MachineInstr *UseMI = UseMO.getParent();
272 ++UI;
273
274 // Don't replace the result register of the copy we're about to erase.
275 if (UseMI == AddendMI)
276 continue;
277
278 UseMO.substVirtReg(KilledProdReg, KilledProdSubReg, *TRI);
279 }
280
281 // Recalculate the live intervals of the killed product operand.
282 LIS->removeInterval(KilledProdReg);
283 LiveInterval &NewFMAInt =
284 LIS->createAndComputeVirtRegInterval(KilledProdReg);
285
286 LLVM_DEBUG(dbgs() << " extended: " << NewFMAInt << '\n');
287 (void)NewFMAInt;
288
289 // Extend the live interval of the addend source (it might end at the
290 // copy to be removed, or somewhere in between there and here). This
291 // is necessary only if it is a physical register.
292 if (!AddendSrcReg.isVirtual())
293 for (MCRegUnit Unit : TRI->regunits(AddendSrcReg.asMCReg())) {
294 LiveRange &AddendSrcRange = LIS->getRegUnit(Unit);
295 AddendSrcRange.extendInBlock(LIS->getMBBStartIdx(&MBB),
296 FMAIdx.getRegSlot());
297 LLVM_DEBUG(dbgs() << " extended: " << AddendSrcRange << '\n');
298 }
299
300 FMAInt.removeValNo(FMAValNo);
301 LLVM_DEBUG(dbgs() << " trimmed: " << FMAInt << '\n');
302
303 // Remove the (now unused) copy.
304
305 LLVM_DEBUG(dbgs() << " removing: " << *AddendMI << '\n');
306 LIS->RemoveMachineInstrFromMaps(*AddendMI);
307 AddendMI->eraseFromParent();
308
309 Changed = true;
310 }
311
312 return Changed;
313 }
314
315public:
316 bool runOnMachineFunction(MachineFunction &MF) override {
317 if (skipFunction(MF.getFunction()))
318 return false;
319
320 // If we don't have VSX then go ahead and return without doing
321 // anything.
322 const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
323 if (!STI.hasVSX())
324 return false;
325
326 LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
327
328 TII = STI.getInstrInfo();
329
330 bool Changed = false;
331
332 if (!STI.getCLOpts().vsx_fma_mutation)
333 return Changed;
334
335 for (MachineBasicBlock &B : llvm::make_early_inc_range(MF))
336 if (processBlock(B))
337 Changed = true;
338
339 return Changed;
340 }
341
342 void getAnalysisUsage(AnalysisUsage &AU) const override {
343 AU.addRequired<LiveIntervalsWrapperPass>();
344 AU.addPreserved<LiveIntervalsWrapperPass>();
345 AU.addPreserved<SlotIndexesWrapperPass>();
346 AU.addPreserved<MachineDominatorTreeWrapperPass>();
347 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
348 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
350 }
351 };
352}
353
355 "PowerPC VSX FMA Mutation", false, false)
359 "PowerPC VSX FMA Mutation", false, false)
360
361char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
362
363char PPCVSXFMAMutate::ID = 0;
365 return new PPCVSXFMAMutate();
366}
MachineInstrBuilder & UseMI
static const MachineInstrBuilder & AddSubReg(const MachineInstrBuilder &MIB, MCRegister Reg, unsigned SubIdx, RegState State, const TargetRegisterInfo *TRI)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#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
MachineRegisterInfo & MRI
SI Optimize VGPR LiveRange
This file contains some templates that are useful if you are working with the STL at all.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool processBlock(MachineBasicBlock &MBB, const SystemZInstrInfo *TII, const TargetRegisterInfo *TRI)
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LLVM_ABI void removeValNo(VNInfo *ValNo)
removeValNo - Remove all the segments defined by the specified value#.
LLVM_ABI std::pair< VNInfo *, bool > extendInBlock(ArrayRef< SlotIndex > Undefs, SlotIndex StartIdx, SlotIndex Kill)
Attempt to extend a value defined after StartIdx to include Use.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock * getParent() const
bool isFullCopy() const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
unsigned getSubReg() const
LLVM_ABI void substVirtReg(Register Reg, unsigned SubIdx, const TargetRegisterInfo &)
substVirtReg - Substitute the current register with the virtual subregister Reg:SubReg.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
reg_nodbg_iterator reg_nodbg_begin(Register RegNo) const
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
static reg_nodbg_iterator reg_nodbg_end()
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
const PPCOptions & getCLOpts() const
const PPCInstrInfo * getInstrInfo() const override
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SlotIndex def
The index of the defining instruction.
Define some predicates that are used for node matching.
int32_t getAltVSXFMAOpcode(uint32_t Opcode)
This is an optimization pass for GlobalISel generic memory operations.
FunctionPass * createPPCVSXFMAMutatePass()
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
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
char & PPCVSXFMAMutateID