LLVM 24.0.0git
HexagonPeephole.cpp
Go to the documentation of this file.
1//===-- HexagonPeephole.cpp - Hexagon Peephole Optimizations --------------===//
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// This peephole pass optimizes in the following cases.
8// 1. Optimizes redundant sign extends for the following case
9// Transform the following pattern
10// %170 = SXTW %166
11// ...
12// %176 = COPY %170:isub_lo
13//
14// Into
15// %176 = COPY %166
16//
17// 2. Optimizes redundant negation of predicates.
18// %15 = CMPGTrr %6, %2
19// ...
20// %16 = NOT_p killed %15
21// ...
22// JMP_c killed %16, <%bb.1>, implicit dead %pc
23//
24// Into
25// %15 = CMPGTrr %6, %2;
26// ...
27// JMP_cNot killed %15, <%bb.1>, implicit dead %pc;
28//
29// 3. Fuse the A2_vminub/C2_cmpgtup intrinsic pair, which share inputs, into the
30// dual-output A6_vminub_RdP hardware instruction.
31// %1 = A2_vminub %a, %b
32// %2 = C2_cmpgtup %a, %b
33// turning it into
34// %3, %4 = A6_vminub_RdP %a, %b
35// (Hexagon has no multi-output intrinsics, so the two results are produced by
36// separate intrinsics that this pass recombines.)
37//
38// Note: The first two transformations make instructions like
39// %170 = SXTW %166 or %16 = NOT_p killed %15
40// redundant. A dead-instruction removal pass, such as DCE or DIE, eliminates
41// them.
42
43//===----------------------------------------------------------------------===//
44
45#include "Hexagon.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/DenseMap.h"
51#include "llvm/ADT/Statistic.h"
56#include "llvm/CodeGen/Passes.h"
59#include "llvm/Pass.h"
61
62using namespace llvm;
63
64#define DEBUG_TYPE "hexagon-peephole"
65
66namespace {
67 struct HexagonPeephole : public MachineFunctionPass {
68 const HexagonInstrInfo *QII;
70
71 public:
72 static char ID;
73 HexagonPeephole() : MachineFunctionPass(ID) {}
74
75 bool runOnMachineFunction(MachineFunction &MF) override;
76 bool fuseIntrinsicVMinUB(MachineFunction &MF);
77
78 StringRef getPassName() const override {
79 return "Hexagon optimize redundant zero and size extends";
80 }
81
82 void getAnalysisUsage(AnalysisUsage &AU) const override {
84 }
85 };
86}
87
88char HexagonPeephole::ID = 0;
89
90INITIALIZE_PASS(HexagonPeephole, "hexagon-peephole", "Hexagon Peephole",
91 false, false)
92
93bool HexagonPeephole::runOnMachineFunction(MachineFunction &MF) {
94 if (skipFunction(MF.getFunction()))
95 return false;
96
97 bool Changed = false;
98
99 QII = static_cast<const HexagonInstrInfo *>(MF.getSubtarget().getInstrInfo());
100 MRI = &MF.getRegInfo();
101 const auto &CLOpts = MF.getSubtarget<HexagonSubtarget>().getCLOpts();
102
104 DenseMap<unsigned, std::pair<unsigned, unsigned> > PeepholeDoubleRegsMap;
105
106 if (!CLOpts.opt_peephole)
107 return false;
108
109 // Loop over all of the basic blocks.
110 for (MachineBasicBlock &MBB : MF) {
111 PeepholeMap.clear();
112 PeepholeDoubleRegsMap.clear();
113
114 // Traverse the basic block.
116 // Look for sign extends:
117 // %170 = SXTW %166
118 if (CLOpts.optszext && MI.getOpcode() == Hexagon::A2_sxtw) {
119 assert(MI.getNumOperands() == 2);
120 MachineOperand &Dst = MI.getOperand(0);
121 MachineOperand &Src = MI.getOperand(1);
122 Register DstReg = Dst.getReg();
123 Register SrcReg = Src.getReg();
124 // Just handle virtual registers.
125 if (DstReg.isVirtual() && SrcReg.isVirtual()) {
126 // Map the following:
127 // %170 = SXTW %166
128 // PeepholeMap[170] = %166
129 PeepholeMap[DstReg] = SrcReg;
130 }
131 }
132
133 // Look for %170 = COMBINE_ir_V4 (0, %169)
134 // %170:DoublRegs, %169:IntRegs
135 if (CLOpts.opt_ext_to_64 && MI.getOpcode() == Hexagon::A4_combineir) {
136 assert(MI.getNumOperands() == 3);
137 MachineOperand &Dst = MI.getOperand(0);
138 MachineOperand &Src1 = MI.getOperand(1);
139 MachineOperand &Src2 = MI.getOperand(2);
140 if (Src1.getImm() != 0)
141 continue;
142 Register DstReg = Dst.getReg();
143 Register SrcReg = Src2.getReg();
144 PeepholeMap[DstReg] = SrcReg;
145 }
146
147 // Look for this sequence below
148 // %DoubleReg1 = LSRd_ri %DoubleReg0, 32
149 // %IntReg = COPY %DoubleReg1:isub_lo.
150 // and convert into
151 // %IntReg = COPY %DoubleReg0:isub_hi.
152 if (MI.getOpcode() == Hexagon::S2_lsr_i_p) {
153 assert(MI.getNumOperands() == 3);
154 MachineOperand &Dst = MI.getOperand(0);
155 MachineOperand &Src1 = MI.getOperand(1);
156 MachineOperand &Src2 = MI.getOperand(2);
157 if (Src2.getImm() != 32)
158 continue;
159 Register DstReg = Dst.getReg();
160 Register SrcReg = Src1.getReg();
161 PeepholeDoubleRegsMap[DstReg] =
162 std::make_pair(*&SrcReg, Hexagon::isub_hi);
163 }
164
165 // Look for P=NOT(P).
166 if (CLOpts.pnotp && MI.getOpcode() == Hexagon::C2_not) {
167 assert(MI.getNumOperands() == 2);
168 MachineOperand &Dst = MI.getOperand(0);
169 MachineOperand &Src = MI.getOperand(1);
170 Register DstReg = Dst.getReg();
171 Register SrcReg = Src.getReg();
172 // Just handle virtual registers.
173 if (DstReg.isVirtual() && SrcReg.isVirtual()) {
174 // Map the following:
175 // %170 = NOT_xx %166
176 // PeepholeMap[170] = %166
177 PeepholeMap[DstReg] = SrcReg;
178 }
179 }
180
181 // Look for copy:
182 // %176 = COPY %170:isub_lo
183 if (CLOpts.optszext && MI.isCopy()) {
184 assert(MI.getNumOperands() == 2);
185 MachineOperand &Dst = MI.getOperand(0);
186 MachineOperand &Src = MI.getOperand(1);
187
188 // Make sure we are copying the lower 32 bits.
189 if (Src.getSubReg() != Hexagon::isub_lo)
190 continue;
191
192 Register DstReg = Dst.getReg();
193 Register SrcReg = Src.getReg();
194 if (DstReg.isVirtual() && SrcReg.isVirtual()) {
195 // Try to find in the map.
196 if (unsigned PeepholeSrc = PeepholeMap.lookup(SrcReg)) {
197 // Change the 1st operand.
198 MI.removeOperand(1);
199 MI.addOperand(MachineOperand::CreateReg(PeepholeSrc, false));
200 Changed = true;
201 } else {
203 PeepholeDoubleRegsMap.find(SrcReg);
204 if (DI != PeepholeDoubleRegsMap.end()) {
205 std::pair<unsigned,unsigned> PeepholeSrc = DI->second;
206 MI.removeOperand(1);
207 MI.addOperand(MachineOperand::CreateReg(
208 PeepholeSrc.first, false /*isDef*/, false /*isImp*/,
209 false /*isKill*/, false /*isDead*/, false /*isUndef*/,
210 false /*isEarlyClobber*/, PeepholeSrc.second));
211 Changed = true;
212 }
213 }
214 }
215 }
216
217 // Look for Predicated instructions.
218 if (CLOpts.pnotp) {
219 bool Done = false;
220 if (QII->isPredicated(MI)) {
221 MachineOperand &Op0 = MI.getOperand(0);
222 Register Reg0 = Op0.getReg();
223 const TargetRegisterClass *RC0 = MRI->getRegClass(Reg0);
224 if (RC0->getID() == Hexagon::PredRegsRegClassID) {
225 // Handle instructions that have a prediate register in op0
226 // (most cases of predicable instructions).
227 if (Reg0.isVirtual()) {
228 // Try to find in the map.
229 if (unsigned PeepholeSrc = PeepholeMap.lookup(Reg0)) {
230 // Change the 1st operand and, flip the opcode.
231 MI.getOperand(0).setReg(PeepholeSrc);
232 int NewOp = QII->getInvertedPredicatedOpcode(MI.getOpcode());
233 MI.setDesc(QII->get(NewOp));
234 Changed = true;
235 Done = true;
236 }
237 }
238 }
239 }
240
241 if (!Done) {
242 // Handle special instructions.
243 unsigned Op = MI.getOpcode();
244 unsigned NewOp = 0;
245 unsigned PR = 1, S1 = 2, S2 = 3; // Operand indices.
246
247 switch (Op) {
248 case Hexagon::C2_mux:
249 case Hexagon::C2_muxii:
250 NewOp = Op;
251 break;
252 case Hexagon::C2_muxri:
253 NewOp = Hexagon::C2_muxir;
254 break;
255 case Hexagon::C2_muxir:
256 NewOp = Hexagon::C2_muxri;
257 break;
258 }
259 if (NewOp) {
260 Register PSrc = MI.getOperand(PR).getReg();
261 if (unsigned POrig = PeepholeMap.lookup(PSrc)) {
262 BuildMI(MBB, MI.getIterator(), MI.getDebugLoc(), QII->get(NewOp),
263 MI.getOperand(0).getReg())
264 .addReg(POrig)
265 .add(MI.getOperand(S2))
266 .add(MI.getOperand(S1));
267 MI.eraseFromParent();
268 Changed = true;
269 }
270 } // if (NewOp)
271 } // if (!Done)
272
273 } // if (CLOpts.pnotp)
274
275 } // Instruction
276 } // Basic Block
277
278 if (CLOpts.fuse_intrinsic_vminub)
279 Changed |= fuseIntrinsicVMinUB(MF);
280
281 return Changed;
282}
283
284// Return true if both instructions have identical input operands in order.
285static bool hasCommonInputOps(const MachineInstr &I1, const MachineInstr &I2) {
286 auto I1Uses = I1.explicit_uses();
287 auto I2Uses = I2.explicit_uses();
288 unsigned I1NumUses = I1.getNumExplicitOperands() - I1.getNumExplicitDefs();
289 unsigned I2NumUses = I2.getNumExplicitOperands() - I2.getNumExplicitDefs();
290 if (!I1NumUses || I1NumUses != I2NumUses)
291 return false;
292
293 auto I2Use = I2Uses.begin();
294 for (const MachineOperand &I1Use : I1Uses)
295 if (!I1Use.isIdenticalTo(*I2Use++))
296 return false;
297 return true;
298}
299
301 const MachineInstr &Between,
302 const TargetRegisterInfo *TRI) {
303 for (Register Input : Inputs)
304 if (Between.modifiesRegister(Input, TRI))
305 return true;
306 return false;
307}
308
309bool HexagonPeephole::fuseIntrinsicVMinUB(MachineFunction &MF) {
310 bool Changed = false;
311 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
312
313 for (MachineBasicBlock &MBB : MF) {
314 SmallPtrSet<MachineInstr *, 8> DeadMIs;
315
316 for (MachineInstr &MI : MBB) {
317 unsigned Opc = MI.getOpcode();
318 if ((Opc != Hexagon::A2_vminub && Opc != Hexagon::C2_cmpgtup) ||
319 DeadMIs.count(&MI))
320 continue;
321
322 unsigned SiblingOpc =
323 Opc == Hexagon::A2_vminub ? Hexagon::C2_cmpgtup : Hexagon::A2_vminub;
324 SmallVector<Register, 2> PhysicalInputs;
325 for (const MachineOperand &MO : MI.operands())
326 if (MO.isReg() && !MO.isDef() && MO.getReg().isPhysical())
327 PhysicalInputs.push_back(MO.getReg());
328 MachineInstr *Sibling = nullptr;
329 auto It = MI.getIterator();
330 for (++It; It != MBB.end(); ++It) {
331 if (!DeadMIs.count(&*It) && It->getOpcode() == SiblingOpc &&
332 hasCommonInputOps(MI, *It)) {
333 Sibling = &*It;
334 break;
335 }
336 if (modifiesPhysicalInput(PhysicalInputs, *It, TRI))
337 break;
338 }
339 if (!Sibling)
340 continue;
341
342 MachineInstr *VMin = Opc == Hexagon::A2_vminub ? &MI : Sibling;
343 MachineInstr *Cmp = Opc == Hexagon::A2_vminub ? Sibling : &MI;
344 Register VMinReg =
345 MRI->createVirtualRegister(&Hexagon::DoubleRegsRegClass);
346 Register CmpReg = MRI->createVirtualRegister(&Hexagon::PredRegsRegClass);
347
348 BuildMI(MBB, MI.getIterator(), MI.getDebugLoc(),
349 QII->get(Hexagon::A6_vminub_RdP), VMinReg)
350 .addReg(CmpReg, RegState::Define)
351 .add(VMin->getOperand(1))
352 .add(VMin->getOperand(2));
353
354 Register VMinDef = VMin->getOperand(0).getReg();
355 Register CmpDef = Cmp->getOperand(0).getReg();
356 assert(VMinDef.isVirtual() && CmpDef.isVirtual() &&
357 "vminub fusion requires virtual result registers");
358 MRI->replaceRegWith(VMinDef, VMinReg);
359 VMin->getOperand(0).setReg(VMinDef);
360 MRI->replaceRegWith(CmpDef, CmpReg);
361 Cmp->getOperand(0).setReg(CmpDef);
362
363 DeadMIs.insert(&MI);
364 DeadMIs.insert(Sibling);
365 Changed = true;
366 }
367
368 for (MachineInstr *MI : DeadMIs)
369 MI->eraseFromParent();
370 }
371
372 return Changed;
373}
374
376 return new HexagonPeephole();
377}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT S1
MachineBasicBlock & MBB
This file defines the DenseMap class.
static bool modifiesPhysicalInput(ArrayRef< Register > Inputs, const MachineInstr &Between, const TargetRegisterInfo *TRI)
static bool hasCommonInputOps(const MachineInstr &I1, const MachineInstr &I2)
IRTranslator LLVM IR MI
unsigned Opc
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
The Input class is used to parse a yaml document into in-memory structs and vectors.
Represent the analysis usage information of a pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end()
Definition DenseMap.h:686
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
const HexagonOptions & getCLOpts() const
unsigned getID() const
getID() - Return the register class ID number.
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 & add(const MachineOperand &MO) const
Representation of each machine instruction.
LLVM_ABI unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register.
mop_range explicit_uses()
LLVM_ABI unsigned getNumExplicitDefs() const
Returns the number of non-implicit definitions.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
self_iterator getIterator()
Definition ilist_node.h:123
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Done
Definition Threading.h:60
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
FunctionPass * createHexagonPeephole()
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DWARFExpression::Operation Op
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58