LLVM  3.7.0
AArch64ConditionOptimizer.cpp
Go to the documentation of this file.
1 //=- AArch64ConditionOptimizer.cpp - Remove useless comparisons for AArch64 -=//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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:
13 // * GE -> GT
14 // * GT -> GE
15 // * LT -> LE
16 // * LE -> LT
17 // and adjusting immediate values appropriately. It basically corrects two
18 // immediate values towards each other to make them equal.
19 //
20 // Consider the following example in C:
21 //
22 // if ((a < 5 && ...) || (a > 5 && ...)) {
23 // ~~~~~ ~~~~~
24 // ^ ^
25 // x y
26 //
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:
32 //
33 // ...
34 // cmp w8, #4
35 // b.gt .LBB0_3
36 // ...
37 // .LBB0_3:
38 // cmp w8, #6
39 // b.lt .LBB0_6
40 // ...
41 //
42 // Same assembly after the pass:
43 //
44 // ...
45 // cmp w8, #5
46 // b.ge .LBB0_3
47 // ...
48 // .LBB0_3:
49 // cmp w8, #5 // <-- CSE pass removes this instruction
50 // b.le .LBB0_6
51 // ...
52 //
53 // Currently only SUBS and ADDS followed by b.?? are supported.
54 //
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
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "AArch64.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/ADT/Statistic.h"
71 #include "llvm/CodeGen/Passes.h"
73 #include "llvm/Support/Debug.h"
77 #include <cstdlib>
78 #include <tuple>
79 
80 using namespace llvm;
81 
82 #define DEBUG_TYPE "aarch64-condopt"
83 
84 STATISTIC(NumConditionsAdjusted, "Number of conditions adjusted");
85 
86 namespace {
87 class AArch64ConditionOptimizer : public MachineFunctionPass {
88  const TargetInstrInfo *TII;
89  MachineDominatorTree *DomTree;
90  const MachineRegisterInfo *MRI;
91 
92 public:
93  // Stores immediate, compare instruction opcode and branch condition (in this
94  // order) of adjusted comparison.
95  typedef std::tuple<int, unsigned, AArch64CC::CondCode> CmpInfo;
96 
97  static char ID;
98  AArch64ConditionOptimizer() : MachineFunctionPass(ID) {}
99  void getAnalysisUsage(AnalysisUsage &AU) const override;
100  MachineInstr *findSuitableCompare(MachineBasicBlock *MBB);
101  CmpInfo adjustCmp(MachineInstr *CmpMI, AArch64CC::CondCode Cmp);
102  void modifyCmp(MachineInstr *CmpMI, const CmpInfo &Info);
103  bool adjustTo(MachineInstr *CmpMI, AArch64CC::CondCode Cmp, MachineInstr *To,
104  int ToImm);
105  bool runOnMachineFunction(MachineFunction &MF) override;
106  const char *getPassName() const override {
107  return "AArch64 Condition Optimizer";
108  }
109 };
110 } // end anonymous namespace
111 
113 
114 namespace llvm {
116 }
117 
118 INITIALIZE_PASS_BEGIN(AArch64ConditionOptimizer, "aarch64-condopt",
119  "AArch64 CondOpt Pass", false, false)
121 INITIALIZE_PASS_END(AArch64ConditionOptimizer, "aarch64-condopt",
122  "AArch64 CondOpt Pass", false, false)
123 
125  return new AArch64ConditionOptimizer();
126 }
127 
128 void AArch64ConditionOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
132 }
133 
134 // Finds compare instruction that corresponds to supported types of branching.
135 // Returns the instruction or nullptr on failures or detecting unsupported
136 // instructions.
137 MachineInstr *AArch64ConditionOptimizer::findSuitableCompare(
138  MachineBasicBlock *MBB) {
140  if (I == MBB->end())
141  return nullptr;
142 
143  if (I->getOpcode() != AArch64::Bcc)
144  return nullptr;
145 
146  // Now find the instruction controlling the terminator.
147  for (MachineBasicBlock::iterator B = MBB->begin(); I != B;) {
148  --I;
149  assert(!I->isTerminator() && "Spurious terminator");
150  switch (I->getOpcode()) {
151  // cmp is an alias for subs with a dead destination register.
152  case AArch64::SUBSWri:
153  case AArch64::SUBSXri:
154  // cmn is an alias for adds with a dead destination register.
155  case AArch64::ADDSWri:
156  case AArch64::ADDSXri:
157  if (MRI->use_empty(I->getOperand(0).getReg()))
158  return I;
159 
160  DEBUG(dbgs() << "Destination of cmp is not dead, " << *I << '\n');
161  return nullptr;
162 
163  // Prevent false positive case like:
164  // cmp w19, #0
165  // cinc w0, w19, gt
166  // ...
167  // fcmp d8, #0.0
168  // b.gt .LBB0_5
169  case AArch64::FCMPDri:
170  case AArch64::FCMPSri:
171  case AArch64::FCMPESri:
172  case AArch64::FCMPEDri:
173 
174  case AArch64::SUBSWrr:
175  case AArch64::SUBSXrr:
176  case AArch64::ADDSWrr:
177  case AArch64::ADDSXrr:
178  case AArch64::FCMPSrr:
179  case AArch64::FCMPDrr:
180  case AArch64::FCMPESrr:
181  case AArch64::FCMPEDrr:
182  // Skip comparison instructions without immediate operands.
183  return nullptr;
184  }
185  }
186  DEBUG(dbgs() << "Flags not defined in BB#" << MBB->getNumber() << '\n');
187  return nullptr;
188 }
189 
190 // Changes opcode adds <-> subs considering register operand width.
191 static int getComplementOpc(int Opc) {
192  switch (Opc) {
193  case AArch64::ADDSWri: return AArch64::SUBSWri;
194  case AArch64::ADDSXri: return AArch64::SUBSXri;
195  case AArch64::SUBSWri: return AArch64::ADDSWri;
196  case AArch64::SUBSXri: return AArch64::ADDSXri;
197  default:
198  llvm_unreachable("Unexpected opcode");
199  }
200 }
201 
202 // Changes form of comparison inclusive <-> exclusive.
204  switch (Cmp) {
205  case AArch64CC::GT: return AArch64CC::GE;
206  case AArch64CC::GE: return AArch64CC::GT;
207  case AArch64CC::LT: return AArch64CC::LE;
208  case AArch64CC::LE: return AArch64CC::LT;
209  default:
210  llvm_unreachable("Unexpected condition code");
211  }
212 }
213 
214 // Transforms GT -> GE, GE -> GT, LT -> LE, LE -> LT by updating comparison
215 // operator and condition code.
216 AArch64ConditionOptimizer::CmpInfo AArch64ConditionOptimizer::adjustCmp(
217  MachineInstr *CmpMI, AArch64CC::CondCode Cmp) {
218  unsigned Opc = CmpMI->getOpcode();
219 
220  // CMN (compare with negative immediate) is an alias to ADDS (as
221  // "operand - negative" == "operand + positive")
222  bool Negative = (Opc == AArch64::ADDSWri || Opc == AArch64::ADDSXri);
223 
224  int Correction = (Cmp == AArch64CC::GT) ? 1 : -1;
225  // Negate Correction value for comparison with negative immediate (CMN).
226  if (Negative) {
227  Correction = -Correction;
228  }
229 
230  const int OldImm = (int)CmpMI->getOperand(2).getImm();
231  const int NewImm = std::abs(OldImm + Correction);
232 
233  // Handle +0 -> -1 and -0 -> +1 (CMN with 0 immediate) transitions by
234  // adjusting compare instruction opcode.
235  if (OldImm == 0 && ((Negative && Correction == 1) ||
236  (!Negative && Correction == -1))) {
237  Opc = getComplementOpc(Opc);
238  }
239 
240  return CmpInfo(NewImm, Opc, getAdjustedCmp(Cmp));
241 }
242 
243 // Applies changes to comparison instruction suggested by adjustCmp().
244 void AArch64ConditionOptimizer::modifyCmp(MachineInstr *CmpMI,
245  const CmpInfo &Info) {
246  int Imm;
247  unsigned Opc;
249  std::tie(Imm, Opc, Cmp) = Info;
250 
251  MachineBasicBlock *const MBB = CmpMI->getParent();
252 
253  // Change immediate in comparison instruction (ADDS or SUBS).
254  BuildMI(*MBB, CmpMI, CmpMI->getDebugLoc(), TII->get(Opc))
255  .addOperand(CmpMI->getOperand(0))
256  .addOperand(CmpMI->getOperand(1))
257  .addImm(Imm)
258  .addOperand(CmpMI->getOperand(3));
259  CmpMI->eraseFromParent();
260 
261  // The fact that this comparison was picked ensures that it's related to the
262  // first terminator instruction.
263  MachineInstr *BrMI = MBB->getFirstTerminator();
264 
265  // Change condition in branch instruction.
266  BuildMI(*MBB, BrMI, BrMI->getDebugLoc(), TII->get(AArch64::Bcc))
267  .addImm(Cmp)
268  .addOperand(BrMI->getOperand(1));
269  BrMI->eraseFromParent();
270 
271  MBB->updateTerminator();
272 
273  ++NumConditionsAdjusted;
274 }
275 
276 // Parse a condition code returned by AnalyzeBranch, and compute the CondCode
277 // corresponding to TBB.
278 // Returns true if parsing was successful, otherwise false is returned.
280  // A normal br.cond simply has the condition code.
281  if (Cond[0].getImm() != -1) {
282  assert(Cond.size() == 1 && "Unknown Cond array format");
283  CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
284  return true;
285  }
286  return false;
287 }
288 
289 // Adjusts one cmp instruction to another one if result of adjustment will allow
290 // CSE. Returns true if compare instruction was changed, otherwise false is
291 // returned.
292 bool AArch64ConditionOptimizer::adjustTo(MachineInstr *CmpMI,
293  AArch64CC::CondCode Cmp, MachineInstr *To, int ToImm)
294 {
295  CmpInfo Info = adjustCmp(CmpMI, Cmp);
296  if (std::get<0>(Info) == ToImm && std::get<1>(Info) == To->getOpcode()) {
297  modifyCmp(CmpMI, Info);
298  return true;
299  }
300  return false;
301 }
302 
303 bool AArch64ConditionOptimizer::runOnMachineFunction(MachineFunction &MF) {
304  DEBUG(dbgs() << "********** AArch64 Conditional Compares **********\n"
305  << "********** Function: " << MF.getName() << '\n');
306  TII = MF.getSubtarget().getInstrInfo();
307  DomTree = &getAnalysis<MachineDominatorTree>();
308  MRI = &MF.getRegInfo();
309 
310  bool Changed = false;
311 
312  // Visit blocks in dominator tree pre-order. The pre-order enables multiple
313  // cmp-conversions from the same head block.
314  // Note that updateDomTree() modifies the children of the DomTree node
315  // currently being visited. The df_iterator supports that; it doesn't look at
316  // child_begin() / child_end() until after a node has been visited.
317  for (MachineDomTreeNode *I : depth_first(DomTree)) {
318  MachineBasicBlock *HBB = I->getBlock();
319 
321  MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
322  if (TII->AnalyzeBranch(*HBB, TBB, FBB, HeadCond)) {
323  continue;
324  }
325 
326  // Equivalence check is to skip loops.
327  if (!TBB || TBB == HBB) {
328  continue;
329  }
330 
332  MachineBasicBlock *TBB_TBB = nullptr, *TBB_FBB = nullptr;
333  if (TII->AnalyzeBranch(*TBB, TBB_TBB, TBB_FBB, TrueCond)) {
334  continue;
335  }
336 
337  MachineInstr *HeadCmpMI = findSuitableCompare(HBB);
338  if (!HeadCmpMI) {
339  continue;
340  }
341 
342  MachineInstr *TrueCmpMI = findSuitableCompare(TBB);
343  if (!TrueCmpMI) {
344  continue;
345  }
346 
347  AArch64CC::CondCode HeadCmp;
348  if (HeadCond.empty() || !parseCond(HeadCond, HeadCmp)) {
349  continue;
350  }
351 
352  AArch64CC::CondCode TrueCmp;
353  if (TrueCond.empty() || !parseCond(TrueCond, TrueCmp)) {
354  continue;
355  }
356 
357  const int HeadImm = (int)HeadCmpMI->getOperand(2).getImm();
358  const int TrueImm = (int)TrueCmpMI->getOperand(2).getImm();
359 
360  DEBUG(dbgs() << "Head branch:\n");
361  DEBUG(dbgs() << "\tcondition: "
362  << AArch64CC::getCondCodeName(HeadCmp) << '\n');
363  DEBUG(dbgs() << "\timmediate: " << HeadImm << '\n');
364 
365  DEBUG(dbgs() << "True branch:\n");
366  DEBUG(dbgs() << "\tcondition: "
367  << AArch64CC::getCondCodeName(TrueCmp) << '\n');
368  DEBUG(dbgs() << "\timmediate: " << TrueImm << '\n');
369 
370  if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::LT) ||
371  (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::GT)) &&
372  std::abs(TrueImm - HeadImm) == 2) {
373  // This branch transforms machine instructions that correspond to
374  //
375  // 1) (a > {TrueImm} && ...) || (a < {HeadImm} && ...)
376  // 2) (a < {TrueImm} && ...) || (a > {HeadImm} && ...)
377  //
378  // into
379  //
380  // 1) (a >= {NewImm} && ...) || (a <= {NewImm} && ...)
381  // 2) (a <= {NewImm} && ...) || (a >= {NewImm} && ...)
382 
383  CmpInfo HeadCmpInfo = adjustCmp(HeadCmpMI, HeadCmp);
384  CmpInfo TrueCmpInfo = adjustCmp(TrueCmpMI, TrueCmp);
385  if (std::get<0>(HeadCmpInfo) == std::get<0>(TrueCmpInfo) &&
386  std::get<1>(HeadCmpInfo) == std::get<1>(TrueCmpInfo)) {
387  modifyCmp(HeadCmpMI, HeadCmpInfo);
388  modifyCmp(TrueCmpMI, TrueCmpInfo);
389  Changed = true;
390  }
391  } else if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::GT) ||
392  (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::LT)) &&
393  std::abs(TrueImm - HeadImm) == 1) {
394  // This branch transforms machine instructions that correspond to
395  //
396  // 1) (a > {TrueImm} && ...) || (a > {HeadImm} && ...)
397  // 2) (a < {TrueImm} && ...) || (a < {HeadImm} && ...)
398  //
399  // into
400  //
401  // 1) (a <= {NewImm} && ...) || (a > {NewImm} && ...)
402  // 2) (a < {NewImm} && ...) || (a >= {NewImm} && ...)
403 
404  // GT -> GE transformation increases immediate value, so picking the
405  // smaller one; LT -> LE decreases immediate value so invert the choice.
406  bool adjustHeadCond = (HeadImm < TrueImm);
407  if (HeadCmp == AArch64CC::LT) {
408  adjustHeadCond = !adjustHeadCond;
409  }
410 
411  if (adjustHeadCond) {
412  Changed |= adjustTo(HeadCmpMI, HeadCmp, TrueCmpMI, TrueImm);
413  } else {
414  Changed |= adjustTo(TrueCmpMI, TrueCmp, HeadCmpMI, HeadImm);
415  }
416  }
417  // Other transformation cases almost never occur due to generation of < or >
418  // comparisons instead of <= and >=.
419  }
420 
421  return Changed;
422 }
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:82
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
STATISTIC(NumFunctions,"Total number of functions")
int getNumber() const
getNumber - MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a M...
iterator getFirstTerminator()
getFirstTerminator - returns an iterator to the first terminator instruction of this basic block...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:70
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:75
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
static const char * getCondCodeName(CondCode Code)
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
int64_t getImm() const
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:134
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:267
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:120
TargetInstrInfo - Interface to description of machine instruction set.
bundle_iterator< MachineInstr, instr_iterator > iterator
static int getComplementOpc(int Opc)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
aarch64 AArch64 CondOpt false
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:273
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:294
MachineInstrBuilder BuildMI(MachineFunction &MF, DebugLoc DL, const MCInstrDesc &MCID)
BuildMI - Builder interface.
aarch64 condopt
INITIALIZE_PASS_BEGIN(AArch64ConditionOptimizer,"aarch64-condopt","AArch64 CondOpt Pass", false, false) INITIALIZE_PASS_END(AArch64ConditionOptimizer
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
void updateTerminator()
updateTerminator - Update the terminator instructions in block to account for changes to the layout...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:123
FunctionPass * createAArch64ConditionOptimizerPass()
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:238
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:51
void initializeAArch64ConditionOptimizerPass(PassRegistry &)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
#define I(x, y, z)
Definition: MD5.cpp:54
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition: APFloat.h:651
static AArch64CC::CondCode getAdjustedCmp(AArch64CC::CondCode Cmp)
static bool parseCond(ArrayRef< MachineOperand > Cond, AArch64CC::CondCode &CC)
iterator_range< df_iterator< T > > depth_first(const T &G)
virtual const TargetInstrInfo * getInstrInfo() const
const MachineInstrBuilder & addOperand(const MachineOperand &MO) const
#define DEBUG(X)
Definition: Debug.h:92
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:41
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...