1 //=- AArch64ConditionOptimizer.cpp - Remove useless comparisons for AArch64 -=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass tries to make consecutive compares of values use same operands to
11 // allow CSE pass to remove duplicated instructions. For this it analyzes
12 // branches and adjusts comparisons with immediate values by converting:
17 // and adjusting immediate values appropriately. It basically corrects two
18 // immediate values towards each other to make them equal.
20 // Consider the following example in C:
22 // if ((a < 5 && ...) || (a > 5 && ...)) {
27 // Here both "x" and "y" expressions compare "a" with "5". When "x" evaluates
28 // to "false", "y" can just check flags set by the first comparison. As a
29 // result of the canonicalization employed by
30 // SelectionDAGBuilder::visitSwitchCase, DAGCombine, and other target-specific
31 // code, assembly ends up in the form that is not CSE friendly:
42 // Same assembly after the pass:
49 // cmp w8, #5 // <-- CSE pass removes this instruction
53 // Currently only SUBS and ADDS followed by b.?? are supported.
55 // TODO: maybe handle TBNZ/TBZ the same way as CMP when used instead for "a < 0"
56 // TODO: handle other conditional instructions (e.g. CSET)
57 // TODO: allow second branching to be anything if it doesn't require adjusting
59 //===----------------------------------------------------------------------===//
62 #include "llvm/ADT/DepthFirstIterator.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/ADT/Statistic.h"
65 #include "llvm/CodeGen/MachineDominators.h"
66 #include "llvm/CodeGen/MachineFunction.h"
67 #include "llvm/CodeGen/MachineFunctionPass.h"
68 #include "llvm/CodeGen/MachineInstrBuilder.h"
69 #include "llvm/CodeGen/Passes.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include "llvm/Target/TargetInstrInfo.h"
74 #include "llvm/Target/TargetSubtargetInfo.h"
80 #define DEBUG_TYPE "aarch64-condopt"
82 STATISTIC(NumConditionsAdjusted, "Number of conditions adjusted");
85 class AArch64ConditionOptimizer : public MachineFunctionPass {
86 const TargetInstrInfo *TII;
87 MachineDominatorTree *DomTree;
90 // Stores immediate, compare instruction opcode and branch condition (in this
91 // order) of adjusted comparison.
92 typedef std::tuple<int, int, AArch64CC::CondCode> CmpInfo;
95 AArch64ConditionOptimizer() : MachineFunctionPass(ID) {}
96 void getAnalysisUsage(AnalysisUsage &AU) const override;
97 MachineInstr *findSuitableCompare(MachineBasicBlock *MBB);
98 CmpInfo adjustCmp(MachineInstr *CmpMI, AArch64CC::CondCode Cmp);
99 void modifyCmp(MachineInstr *CmpMI, const CmpInfo &Info);
100 bool adjustTo(MachineInstr *CmpMI, AArch64CC::CondCode Cmp, MachineInstr *To,
102 bool runOnMachineFunction(MachineFunction &MF) override;
103 const char *getPassName() const override {
104 return "AArch64 Condition Optimizer";
107 } // end anonymous namespace
109 char AArch64ConditionOptimizer::ID = 0;
112 void initializeAArch64ConditionOptimizerPass(PassRegistry &);
115 INITIALIZE_PASS_BEGIN(AArch64ConditionOptimizer, "aarch64-condopt",
116 "AArch64 CondOpt Pass", false, false)
117 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
118 INITIALIZE_PASS_END(AArch64ConditionOptimizer, "aarch64-condopt",
119 "AArch64 CondOpt Pass", false, false)
121 FunctionPass *llvm::createAArch64ConditionOptimizerPass() {
122 return new AArch64ConditionOptimizer();
125 void AArch64ConditionOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
126 AU.addRequired<MachineDominatorTree>();
127 AU.addPreserved<MachineDominatorTree>();
128 MachineFunctionPass::getAnalysisUsage(AU);
131 // Finds compare instruction that corresponds to supported types of branching.
132 // Returns the instruction or nullptr on failures or detecting unsupported
134 MachineInstr *AArch64ConditionOptimizer::findSuitableCompare(
135 MachineBasicBlock *MBB) {
136 MachineBasicBlock::iterator I = MBB->getFirstTerminator();
137 if (I == MBB->end()) {
141 if (I->getOpcode() != AArch64::Bcc) {
145 // Now find the instruction controlling the terminator.
146 for (MachineBasicBlock::iterator B = MBB->begin(); I != B;) {
148 assert(!I->isTerminator() && "Spurious terminator");
149 switch (I->getOpcode()) {
150 // cmp is an alias for subs with a dead destination register.
151 case AArch64::SUBSWri:
152 case AArch64::SUBSXri:
153 // cmn is an alias for adds with a dead destination register.
154 case AArch64::ADDSWri:
155 case AArch64::ADDSXri:
158 case AArch64::SUBSWrr:
159 case AArch64::SUBSXrr:
160 case AArch64::ADDSWrr:
161 case AArch64::ADDSXrr:
162 case AArch64::FCMPSrr:
163 case AArch64::FCMPDrr:
164 case AArch64::FCMPESrr:
165 case AArch64::FCMPEDrr:
166 // Skip comparison instructions without immediate operands.
170 DEBUG(dbgs() << "Flags not defined in BB#" << MBB->getNumber() << '\n');
174 // Changes opcode adds <-> subs considering register operand width.
175 static int getComplementOpc(int Opc) {
177 case AArch64::ADDSWri: return AArch64::SUBSWri;
178 case AArch64::ADDSXri: return AArch64::SUBSXri;
179 case AArch64::SUBSWri: return AArch64::ADDSWri;
180 case AArch64::SUBSXri: return AArch64::ADDSXri;
182 llvm_unreachable("Unexpected opcode");
186 // Changes form of comparison inclusive <-> exclusive.
187 static AArch64CC::CondCode getAdjustedCmp(AArch64CC::CondCode Cmp) {
189 case AArch64CC::GT: return AArch64CC::GE;
190 case AArch64CC::GE: return AArch64CC::GT;
191 case AArch64CC::LT: return AArch64CC::LE;
192 case AArch64CC::LE: return AArch64CC::LT;
194 llvm_unreachable("Unexpected condition code");
198 // Transforms GT -> GE, GE -> GT, LT -> LE, LE -> LT by updating comparison
199 // operator and condition code.
200 AArch64ConditionOptimizer::CmpInfo AArch64ConditionOptimizer::adjustCmp(
201 MachineInstr *CmpMI, AArch64CC::CondCode Cmp) {
202 int Opc = CmpMI->getOpcode();
204 // CMN (compare with negative immediate) is an alias to ADDS (as
205 // "operand - negative" == "operand + positive")
206 bool Negative = (Opc == AArch64::ADDSWri || Opc == AArch64::ADDSXri);
208 int Correction = (Cmp == AArch64CC::GT) ? 1 : -1;
209 // Negate Correction value for comparison with negative immediate (CMN).
211 Correction = -Correction;
214 const int OldImm = (int)CmpMI->getOperand(2).getImm();
215 const int NewImm = std::abs(OldImm + Correction);
217 // Handle +0 -> -1 and -0 -> +1 (CMN with 0 immediate) transitions by
218 // adjusting compare instruction opcode.
219 if (OldImm == 0 && ((Negative && Correction == 1) ||
220 (!Negative && Correction == -1))) {
221 Opc = getComplementOpc(Opc);
224 return CmpInfo(NewImm, Opc, getAdjustedCmp(Cmp));
227 // Applies changes to comparison instruction suggested by adjustCmp().
228 void AArch64ConditionOptimizer::modifyCmp(MachineInstr *CmpMI,
229 const CmpInfo &Info) {
232 AArch64CC::CondCode Cmp;
233 std::tie(Imm, Opc, Cmp) = Info;
235 MachineBasicBlock *const MBB = CmpMI->getParent();
237 // Change immediate in comparison instruction (ADDS or SUBS).
238 BuildMI(*MBB, CmpMI, CmpMI->getDebugLoc(), TII->get(Opc))
239 .addOperand(CmpMI->getOperand(0))
240 .addOperand(CmpMI->getOperand(1))
242 .addOperand(CmpMI->getOperand(3));
243 CmpMI->eraseFromParent();
245 // The fact that this comparison was picked ensures that it's related to the
246 // first terminator instruction.
247 MachineInstr *BrMI = MBB->getFirstTerminator();
249 // Change condition in branch instruction.
250 BuildMI(*MBB, BrMI, BrMI->getDebugLoc(), TII->get(AArch64::Bcc))
252 .addOperand(BrMI->getOperand(1));
253 BrMI->eraseFromParent();
255 MBB->updateTerminator();
257 ++NumConditionsAdjusted;
260 // Parse a condition code returned by AnalyzeBranch, and compute the CondCode
261 // corresponding to TBB.
262 // Returns true if parsing was successful, otherwise false is returned.
263 static bool parseCond(ArrayRef<MachineOperand> Cond, AArch64CC::CondCode &CC) {
264 // A normal br.cond simply has the condition code.
265 if (Cond[0].getImm() != -1) {
266 assert(Cond.size() == 1 && "Unknown Cond array format");
267 CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
273 // Adjusts one cmp instruction to another one if result of adjustment will allow
274 // CSE. Returns true if compare instruction was changed, otherwise false is
276 bool AArch64ConditionOptimizer::adjustTo(MachineInstr *CmpMI,
277 AArch64CC::CondCode Cmp, MachineInstr *To, int ToImm)
279 CmpInfo Info = adjustCmp(CmpMI, Cmp);
280 if (std::get<0>(Info) == ToImm && std::get<1>(Info) == To->getOpcode()) {
281 modifyCmp(CmpMI, Info);
287 bool AArch64ConditionOptimizer::runOnMachineFunction(MachineFunction &MF) {
288 DEBUG(dbgs() << "********** AArch64 Conditional Compares **********\n"
289 << "********** Function: " << MF.getName() << '\n');
290 TII = MF.getTarget().getSubtargetImpl()->getInstrInfo();
291 DomTree = &getAnalysis<MachineDominatorTree>();
293 bool Changed = false;
295 // Visit blocks in dominator tree pre-order. The pre-order enables multiple
296 // cmp-conversions from the same head block.
297 // Note that updateDomTree() modifies the children of the DomTree node
298 // currently being visited. The df_iterator supports that; it doesn't look at
299 // child_begin() / child_end() until after a node has been visited.
300 for (MachineDomTreeNode *I : depth_first(DomTree)) {
301 MachineBasicBlock *HBB = I->getBlock();
303 SmallVector<MachineOperand, 4> HeadCond;
304 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
305 if (TII->AnalyzeBranch(*HBB, TBB, FBB, HeadCond)) {
309 // Equivalence check is to skip loops.
310 if (!TBB || TBB == HBB) {
314 SmallVector<MachineOperand, 4> TrueCond;
315 MachineBasicBlock *TBB_TBB = nullptr, *TBB_FBB = nullptr;
316 if (TII->AnalyzeBranch(*TBB, TBB_TBB, TBB_FBB, TrueCond)) {
320 MachineInstr *HeadCmpMI = findSuitableCompare(HBB);
325 MachineInstr *TrueCmpMI = findSuitableCompare(TBB);
330 AArch64CC::CondCode HeadCmp;
331 if (HeadCond.empty() || !parseCond(HeadCond, HeadCmp)) {
335 AArch64CC::CondCode TrueCmp;
336 if (TrueCond.empty() || !parseCond(TrueCond, TrueCmp)) {
340 const int HeadImm = (int)HeadCmpMI->getOperand(2).getImm();
341 const int TrueImm = (int)TrueCmpMI->getOperand(2).getImm();
343 DEBUG(dbgs() << "Head branch:\n");
344 DEBUG(dbgs() << "\tcondition: "
345 << AArch64CC::getCondCodeName(HeadCmp) << '\n');
346 DEBUG(dbgs() << "\timmediate: " << HeadImm << '\n');
348 DEBUG(dbgs() << "True branch:\n");
349 DEBUG(dbgs() << "\tcondition: "
350 << AArch64CC::getCondCodeName(TrueCmp) << '\n');
351 DEBUG(dbgs() << "\timmediate: " << TrueImm << '\n');
353 if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::LT) ||
354 (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::GT)) &&
355 std::abs(TrueImm - HeadImm) == 2) {
356 // This branch transforms machine instructions that correspond to
358 // 1) (a > {TrueImm} && ...) || (a < {HeadImm} && ...)
359 // 2) (a < {TrueImm} && ...) || (a > {HeadImm} && ...)
363 // 1) (a >= {NewImm} && ...) || (a <= {NewImm} && ...)
364 // 2) (a <= {NewImm} && ...) || (a >= {NewImm} && ...)
366 CmpInfo HeadCmpInfo = adjustCmp(HeadCmpMI, HeadCmp);
367 CmpInfo TrueCmpInfo = adjustCmp(TrueCmpMI, TrueCmp);
368 if (std::get<0>(HeadCmpInfo) == std::get<0>(TrueCmpInfo) &&
369 std::get<1>(HeadCmpInfo) == std::get<1>(TrueCmpInfo)) {
370 modifyCmp(HeadCmpMI, HeadCmpInfo);
371 modifyCmp(TrueCmpMI, TrueCmpInfo);
374 } else if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::GT) ||
375 (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::LT)) &&
376 std::abs(TrueImm - HeadImm) == 1) {
377 // This branch transforms machine instructions that correspond to
379 // 1) (a > {TrueImm} && ...) || (a > {HeadImm} && ...)
380 // 2) (a < {TrueImm} && ...) || (a < {HeadImm} && ...)
384 // 1) (a <= {NewImm} && ...) || (a > {NewImm} && ...)
385 // 2) (a < {NewImm} && ...) || (a >= {NewImm} && ...)
387 // GT -> GE transformation increases immediate value, so picking the
388 // smaller one; LT -> LE decreases immediate value so invert the choice.
389 bool adjustHeadCond = (HeadImm < TrueImm);
390 if (HeadCmp == AArch64CC::LT) {
391 adjustHeadCond = !adjustHeadCond;
394 if (adjustHeadCond) {
395 Changed |= adjustTo(HeadCmpMI, HeadCmp, TrueCmpMI, TrueImm);
397 Changed |= adjustTo(TrueCmpMI, TrueCmp, HeadCmpMI, HeadImm);
400 // Other transformation cases almost never occur due to generation of < or >
401 // comparisons instead of <= and >=.