AArch64ConditionOptimizer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. //=- AArch64ConditionOptimizer.cpp - Remove useless comparisons 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. //
  9. // This pass tries to make consecutive compares of values use same operands to
  10. // allow CSE pass to remove duplicated instructions. For this it analyzes
  11. // branches and adjusts comparisons with immediate values by converting:
  12. // * GE -> GT
  13. // * GT -> GE
  14. // * LT -> LE
  15. // * LE -> LT
  16. // and adjusting immediate values appropriately. It basically corrects two
  17. // immediate values towards each other to make them equal.
  18. //
  19. // Consider the following example in C:
  20. //
  21. // if ((a < 5 && ...) || (a > 5 && ...)) {
  22. // ~~~~~ ~~~~~
  23. // ^ ^
  24. // x y
  25. //
  26. // Here both "x" and "y" expressions compare "a" with "5". When "x" evaluates
  27. // to "false", "y" can just check flags set by the first comparison. As a
  28. // result of the canonicalization employed by
  29. // SelectionDAGBuilder::visitSwitchCase, DAGCombine, and other target-specific
  30. // code, assembly ends up in the form that is not CSE friendly:
  31. //
  32. // ...
  33. // cmp w8, #4
  34. // b.gt .LBB0_3
  35. // ...
  36. // .LBB0_3:
  37. // cmp w8, #6
  38. // b.lt .LBB0_6
  39. // ...
  40. //
  41. // Same assembly after the pass:
  42. //
  43. // ...
  44. // cmp w8, #5
  45. // b.ge .LBB0_3
  46. // ...
  47. // .LBB0_3:
  48. // cmp w8, #5 // <-- CSE pass removes this instruction
  49. // b.le .LBB0_6
  50. // ...
  51. //
  52. // Currently only SUBS and ADDS followed by b.?? are supported.
  53. //
  54. // TODO: maybe handle TBNZ/TBZ the same way as CMP when used instead for "a < 0"
  55. // TODO: handle other conditional instructions (e.g. CSET)
  56. // TODO: allow second branching to be anything if it doesn't require adjusting
  57. //
  58. //===----------------------------------------------------------------------===//
  59. #include "AArch64.h"
  60. #include "MCTargetDesc/AArch64AddressingModes.h"
  61. #include "Utils/AArch64BaseInfo.h"
  62. #include "llvm/ADT/ArrayRef.h"
  63. #include "llvm/ADT/DepthFirstIterator.h"
  64. #include "llvm/ADT/SmallVector.h"
  65. #include "llvm/ADT/Statistic.h"
  66. #include "llvm/CodeGen/MachineBasicBlock.h"
  67. #include "llvm/CodeGen/MachineDominators.h"
  68. #include "llvm/CodeGen/MachineFunction.h"
  69. #include "llvm/CodeGen/MachineFunctionPass.h"
  70. #include "llvm/CodeGen/MachineInstr.h"
  71. #include "llvm/CodeGen/MachineInstrBuilder.h"
  72. #include "llvm/CodeGen/MachineOperand.h"
  73. #include "llvm/CodeGen/MachineRegisterInfo.h"
  74. #include "llvm/CodeGen/TargetInstrInfo.h"
  75. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  76. #include "llvm/InitializePasses.h"
  77. #include "llvm/Pass.h"
  78. #include "llvm/Support/Debug.h"
  79. #include "llvm/Support/ErrorHandling.h"
  80. #include "llvm/Support/raw_ostream.h"
  81. #include <cassert>
  82. #include <cstdlib>
  83. #include <tuple>
  84. using namespace llvm;
  85. #define DEBUG_TYPE "aarch64-condopt"
  86. STATISTIC(NumConditionsAdjusted, "Number of conditions adjusted");
  87. namespace {
  88. class AArch64ConditionOptimizer : public MachineFunctionPass {
  89. const TargetInstrInfo *TII;
  90. MachineDominatorTree *DomTree;
  91. const MachineRegisterInfo *MRI;
  92. public:
  93. // Stores immediate, compare instruction opcode and branch condition (in this
  94. // order) of adjusted comparison.
  95. using CmpInfo = std::tuple<int, unsigned, AArch64CC::CondCode>;
  96. static char ID;
  97. AArch64ConditionOptimizer() : MachineFunctionPass(ID) {
  98. initializeAArch64ConditionOptimizerPass(*PassRegistry::getPassRegistry());
  99. }
  100. void getAnalysisUsage(AnalysisUsage &AU) const override;
  101. MachineInstr *findSuitableCompare(MachineBasicBlock *MBB);
  102. CmpInfo adjustCmp(MachineInstr *CmpMI, AArch64CC::CondCode Cmp);
  103. void modifyCmp(MachineInstr *CmpMI, const CmpInfo &Info);
  104. bool adjustTo(MachineInstr *CmpMI, AArch64CC::CondCode Cmp, MachineInstr *To,
  105. int ToImm);
  106. bool runOnMachineFunction(MachineFunction &MF) override;
  107. StringRef getPassName() const override {
  108. return "AArch64 Condition Optimizer";
  109. }
  110. };
  111. } // end anonymous namespace
  112. char AArch64ConditionOptimizer::ID = 0;
  113. INITIALIZE_PASS_BEGIN(AArch64ConditionOptimizer, "aarch64-condopt",
  114. "AArch64 CondOpt Pass", false, false)
  115. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  116. INITIALIZE_PASS_END(AArch64ConditionOptimizer, "aarch64-condopt",
  117. "AArch64 CondOpt Pass", false, false)
  118. FunctionPass *llvm::createAArch64ConditionOptimizerPass() {
  119. return new AArch64ConditionOptimizer();
  120. }
  121. void AArch64ConditionOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
  122. AU.addRequired<MachineDominatorTree>();
  123. AU.addPreserved<MachineDominatorTree>();
  124. MachineFunctionPass::getAnalysisUsage(AU);
  125. }
  126. // Finds compare instruction that corresponds to supported types of branching.
  127. // Returns the instruction or nullptr on failures or detecting unsupported
  128. // instructions.
  129. MachineInstr *AArch64ConditionOptimizer::findSuitableCompare(
  130. MachineBasicBlock *MBB) {
  131. MachineBasicBlock::iterator Term = MBB->getFirstTerminator();
  132. if (Term == MBB->end())
  133. return nullptr;
  134. if (Term->getOpcode() != AArch64::Bcc)
  135. return nullptr;
  136. // Since we may modify cmp of this MBB, make sure NZCV does not live out.
  137. for (auto *SuccBB : MBB->successors())
  138. if (SuccBB->isLiveIn(AArch64::NZCV))
  139. return nullptr;
  140. // Now find the instruction controlling the terminator.
  141. for (MachineBasicBlock::iterator B = MBB->begin(), It = Term; It != B;) {
  142. It = prev_nodbg(It, B);
  143. MachineInstr &I = *It;
  144. assert(!I.isTerminator() && "Spurious terminator");
  145. // Check if there is any use of NZCV between CMP and Bcc.
  146. if (I.readsRegister(AArch64::NZCV))
  147. return nullptr;
  148. switch (I.getOpcode()) {
  149. // cmp is an alias for subs with a dead destination register.
  150. case AArch64::SUBSWri:
  151. case AArch64::SUBSXri:
  152. // cmn is an alias for adds with a dead destination register.
  153. case AArch64::ADDSWri:
  154. case AArch64::ADDSXri: {
  155. unsigned ShiftAmt = AArch64_AM::getShiftValue(I.getOperand(3).getImm());
  156. if (!I.getOperand(2).isImm()) {
  157. LLVM_DEBUG(dbgs() << "Immediate of cmp is symbolic, " << I << '\n');
  158. return nullptr;
  159. } else if (I.getOperand(2).getImm() << ShiftAmt >= 0xfff) {
  160. LLVM_DEBUG(dbgs() << "Immediate of cmp may be out of range, " << I
  161. << '\n');
  162. return nullptr;
  163. } else if (!MRI->use_nodbg_empty(I.getOperand(0).getReg())) {
  164. LLVM_DEBUG(dbgs() << "Destination of cmp is not dead, " << I << '\n');
  165. return nullptr;
  166. }
  167. return &I;
  168. }
  169. // Prevent false positive case like:
  170. // cmp w19, #0
  171. // cinc w0, w19, gt
  172. // ...
  173. // fcmp d8, #0.0
  174. // b.gt .LBB0_5
  175. case AArch64::FCMPDri:
  176. case AArch64::FCMPSri:
  177. case AArch64::FCMPESri:
  178. case AArch64::FCMPEDri:
  179. case AArch64::SUBSWrr:
  180. case AArch64::SUBSXrr:
  181. case AArch64::ADDSWrr:
  182. case AArch64::ADDSXrr:
  183. case AArch64::FCMPSrr:
  184. case AArch64::FCMPDrr:
  185. case AArch64::FCMPESrr:
  186. case AArch64::FCMPEDrr:
  187. // Skip comparison instructions without immediate operands.
  188. return nullptr;
  189. }
  190. }
  191. LLVM_DEBUG(dbgs() << "Flags not defined in " << printMBBReference(*MBB)
  192. << '\n');
  193. return nullptr;
  194. }
  195. // Changes opcode adds <-> subs considering register operand width.
  196. static int getComplementOpc(int Opc) {
  197. switch (Opc) {
  198. case AArch64::ADDSWri: return AArch64::SUBSWri;
  199. case AArch64::ADDSXri: return AArch64::SUBSXri;
  200. case AArch64::SUBSWri: return AArch64::ADDSWri;
  201. case AArch64::SUBSXri: return AArch64::ADDSXri;
  202. default:
  203. llvm_unreachable("Unexpected opcode");
  204. }
  205. }
  206. // Changes form of comparison inclusive <-> exclusive.
  207. static AArch64CC::CondCode getAdjustedCmp(AArch64CC::CondCode Cmp) {
  208. switch (Cmp) {
  209. case AArch64CC::GT: return AArch64CC::GE;
  210. case AArch64CC::GE: return AArch64CC::GT;
  211. case AArch64CC::LT: return AArch64CC::LE;
  212. case AArch64CC::LE: return AArch64CC::LT;
  213. default:
  214. llvm_unreachable("Unexpected condition code");
  215. }
  216. }
  217. // Transforms GT -> GE, GE -> GT, LT -> LE, LE -> LT by updating comparison
  218. // operator and condition code.
  219. AArch64ConditionOptimizer::CmpInfo AArch64ConditionOptimizer::adjustCmp(
  220. MachineInstr *CmpMI, AArch64CC::CondCode Cmp) {
  221. unsigned Opc = CmpMI->getOpcode();
  222. // CMN (compare with negative immediate) is an alias to ADDS (as
  223. // "operand - negative" == "operand + positive")
  224. bool Negative = (Opc == AArch64::ADDSWri || Opc == AArch64::ADDSXri);
  225. int Correction = (Cmp == AArch64CC::GT) ? 1 : -1;
  226. // Negate Correction value for comparison with negative immediate (CMN).
  227. if (Negative) {
  228. Correction = -Correction;
  229. }
  230. const int OldImm = (int)CmpMI->getOperand(2).getImm();
  231. const int NewImm = std::abs(OldImm + Correction);
  232. // Handle +0 -> -1 and -0 -> +1 (CMN with 0 immediate) transitions by
  233. // adjusting compare instruction opcode.
  234. if (OldImm == 0 && ((Negative && Correction == 1) ||
  235. (!Negative && Correction == -1))) {
  236. Opc = getComplementOpc(Opc);
  237. }
  238. return CmpInfo(NewImm, Opc, getAdjustedCmp(Cmp));
  239. }
  240. // Applies changes to comparison instruction suggested by adjustCmp().
  241. void AArch64ConditionOptimizer::modifyCmp(MachineInstr *CmpMI,
  242. const CmpInfo &Info) {
  243. int Imm;
  244. unsigned Opc;
  245. AArch64CC::CondCode Cmp;
  246. std::tie(Imm, Opc, Cmp) = Info;
  247. MachineBasicBlock *const MBB = CmpMI->getParent();
  248. // Change immediate in comparison instruction (ADDS or SUBS).
  249. BuildMI(*MBB, CmpMI, CmpMI->getDebugLoc(), TII->get(Opc))
  250. .add(CmpMI->getOperand(0))
  251. .add(CmpMI->getOperand(1))
  252. .addImm(Imm)
  253. .add(CmpMI->getOperand(3));
  254. CmpMI->eraseFromParent();
  255. // The fact that this comparison was picked ensures that it's related to the
  256. // first terminator instruction.
  257. MachineInstr &BrMI = *MBB->getFirstTerminator();
  258. // Change condition in branch instruction.
  259. BuildMI(*MBB, BrMI, BrMI.getDebugLoc(), TII->get(AArch64::Bcc))
  260. .addImm(Cmp)
  261. .add(BrMI.getOperand(1));
  262. BrMI.eraseFromParent();
  263. ++NumConditionsAdjusted;
  264. }
  265. // Parse a condition code returned by analyzeBranch, and compute the CondCode
  266. // corresponding to TBB.
  267. // Returns true if parsing was successful, otherwise false is returned.
  268. static bool parseCond(ArrayRef<MachineOperand> Cond, AArch64CC::CondCode &CC) {
  269. // A normal br.cond simply has the condition code.
  270. if (Cond[0].getImm() != -1) {
  271. assert(Cond.size() == 1 && "Unknown Cond array format");
  272. CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
  273. return true;
  274. }
  275. return false;
  276. }
  277. // Adjusts one cmp instruction to another one if result of adjustment will allow
  278. // CSE. Returns true if compare instruction was changed, otherwise false is
  279. // returned.
  280. bool AArch64ConditionOptimizer::adjustTo(MachineInstr *CmpMI,
  281. AArch64CC::CondCode Cmp, MachineInstr *To, int ToImm)
  282. {
  283. CmpInfo Info = adjustCmp(CmpMI, Cmp);
  284. if (std::get<0>(Info) == ToImm && std::get<1>(Info) == To->getOpcode()) {
  285. modifyCmp(CmpMI, Info);
  286. return true;
  287. }
  288. return false;
  289. }
  290. bool AArch64ConditionOptimizer::runOnMachineFunction(MachineFunction &MF) {
  291. LLVM_DEBUG(dbgs() << "********** AArch64 Conditional Compares **********\n"
  292. << "********** Function: " << MF.getName() << '\n');
  293. if (skipFunction(MF.getFunction()))
  294. return false;
  295. TII = MF.getSubtarget().getInstrInfo();
  296. DomTree = &getAnalysis<MachineDominatorTree>();
  297. MRI = &MF.getRegInfo();
  298. bool Changed = false;
  299. // Visit blocks in dominator tree pre-order. The pre-order enables multiple
  300. // cmp-conversions from the same head block.
  301. // Note that updateDomTree() modifies the children of the DomTree node
  302. // currently being visited. The df_iterator supports that; it doesn't look at
  303. // child_begin() / child_end() until after a node has been visited.
  304. for (MachineDomTreeNode *I : depth_first(DomTree)) {
  305. MachineBasicBlock *HBB = I->getBlock();
  306. SmallVector<MachineOperand, 4> HeadCond;
  307. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  308. if (TII->analyzeBranch(*HBB, TBB, FBB, HeadCond)) {
  309. continue;
  310. }
  311. // Equivalence check is to skip loops.
  312. if (!TBB || TBB == HBB) {
  313. continue;
  314. }
  315. SmallVector<MachineOperand, 4> TrueCond;
  316. MachineBasicBlock *TBB_TBB = nullptr, *TBB_FBB = nullptr;
  317. if (TII->analyzeBranch(*TBB, TBB_TBB, TBB_FBB, TrueCond)) {
  318. continue;
  319. }
  320. MachineInstr *HeadCmpMI = findSuitableCompare(HBB);
  321. if (!HeadCmpMI) {
  322. continue;
  323. }
  324. MachineInstr *TrueCmpMI = findSuitableCompare(TBB);
  325. if (!TrueCmpMI) {
  326. continue;
  327. }
  328. AArch64CC::CondCode HeadCmp;
  329. if (HeadCond.empty() || !parseCond(HeadCond, HeadCmp)) {
  330. continue;
  331. }
  332. AArch64CC::CondCode TrueCmp;
  333. if (TrueCond.empty() || !parseCond(TrueCond, TrueCmp)) {
  334. continue;
  335. }
  336. const int HeadImm = (int)HeadCmpMI->getOperand(2).getImm();
  337. const int TrueImm = (int)TrueCmpMI->getOperand(2).getImm();
  338. LLVM_DEBUG(dbgs() << "Head branch:\n");
  339. LLVM_DEBUG(dbgs() << "\tcondition: " << AArch64CC::getCondCodeName(HeadCmp)
  340. << '\n');
  341. LLVM_DEBUG(dbgs() << "\timmediate: " << HeadImm << '\n');
  342. LLVM_DEBUG(dbgs() << "True branch:\n");
  343. LLVM_DEBUG(dbgs() << "\tcondition: " << AArch64CC::getCondCodeName(TrueCmp)
  344. << '\n');
  345. LLVM_DEBUG(dbgs() << "\timmediate: " << TrueImm << '\n');
  346. if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::LT) ||
  347. (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::GT)) &&
  348. std::abs(TrueImm - HeadImm) == 2) {
  349. // This branch transforms machine instructions that correspond to
  350. //
  351. // 1) (a > {TrueImm} && ...) || (a < {HeadImm} && ...)
  352. // 2) (a < {TrueImm} && ...) || (a > {HeadImm} && ...)
  353. //
  354. // into
  355. //
  356. // 1) (a >= {NewImm} && ...) || (a <= {NewImm} && ...)
  357. // 2) (a <= {NewImm} && ...) || (a >= {NewImm} && ...)
  358. CmpInfo HeadCmpInfo = adjustCmp(HeadCmpMI, HeadCmp);
  359. CmpInfo TrueCmpInfo = adjustCmp(TrueCmpMI, TrueCmp);
  360. if (std::get<0>(HeadCmpInfo) == std::get<0>(TrueCmpInfo) &&
  361. std::get<1>(HeadCmpInfo) == std::get<1>(TrueCmpInfo)) {
  362. modifyCmp(HeadCmpMI, HeadCmpInfo);
  363. modifyCmp(TrueCmpMI, TrueCmpInfo);
  364. Changed = true;
  365. }
  366. } else if (((HeadCmp == AArch64CC::GT && TrueCmp == AArch64CC::GT) ||
  367. (HeadCmp == AArch64CC::LT && TrueCmp == AArch64CC::LT)) &&
  368. std::abs(TrueImm - HeadImm) == 1) {
  369. // This branch transforms machine instructions that correspond to
  370. //
  371. // 1) (a > {TrueImm} && ...) || (a > {HeadImm} && ...)
  372. // 2) (a < {TrueImm} && ...) || (a < {HeadImm} && ...)
  373. //
  374. // into
  375. //
  376. // 1) (a <= {NewImm} && ...) || (a > {NewImm} && ...)
  377. // 2) (a < {NewImm} && ...) || (a >= {NewImm} && ...)
  378. // GT -> GE transformation increases immediate value, so picking the
  379. // smaller one; LT -> LE decreases immediate value so invert the choice.
  380. bool adjustHeadCond = (HeadImm < TrueImm);
  381. if (HeadCmp == AArch64CC::LT) {
  382. adjustHeadCond = !adjustHeadCond;
  383. }
  384. if (adjustHeadCond) {
  385. Changed |= adjustTo(HeadCmpMI, HeadCmp, TrueCmpMI, TrueImm);
  386. } else {
  387. Changed |= adjustTo(TrueCmpMI, TrueCmp, HeadCmpMI, HeadImm);
  388. }
  389. }
  390. // Other transformation cases almost never occur due to generation of < or >
  391. // comparisons instead of <= and >=.
  392. }
  393. return Changed;
  394. }