LLVM 24.0.0git
AArch64CondBrTuning.cpp
Go to the documentation of this file.
1//===-- AArch64CondBrTuning.cpp --- Conditional branch tuning for AArch64 -===//
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/// \file
9/// This file contains a pass that transforms CBZ/CBNZ/TBZ/TBNZ instructions
10/// into a conditional branch (B.cond), when the NZCV flags can be set for
11/// "free". This is preferred on targets that have more flexibility when
12/// scheduling B.cond instructions as compared to CBZ/CBNZ/TBZ/TBNZ (assuming
13/// all other variables are equal). This can also reduce register pressure.
14///
15/// A few examples:
16///
17/// 1) add w8, w0, w1 -> cmn w0, w1 ; CMN is an alias of ADDS.
18/// cbz w8, .LBB_2 -> b.eq .LBB0_2
19///
20/// 2) add w8, w0, w1 -> adds w8, w0, w1 ; w8 has multiple uses.
21/// cbz w8, .LBB1_2 -> b.eq .LBB1_2
22///
23/// 3) sub w8, w0, w1 -> subs w8, w0, w1 ; w8 has multiple uses.
24/// tbz w8, #31, .LBB6_2 -> b.pl .LBB6_2
25///
26//===----------------------------------------------------------------------===//
27
28#include "AArch64.h"
29#include "AArch64Subtarget.h"
34#include "llvm/CodeGen/Passes.h"
39#include "llvm/Support/Debug.h"
41
42using namespace llvm;
43
44#define DEBUG_TYPE "aarch64-cond-br-tuning"
45#define AARCH64_CONDBR_TUNING_NAME "AArch64 Conditional Branch Tuning"
46
47namespace {
48class AArch64CondBrTuning : public MachineFunctionPass {
49 const AArch64InstrInfo *TII;
51
53
54public:
55 static char ID;
56 AArch64CondBrTuning() : MachineFunctionPass(ID) {}
57 void getAnalysisUsage(AnalysisUsage &AU) const override;
58 bool runOnMachineFunction(MachineFunction &MF) override;
59 StringRef getPassName() const override { return AARCH64_CONDBR_TUNING_NAME; }
60
61private:
62 MachineInstr *getOperandDef(const MachineOperand &MO);
63 MachineInstr *convertToFlagSetting(MachineInstr &MI, bool IsFlagSetting,
64 bool Is64Bit);
65 MachineInstr *convertToCondBr(MachineInstr &MI);
66 bool tryToTuneBranch(MachineInstr &MI, MachineInstr &DefMI);
67};
68} // end anonymous namespace
69
70char AArch64CondBrTuning::ID = 0;
71
72INITIALIZE_PASS(AArch64CondBrTuning, "aarch64-cond-br-tuning",
73 AARCH64_CONDBR_TUNING_NAME, false, false)
74
75void AArch64CondBrTuning::getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.setPreservesCFG();
77 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
79}
80
81MachineInstr *AArch64CondBrTuning::getOperandDef(const MachineOperand &MO) {
82 if (!MO.getReg().isVirtual())
83 return nullptr;
84 return MRI->getUniqueVRegDef(MO.getReg());
85}
86
87MachineInstr *AArch64CondBrTuning::convertToFlagSetting(MachineInstr &MI,
88 bool IsFlagSetting,
89 bool Is64Bit) {
90 // If this is already the flag setting version of the instruction (e.g., SUBS)
91 // just make sure the implicit-def of NZCV isn't marked dead.
92 if (IsFlagSetting) {
93 for (MachineOperand &MO : MI.implicit_operands())
94 if (MO.isReg() && MO.isDead() && MO.getReg() == AArch64::NZCV)
95 MO.setIsDead(false);
96 return &MI;
97 }
98 unsigned NewOpc = TII->convertToFlagSettingOpc(MI.getOpcode());
99 Register NewDestReg = MI.getOperand(0).getReg();
100 if (MRI->hasOneNonDBGUse(MI.getOperand(0).getReg()))
101 NewDestReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
102
103 MachineInstrBuilder MIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
104 TII->get(NewOpc), NewDestReg);
105
106 // If the MI has a debug instruction number, preserve that in the new Machine
107 // Instruction that is created.
108 if (MI.peekDebugInstrNum() != 0)
109 MIB->setDebugInstrNum(MI.peekDebugInstrNum());
110
111 for (const MachineOperand &MO : llvm::drop_begin(MI.operands()))
112 MIB.add(MO);
113
114 return MIB;
115}
116
117MachineInstr *AArch64CondBrTuning::convertToCondBr(MachineInstr &MI) {
119 MachineBasicBlock *TargetMBB = TII->getBranchDestBlock(MI);
120 switch (MI.getOpcode()) {
121 default:
122 llvm_unreachable("Unexpected opcode!");
123
124 case AArch64::CBZW:
125 case AArch64::CBZX:
126 CC = AArch64CC::EQ;
127 break;
128 case AArch64::CBNZW:
129 case AArch64::CBNZX:
130 CC = AArch64CC::NE;
131 break;
132 case AArch64::TBZW:
133 case AArch64::TBZX:
134 CC = AArch64CC::PL;
135 break;
136 case AArch64::TBNZW:
137 case AArch64::TBNZX:
138 CC = AArch64CC::MI;
139 break;
140 }
141 return BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(AArch64::Bcc))
142 .addImm(CC)
143 .addMBB(TargetMBB);
144}
145
146bool AArch64CondBrTuning::tryToTuneBranch(MachineInstr &MI,
147 MachineInstr &DefMI) {
148 // We don't want NZCV bits live across blocks.
149 if (MI.getParent() != DefMI.getParent())
150 return false;
151
152 bool IsFlagSetting = true;
153 unsigned MIOpc = MI.getOpcode();
154 MachineInstr *NewCmp = nullptr, *NewBr = nullptr;
155 switch (DefMI.getOpcode()) {
156 default:
157 return false;
158 case AArch64::ADDWri:
159 case AArch64::ADDWrr:
160 case AArch64::ADDWrs:
161 case AArch64::ADDWrx:
162 case AArch64::ANDWri:
163 case AArch64::ANDWrr:
164 case AArch64::ANDWrs:
165 case AArch64::BICWrr:
166 case AArch64::BICWrs:
167 case AArch64::SUBWri:
168 case AArch64::SUBWrr:
169 case AArch64::SUBWrs:
170 case AArch64::SUBWrx:
171 IsFlagSetting = false;
172 [[fallthrough]];
173 case AArch64::ADDSWri:
174 case AArch64::ADDSWrr:
175 case AArch64::ADDSWrs:
176 case AArch64::ADDSWrx:
177 case AArch64::ANDSWri:
178 case AArch64::ANDSWrr:
179 case AArch64::ANDSWrs:
180 case AArch64::BICSWrr:
181 case AArch64::BICSWrs:
182 case AArch64::SUBSWri:
183 case AArch64::SUBSWrr:
184 case AArch64::SUBSWrs:
185 case AArch64::SUBSWrx:
186 switch (MIOpc) {
187 default:
188 llvm_unreachable("Unexpected opcode!");
189
190 case AArch64::CBZW:
191 case AArch64::CBNZW:
192 case AArch64::TBZW:
193 case AArch64::TBNZW:
194 // Check to see if the TBZ/TBNZ is checking the sign bit.
195 if ((MIOpc == AArch64::TBZW || MIOpc == AArch64::TBNZW) &&
196 MI.getOperand(1).getImm() != 31)
197 return false;
198
199 // There must not be any instruction between DefMI and MI that clobbers or
200 // reads NZCV.
202 return false;
203 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
204 LLVM_DEBUG(DefMI.print(dbgs()));
205 LLVM_DEBUG(dbgs() << " ");
207
208 NewCmp = convertToFlagSetting(DefMI, IsFlagSetting, /*Is64Bit=*/false);
209 NewBr = convertToCondBr(MI);
210 break;
211 }
212 break;
213
214 case AArch64::ADDXri:
215 case AArch64::ADDXrr:
216 case AArch64::ADDXrs:
217 case AArch64::ADDXrx:
218 case AArch64::ANDXri:
219 case AArch64::ANDXrr:
220 case AArch64::ANDXrs:
221 case AArch64::BICXrr:
222 case AArch64::BICXrs:
223 case AArch64::SUBXri:
224 case AArch64::SUBXrr:
225 case AArch64::SUBXrs:
226 case AArch64::SUBXrx:
227 IsFlagSetting = false;
228 [[fallthrough]];
229 case AArch64::ADDSXri:
230 case AArch64::ADDSXrr:
231 case AArch64::ADDSXrs:
232 case AArch64::ADDSXrx:
233 case AArch64::ANDSXri:
234 case AArch64::ANDSXrr:
235 case AArch64::ANDSXrs:
236 case AArch64::BICSXrr:
237 case AArch64::BICSXrs:
238 case AArch64::SUBSXri:
239 case AArch64::SUBSXrr:
240 case AArch64::SUBSXrs:
241 case AArch64::SUBSXrx:
242 switch (MIOpc) {
243 default:
244 llvm_unreachable("Unexpected opcode!");
245
246 case AArch64::CBZX:
247 case AArch64::CBNZX:
248 case AArch64::TBZX:
249 case AArch64::TBNZX: {
250 // Check to see if the TBZ/TBNZ is checking the sign bit.
251 if ((MIOpc == AArch64::TBZX || MIOpc == AArch64::TBNZX) &&
252 MI.getOperand(1).getImm() != 63)
253 return false;
254 // There must not be any instruction between DefMI and MI that clobbers or
255 // reads NZCV.
257 return false;
258 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
259 LLVM_DEBUG(DefMI.print(dbgs()));
260 LLVM_DEBUG(dbgs() << " ");
262
263 NewCmp = convertToFlagSetting(DefMI, IsFlagSetting, /*Is64Bit=*/true);
264 NewBr = convertToCondBr(MI);
265 break;
266 }
267 }
268 break;
269 }
270 (void)NewCmp; (void)NewBr;
271 assert(NewCmp && NewBr && "Expected new instructions.");
272
273 LLVM_DEBUG(dbgs() << " with instruction:\n ");
274 LLVM_DEBUG(NewCmp->print(dbgs()));
275 LLVM_DEBUG(dbgs() << " ");
276 LLVM_DEBUG(NewBr->print(dbgs()));
277
278 // If this was a flag setting version of the instruction, we use the original
279 // instruction by just clearing the dead marked on the implicit-def of NCZV.
280 // Therefore, we should not erase this instruction.
281 if (!IsFlagSetting)
282 DefMI.eraseFromParent();
283 MI.eraseFromParent();
284 return true;
285}
286
287bool AArch64CondBrTuning::runOnMachineFunction(MachineFunction &MF) {
288 if (skipFunction(MF.getFunction()))
289 return false;
290
292 dbgs() << "********** AArch64 Conditional Branch Tuning **********\n"
293 << "********** Function: " << MF.getName() << '\n');
294
295 TII = static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
297 MRI = &MF.getRegInfo();
298
299 bool Changed = false;
300 for (MachineBasicBlock &MBB : MF) {
301 bool LocalChange = false;
302 for (MachineInstr &MI : MBB.terminators()) {
303 switch (MI.getOpcode()) {
304 default:
305 break;
306 case AArch64::CBZW:
307 case AArch64::CBZX:
308 case AArch64::CBNZW:
309 case AArch64::CBNZX:
310 case AArch64::TBZW:
311 case AArch64::TBZX:
312 case AArch64::TBNZW:
313 case AArch64::TBNZX:
314 MachineInstr *DefMI = getOperandDef(MI.getOperand(0));
315 LocalChange = (DefMI && tryToTuneBranch(MI, *DefMI));
316 break;
317 }
318 // If the optimization was successful, we can't optimize any other
319 // branches because doing so would clobber the NZCV flags.
320 if (LocalChange) {
321 Changed = true;
322 break;
323 }
324 }
325 }
326 return Changed;
327}
328
330 return new AArch64CondBrTuning();
331}
#define AARCH64_CONDBR_TUNING_NAME
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
iterator_range< iterator > terminators()
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.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
void setDebugInstrNum(unsigned Num)
Set instruction number of this MachineInstr.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsDead(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
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 * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition Pass.cpp:140
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
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.
Changed
#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.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionPass * createAArch64CondBrTuning()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isNZCVTouchedInInstructionRange(const MachineInstr &DefMI, const MachineInstr &UseMI, const TargetRegisterInfo *TRI)
Return true if there is an instruction /after/ DefMI and before UseMI which either reads or clobbers ...