LLVM 24.0.0git
MLxExpansionPass.cpp
Go to the documentation of this file.
1//===-- MLxExpansionPass.cpp - Expand MLx instrs to avoid hazards ---------===//
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// Expand VFP / NEON floating point MLA / MLS instructions (each to a pair of
10// multiple and add / sub instructions) when special VMLx hazards are detected.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ARM.h"
15#include "ARMBaseInstrInfo.h"
16#include "ARMSubtarget.h"
18#include "llvm/ADT/Statistic.h"
26#include "llvm/Support/Debug.h"
28using namespace llvm;
29
30#define DEBUG_TYPE "mlx-expansion"
31
32static cl::opt<bool>
33ForceExpand("expand-all-fp-mlx", cl::init(false), cl::Hidden);
35ExpandLimit("expand-limit", cl::init(~0U), cl::Hidden);
36
37STATISTIC(NumExpand, "Number of fp MLA / MLS instructions expanded");
38
39namespace {
40 struct MLxExpansion : public MachineFunctionPass {
41 static char ID;
42 MLxExpansion() : MachineFunctionPass(ID) {}
43
44 bool runOnMachineFunction(MachineFunction &Fn) override;
45
46 StringRef getPassName() const override {
47 return "ARM MLA / MLS expansion pass";
48 }
49
50 void getAnalysisUsage(AnalysisUsage &AU) const override {
51 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
53 }
54
55 private:
56 const ARMBaseInstrInfo *TII;
57 const TargetRegisterInfo *TRI;
58 MachineRegisterInfo *MRI;
59
60 bool isLikeA9;
61 bool isSwift;
62 unsigned MIIdx;
63 MachineInstr* LastMIs[4];
64 SmallPtrSet<MachineInstr*, 4> IgnoreStall;
65
66 void clearStack();
67 void pushStack(MachineInstr *MI);
68 MachineInstr *getAccDefMI(MachineInstr *MI) const;
69 unsigned getDefReg(MachineInstr *MI) const;
70 bool hasLoopHazard(MachineInstr *MI) const;
71 bool hasRAWHazard(unsigned Reg, MachineInstr *MI) const;
72 bool FindMLxHazard(MachineInstr *MI);
73 void ExpandFPMLxInstruction(MachineBasicBlock &MBB, MachineInstr *MI,
74 unsigned MulOpc, unsigned AddSubOpc,
75 bool NegAcc, bool HasLane);
76 bool ExpandFPMLxInstructions(MachineBasicBlock &MBB);
77 };
78 char MLxExpansion::ID = 0;
79}
80
81void MLxExpansion::clearStack() {
82 std::fill(LastMIs, LastMIs + 4, nullptr);
83 MIIdx = 0;
84}
85
86void MLxExpansion::pushStack(MachineInstr *MI) {
87 LastMIs[MIIdx] = MI;
88 if (++MIIdx == 4)
89 MIIdx = 0;
90}
91
92MachineInstr *MLxExpansion::getAccDefMI(MachineInstr *MI) const {
93 // Look past COPY and INSERT_SUBREG instructions to find the
94 // real definition MI. This is important for _sfp instructions.
95 Register Reg = MI->getOperand(1).getReg();
96 if (Reg.isPhysical())
97 return nullptr;
98
99 MachineBasicBlock *MBB = MI->getParent();
100 MachineInstr *DefMI = MRI->getVRegDef(Reg);
101 while (true) {
102 if (DefMI->getParent() != MBB)
103 break;
104 if (DefMI->isCopyLike()) {
105 Reg = DefMI->getOperand(1).getReg();
106 if (Reg.isVirtual()) {
107 DefMI = MRI->getVRegDef(Reg);
108 continue;
109 }
110 } else if (DefMI->isInsertSubreg()) {
111 Reg = DefMI->getOperand(2).getReg();
112 if (Reg.isVirtual()) {
113 DefMI = MRI->getVRegDef(Reg);
114 continue;
115 }
116 }
117 break;
118 }
119 return DefMI;
120}
121
122unsigned MLxExpansion::getDefReg(MachineInstr *MI) const {
123 Register Reg = MI->getOperand(0).getReg();
124 if (Reg.isPhysical() || !MRI->hasOneNonDBGUse(Reg))
125 return Reg;
126
127 MachineBasicBlock *MBB = MI->getParent();
128 MachineInstr *UseMI = &*MRI->use_instr_nodbg_begin(Reg);
129 if (UseMI->getParent() != MBB)
130 return Reg;
131
132 while (UseMI->isCopy() || UseMI->isInsertSubreg()) {
133 Reg = UseMI->getOperand(0).getReg();
134 if (Reg.isPhysical() || !MRI->hasOneNonDBGUse(Reg))
135 return Reg;
137 if (UseMI->getParent() != MBB)
138 return Reg;
139 }
140
141 return Reg;
142}
143
144/// hasLoopHazard - Check whether an MLx instruction is chained to itself across
145/// a single-MBB loop.
146bool MLxExpansion::hasLoopHazard(MachineInstr *MI) const {
147 Register Reg = MI->getOperand(1).getReg();
148 if (Reg.isPhysical())
149 return false;
150
151 MachineBasicBlock *MBB = MI->getParent();
152 MachineInstr *DefMI = MRI->getVRegDef(Reg);
153 while (true) {
154outer_continue:
155 if (DefMI->getParent() != MBB)
156 break;
157
158 if (DefMI->isPHI()) {
159 for (unsigned i = 1, e = DefMI->getNumOperands(); i < e; i += 2) {
160 if (DefMI->getOperand(i + 1).getMBB() == MBB) {
161 Register SrcReg = DefMI->getOperand(i).getReg();
162 if (SrcReg.isVirtual()) {
163 DefMI = MRI->getVRegDef(SrcReg);
164 goto outer_continue;
165 }
166 }
167 }
168 } else if (DefMI->isCopyLike()) {
169 Reg = DefMI->getOperand(1).getReg();
170 if (Reg.isVirtual()) {
171 DefMI = MRI->getVRegDef(Reg);
172 continue;
173 }
174 } else if (DefMI->isInsertSubreg()) {
175 Reg = DefMI->getOperand(2).getReg();
176 if (Reg.isVirtual()) {
177 DefMI = MRI->getVRegDef(Reg);
178 continue;
179 }
180 }
181
182 break;
183 }
184
185 return DefMI == MI;
186}
187
188bool MLxExpansion::hasRAWHazard(unsigned Reg, MachineInstr *MI) const {
189 // FIXME: Detect integer instructions properly.
190 const MCInstrDesc &MCID = MI->getDesc();
191 unsigned Domain = MCID.TSFlags & ARMII::DomainMask;
192 if (MI->mayStore())
193 return false;
194 unsigned Opcode = MCID.getOpcode();
195 if (Opcode == ARM::VMOVRS || Opcode == ARM::VMOVRRD)
196 return false;
198 return MI->readsRegister(Reg, TRI);
199 return false;
200}
201
202static bool isFpMulInstruction(unsigned Opcode) {
203 switch (Opcode) {
204 case ARM::VMULS:
205 case ARM::VMULfd:
206 case ARM::VMULfq:
207 case ARM::VMULD:
208 case ARM::VMULslfd:
209 case ARM::VMULslfq:
210 return true;
211 default:
212 return false;
213 }
214}
215
216bool MLxExpansion::FindMLxHazard(MachineInstr *MI) {
217 if (NumExpand >= ExpandLimit)
218 return false;
219
220 if (ForceExpand)
221 return true;
222
223 MachineInstr *DefMI = getAccDefMI(MI);
224 if (TII->isFpMLxInstruction(DefMI->getOpcode())) {
225 // r0 = vmla
226 // r3 = vmla r0, r1, r2
227 // takes 16 - 17 cycles
228 //
229 // r0 = vmla
230 // r4 = vmul r1, r2
231 // r3 = vadd r0, r4
232 // takes about 14 - 15 cycles even with vmul stalling for 4 cycles.
233 IgnoreStall.insert(DefMI);
234 return true;
235 }
236
237 // On Swift, we mostly care about hazards from multiplication instructions
238 // writing the accumulator and the pipelining of loop iterations by out-of-
239 // order execution.
240 if (isSwift)
241 return isFpMulInstruction(DefMI->getOpcode()) || hasLoopHazard(MI);
242
243 if (IgnoreStall.count(MI))
244 return false;
245
246 // If a VMLA.F is followed by an VADD.F or VMUL.F with no RAW hazard, the
247 // VADD.F or VMUL.F will stall 4 cycles before issue. The 4 cycle stall
248 // preserves the in-order retirement of the instructions.
249 // Look at the next few instructions, if *most* of them can cause hazards,
250 // then the scheduler can't *fix* this, we'd better break up the VMLA.
251 unsigned Limit1 = isLikeA9 ? 1 : 4;
252 unsigned Limit2 = isLikeA9 ? 1 : 4;
253 for (unsigned i = 1; i <= 4; ++i) {
254 int Idx = ((int)MIIdx - i + 4) % 4;
255 MachineInstr *NextMI = LastMIs[Idx];
256 if (!NextMI)
257 continue;
258
259 if (TII->canCauseFpMLxStall(NextMI->getOpcode())) {
260 if (i <= Limit1)
261 return true;
262 }
263
264 // Look for VMLx RAW hazard.
265 if (i <= Limit2 && hasRAWHazard(getDefReg(MI), NextMI))
266 return true;
267 }
268
269 return false;
270}
271
272/// ExpandFPMLxInstructions - Expand a MLA / MLS instruction into a pair
273/// of MUL + ADD / SUB instructions.
274void
275MLxExpansion::ExpandFPMLxInstruction(MachineBasicBlock &MBB, MachineInstr *MI,
276 unsigned MulOpc, unsigned AddSubOpc,
277 bool NegAcc, bool HasLane) {
278 Register DstReg = MI->getOperand(0).getReg();
279 bool DstDead = MI->getOperand(0).isDead();
280 Register AccReg = MI->getOperand(1).getReg();
281 Register Src1Reg = MI->getOperand(2).getReg();
282 Register Src2Reg = MI->getOperand(3).getReg();
283 bool Src1Kill = MI->getOperand(2).isKill();
284 bool Src2Kill = MI->getOperand(3).isKill();
285 unsigned LaneImm = HasLane ? MI->getOperand(4).getImm() : 0;
286 unsigned NextOp = HasLane ? 5 : 4;
287 ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NextOp).getImm();
288 Register PredReg = MI->getOperand(++NextOp).getReg();
289
290 const MCInstrDesc &MCID1 = TII->get(MulOpc);
291 const MCInstrDesc &MCID2 = TII->get(AddSubOpc);
292 Register TmpReg = MRI->createVirtualRegister(TII->getRegClass(MCID1, 0));
293
294 MachineInstrBuilder MIB = BuildMI(MBB, MI, MI->getDebugLoc(), MCID1, TmpReg)
295 .addReg(Src1Reg, getKillRegState(Src1Kill))
296 .addReg(Src2Reg, getKillRegState(Src2Kill));
297 if (HasLane)
298 MIB.addImm(LaneImm);
299 MIB.addImm(Pred).addReg(PredReg);
300
301 MIB = BuildMI(MBB, MI, MI->getDebugLoc(), MCID2)
302 .addReg(DstReg, getDefRegState(true) | getDeadRegState(DstDead));
303
304 if (NegAcc) {
305 bool AccKill = MRI->hasOneNonDBGUse(AccReg);
306 MIB.addReg(TmpReg, getKillRegState(true))
307 .addReg(AccReg, getKillRegState(AccKill));
308 } else {
309 MIB.addReg(AccReg).addReg(TmpReg, getKillRegState(true));
310 }
311 MIB.addImm(Pred).addReg(PredReg);
312
313 LLVM_DEBUG({
314 dbgs() << "Expanding: " << *MI;
315 dbgs() << " to:\n";
317 MII = std::prev(MII);
318 MachineInstr &MI2 = *MII;
319 MII = std::prev(MII);
320 MachineInstr &MI1 = *MII;
321 dbgs() << " " << MI1;
322 dbgs() << " " << MI2;
323 });
324
325 MI->eraseFromParent();
326 ++NumExpand;
327}
328
329bool MLxExpansion::ExpandFPMLxInstructions(MachineBasicBlock &MBB) {
330 bool Changed = false;
331
332 clearStack();
333 IgnoreStall.clear();
334
335 unsigned Skip = 0;
337 while (MII != E) {
338 MachineInstr *MI = &*MII++;
339
340 if (MI->isPosition() || MI->isImplicitDef() || MI->isCopy())
341 continue;
342
343 const MCInstrDesc &MCID = MI->getDesc();
344 if (MI->isBarrier()) {
345 clearStack();
346 Skip = 0;
347 continue;
348 }
349
350 unsigned Domain = MCID.TSFlags & ARMII::DomainMask;
352 if (++Skip == 2)
353 // Assume dual issues of non-VFP / NEON instructions.
354 pushStack(nullptr);
355 } else {
356 Skip = 0;
357
358 unsigned MulOpc, AddSubOpc;
359 bool NegAcc, HasLane;
360 if (!TII->isFpMLxInstruction(MCID.getOpcode(),
361 MulOpc, AddSubOpc, NegAcc, HasLane) ||
362 !FindMLxHazard(MI))
363 pushStack(MI);
364 else {
365 ExpandFPMLxInstruction(MBB, MI, MulOpc, AddSubOpc, NegAcc, HasLane);
366 Changed = true;
367 }
368 }
369 }
370
371 return Changed;
372}
373
374bool MLxExpansion::runOnMachineFunction(MachineFunction &Fn) {
375 if (skipFunction(Fn.getFunction()))
376 return false;
377
378 TII = static_cast<const ARMBaseInstrInfo *>(Fn.getSubtarget().getInstrInfo());
380 MRI = &Fn.getRegInfo();
381 const ARMSubtarget *STI = &Fn.getSubtarget<ARMSubtarget>();
382 if (!STI->expandMLx())
383 return false;
384 isLikeA9 = STI->isLikeA9() || STI->isSwift();
385 isSwift = STI->isSwift();
386
387 bool Modified = false;
388 for (MachineBasicBlock &MBB : Fn)
389 Modified |= ExpandFPMLxInstructions(MBB);
390
391 return Modified;
392}
393
395 return new MLxExpansion();
396}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
static bool hasRAWHazard(MachineInstr *DefMI, MachineInstr *MI, const TargetRegisterInfo &TRI)
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static cl::opt< unsigned > ExpandLimit("expand-limit", cl::init(~0U), cl::Hidden)
static bool isFpMulInstruction(unsigned Opcode)
static cl::opt< bool > ForceExpand("expand-all-fp-mlx", cl::init(false), cl::Hidden)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file defines the SmallPtrSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
bool isSwift() const
bool isLikeA9() const
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:314
unsigned getOpcode() const
Return the opcode number for this descriptor.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
reverse_iterator rbegin()
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.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isCopy() const
const MachineBasicBlock * getParent() const
bool isCopyLike() const
Return true if the instruction behaves like a copy.
unsigned getNumOperands() const
Retuns the total number of operands.
bool isInsertSubreg() const
const MachineOperand & getOperand(unsigned i) const
MachineBasicBlock * getMBB() const
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
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.
constexpr RegState getKillRegState(bool B)
constexpr RegState getDeadRegState(bool B)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr RegState getDefRegState(bool B)
FunctionPass * createMLxExpansionPass()