Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1 | //===- InstCombineCompares.cpp --------------------------------------------===// |
| 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 file implements the visitICmp and visitFCmp functions. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
Chandler Carruth | a917458 | 2015-01-22 05:25:13 +0000 | [diff] [blame] | 14 | #include "InstCombineInternal.h" |
Matt Arsenault | 55e7312 | 2015-01-06 15:50:59 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/APSInt.h" |
Silviu Baranga | f29dfd3 | 2016-01-15 15:52:05 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/SetVector.h" |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/Statistic.h" |
Eli Friedman | 911e12f | 2011-07-20 21:57:23 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/ConstantFolding.h" |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/InstructionSimplify.h" |
| 20 | #include "llvm/Analysis/MemoryBuiltins.h" |
Mehdi Amini | b550cb1 | 2016-04-18 09:17:29 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/TargetLibraryInfo.h" |
| 22 | #include "llvm/Analysis/VectorUtils.h" |
Chandler Carruth | 8cd041e | 2014-03-04 12:24:34 +0000 | [diff] [blame] | 23 | #include "llvm/IR/ConstantRange.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 24 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 25 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 26 | #include "llvm/IR/IntrinsicInst.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 27 | #include "llvm/IR/PatternMatch.h" |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 28 | #include "llvm/Support/Debug.h" |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 29 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 30 | using namespace llvm; |
| 31 | using namespace PatternMatch; |
| 32 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 33 | #define DEBUG_TYPE "instcombine" |
| 34 | |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 35 | // How many times is a select replaced by one of its operands? |
| 36 | STATISTIC(NumSel, "Number of select opts"); |
| 37 | |
Chris Lattner | 9845710 | 2011-02-10 05:23:05 +0000 | [diff] [blame] | 38 | |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 39 | static ConstantInt *extractElement(Constant *V, Constant *Idx) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 40 | return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx)); |
| 41 | } |
| 42 | |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 43 | static bool hasAddOverflow(ConstantInt *Result, |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 44 | ConstantInt *In1, ConstantInt *In2, |
| 45 | bool IsSigned) { |
Chris Lattner | b1a1512 | 2011-07-15 06:08:15 +0000 | [diff] [blame] | 46 | if (!IsSigned) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 47 | return Result->getValue().ult(In1->getValue()); |
Chris Lattner | b1a1512 | 2011-07-15 06:08:15 +0000 | [diff] [blame] | 48 | |
| 49 | if (In2->isNegative()) |
| 50 | return Result->getValue().sgt(In1->getValue()); |
| 51 | return Result->getValue().slt(In1->getValue()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 52 | } |
| 53 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 54 | /// Compute Result = In1+In2, returning true if the result overflowed for this |
| 55 | /// type. |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 56 | static bool addWithOverflow(Constant *&Result, Constant *In1, |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 57 | Constant *In2, bool IsSigned = false) { |
| 58 | Result = ConstantExpr::getAdd(In1, In2); |
| 59 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 60 | if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 61 | for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { |
| 62 | Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 63 | if (hasAddOverflow(extractElement(Result, Idx), |
| 64 | extractElement(In1, Idx), |
| 65 | extractElement(In2, Idx), |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 66 | IsSigned)) |
| 67 | return true; |
| 68 | } |
| 69 | return false; |
| 70 | } |
| 71 | |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 72 | return hasAddOverflow(cast<ConstantInt>(Result), |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 73 | cast<ConstantInt>(In1), cast<ConstantInt>(In2), |
| 74 | IsSigned); |
| 75 | } |
| 76 | |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 77 | static bool hasSubOverflow(ConstantInt *Result, |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 78 | ConstantInt *In1, ConstantInt *In2, |
| 79 | bool IsSigned) { |
Chris Lattner | b1a1512 | 2011-07-15 06:08:15 +0000 | [diff] [blame] | 80 | if (!IsSigned) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 81 | return Result->getValue().ugt(In1->getValue()); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 82 | |
Chris Lattner | b1a1512 | 2011-07-15 06:08:15 +0000 | [diff] [blame] | 83 | if (In2->isNegative()) |
| 84 | return Result->getValue().slt(In1->getValue()); |
| 85 | |
| 86 | return Result->getValue().sgt(In1->getValue()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 87 | } |
| 88 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 89 | /// Compute Result = In1-In2, returning true if the result overflowed for this |
| 90 | /// type. |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 91 | static bool subWithOverflow(Constant *&Result, Constant *In1, |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 92 | Constant *In2, bool IsSigned = false) { |
| 93 | Result = ConstantExpr::getSub(In1, In2); |
| 94 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 95 | if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 96 | for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { |
| 97 | Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 98 | if (hasSubOverflow(extractElement(Result, Idx), |
| 99 | extractElement(In1, Idx), |
| 100 | extractElement(In2, Idx), |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 101 | IsSigned)) |
| 102 | return true; |
| 103 | } |
| 104 | return false; |
| 105 | } |
| 106 | |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 107 | return hasSubOverflow(cast<ConstantInt>(Result), |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 108 | cast<ConstantInt>(In1), cast<ConstantInt>(In2), |
| 109 | IsSigned); |
| 110 | } |
| 111 | |
Balaram Makam | 569eaec | 2016-05-04 21:32:14 +0000 | [diff] [blame] | 112 | /// Given an icmp instruction, return true if any use of this comparison is a |
| 113 | /// branch on sign bit comparison. |
| 114 | static bool isBranchOnSignBitCheck(ICmpInst &I, bool isSignBit) { |
| 115 | for (auto *U : I.users()) |
| 116 | if (isa<BranchInst>(U)) |
| 117 | return isSignBit; |
| 118 | return false; |
| 119 | } |
| 120 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 121 | /// Given an exploded icmp instruction, return true if the comparison only |
| 122 | /// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the |
| 123 | /// result of the comparison is true when the input value is signed. |
Sanjay Patel | 7926366 | 2016-08-21 15:07:45 +0000 | [diff] [blame] | 124 | static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 125 | bool &TrueIfSigned) { |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 126 | switch (Pred) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 127 | case ICmpInst::ICMP_SLT: // True if LHS s< 0 |
| 128 | TrueIfSigned = true; |
Sanjay Patel | 7926366 | 2016-08-21 15:07:45 +0000 | [diff] [blame] | 129 | return RHS == 0; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 130 | case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1 |
| 131 | TrueIfSigned = true; |
Sanjay Patel | 7926366 | 2016-08-21 15:07:45 +0000 | [diff] [blame] | 132 | return RHS.isAllOnesValue(); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 133 | case ICmpInst::ICMP_SGT: // True if LHS s> -1 |
| 134 | TrueIfSigned = false; |
Sanjay Patel | 7926366 | 2016-08-21 15:07:45 +0000 | [diff] [blame] | 135 | return RHS.isAllOnesValue(); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 136 | case ICmpInst::ICMP_UGT: |
| 137 | // True if LHS u> RHS and RHS == high-bit-mask - 1 |
| 138 | TrueIfSigned = true; |
Sanjay Patel | 7926366 | 2016-08-21 15:07:45 +0000 | [diff] [blame] | 139 | return RHS.isMaxSignedValue(); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 140 | case ICmpInst::ICMP_UGE: |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 141 | // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc) |
| 142 | TrueIfSigned = true; |
Sanjay Patel | 7926366 | 2016-08-21 15:07:45 +0000 | [diff] [blame] | 143 | return RHS.isSignBit(); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 144 | default: |
| 145 | return false; |
| 146 | } |
| 147 | } |
| 148 | |
Arnaud A. de Grandmaison | 3ee88e8 | 2013-03-25 11:47:38 +0000 | [diff] [blame] | 149 | /// Returns true if the exploded icmp can be expressed as a signed comparison |
| 150 | /// to zero and updates the predicate accordingly. |
| 151 | /// The signedness of the comparison is preserved. |
Sanjay Patel | 5b11284 | 2016-08-18 14:59:14 +0000 | [diff] [blame] | 152 | /// TODO: Refactor with decomposeBitTestICmp()? |
| 153 | static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) { |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 154 | if (!ICmpInst::isSigned(Pred)) |
Arnaud A. de Grandmaison | 9c383d6 | 2013-03-25 09:48:49 +0000 | [diff] [blame] | 155 | return false; |
| 156 | |
Sanjay Patel | 5b11284 | 2016-08-18 14:59:14 +0000 | [diff] [blame] | 157 | if (C == 0) |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 158 | return ICmpInst::isRelational(Pred); |
Arnaud A. de Grandmaison | 9c383d6 | 2013-03-25 09:48:49 +0000 | [diff] [blame] | 159 | |
Sanjay Patel | 5b11284 | 2016-08-18 14:59:14 +0000 | [diff] [blame] | 160 | if (C == 1) { |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 161 | if (Pred == ICmpInst::ICMP_SLT) { |
| 162 | Pred = ICmpInst::ICMP_SLE; |
Arnaud A. de Grandmaison | 9c383d6 | 2013-03-25 09:48:49 +0000 | [diff] [blame] | 163 | return true; |
Arnaud A. de Grandmaison | 9c383d6 | 2013-03-25 09:48:49 +0000 | [diff] [blame] | 164 | } |
Sanjay Patel | 5b11284 | 2016-08-18 14:59:14 +0000 | [diff] [blame] | 165 | } else if (C.isAllOnesValue()) { |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 166 | if (Pred == ICmpInst::ICMP_SGT) { |
| 167 | Pred = ICmpInst::ICMP_SGE; |
Arnaud A. de Grandmaison | 9c383d6 | 2013-03-25 09:48:49 +0000 | [diff] [blame] | 168 | return true; |
Arnaud A. de Grandmaison | 9c383d6 | 2013-03-25 09:48:49 +0000 | [diff] [blame] | 169 | } |
Arnaud A. de Grandmaison | 3ee88e8 | 2013-03-25 11:47:38 +0000 | [diff] [blame] | 170 | } |
Arnaud A. de Grandmaison | 9c383d6 | 2013-03-25 09:48:49 +0000 | [diff] [blame] | 171 | |
| 172 | return false; |
| 173 | } |
| 174 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 175 | /// Given a signed integer type and a set of known zero and one bits, compute |
| 176 | /// the maximum and minimum values that could have the specified known zero and |
| 177 | /// known one bits, returning them in Min/Max. |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 178 | static void computeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero, |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 179 | const APInt &KnownOne, |
| 180 | APInt &Min, APInt &Max) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 181 | assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && |
| 182 | KnownZero.getBitWidth() == Min.getBitWidth() && |
| 183 | KnownZero.getBitWidth() == Max.getBitWidth() && |
| 184 | "KnownZero, KnownOne and Min, Max must have equal bitwidth."); |
| 185 | APInt UnknownBits = ~(KnownZero|KnownOne); |
| 186 | |
| 187 | // The minimum value is when all unknown bits are zeros, EXCEPT for the sign |
| 188 | // bit if it is unknown. |
| 189 | Min = KnownOne; |
| 190 | Max = KnownOne|UnknownBits; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 191 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 192 | if (UnknownBits.isNegative()) { // Sign bit is unknown |
Jay Foad | 25a5e4c | 2010-12-01 08:53:58 +0000 | [diff] [blame] | 193 | Min.setBit(Min.getBitWidth()-1); |
| 194 | Max.clearBit(Max.getBitWidth()-1); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 195 | } |
| 196 | } |
| 197 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 198 | /// Given an unsigned integer type and a set of known zero and one bits, compute |
| 199 | /// the maximum and minimum values that could have the specified known zero and |
| 200 | /// known one bits, returning them in Min/Max. |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 201 | static void computeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero, |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 202 | const APInt &KnownOne, |
| 203 | APInt &Min, APInt &Max) { |
| 204 | assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && |
| 205 | KnownZero.getBitWidth() == Min.getBitWidth() && |
| 206 | KnownZero.getBitWidth() == Max.getBitWidth() && |
| 207 | "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."); |
| 208 | APInt UnknownBits = ~(KnownZero|KnownOne); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 209 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 210 | // The minimum value is when the unknown bits are all zeros. |
| 211 | Min = KnownOne; |
| 212 | // The maximum value is when the unknown bits are all ones. |
| 213 | Max = KnownOne|UnknownBits; |
| 214 | } |
| 215 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 216 | /// This is called when we see this pattern: |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 217 | /// cmp pred (load (gep GV, ...)), cmpcst |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 218 | /// where GV is a global variable with a constant initializer. Try to simplify |
| 219 | /// this into some simple computation that does not need the load. For example |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 220 | /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". |
| 221 | /// |
| 222 | /// If AndCst is non-null, then the loaded value is masked with that constant |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 223 | /// before doing the comparison. This handles cases like "A[i]&4 == 0". |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 224 | Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, |
| 225 | GlobalVariable *GV, |
| 226 | CmpInst &ICI, |
| 227 | ConstantInt *AndCst) { |
Chris Lattner | fe74176 | 2012-01-31 02:55:06 +0000 | [diff] [blame] | 228 | Constant *Init = GV->getInitializer(); |
| 229 | if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 230 | return nullptr; |
Jim Grosbach | bdbd734 | 2013-04-05 21:20:12 +0000 | [diff] [blame] | 231 | |
Chris Lattner | fe74176 | 2012-01-31 02:55:06 +0000 | [diff] [blame] | 232 | uint64_t ArrayElementCount = Init->getType()->getArrayNumElements(); |
Davide Italiano | 2133bf5 | 2017-02-07 17:56:50 +0000 | [diff] [blame^] | 233 | // Don't blow up on huge arrays. |
| 234 | if (ArrayElementCount > MaxArraySizeForCombine) |
| 235 | return nullptr; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 236 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 237 | // There are many forms of this optimization we can handle, for now, just do |
| 238 | // the simple index into a single-dimensional array. |
| 239 | // |
| 240 | // Require: GEP GV, 0, i {{, constant indices}} |
| 241 | if (GEP->getNumOperands() < 3 || |
| 242 | !isa<ConstantInt>(GEP->getOperand(1)) || |
| 243 | !cast<ConstantInt>(GEP->getOperand(1))->isZero() || |
| 244 | isa<Constant>(GEP->getOperand(2))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 245 | return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 246 | |
| 247 | // Check that indices after the variable are constants and in-range for the |
| 248 | // type they index. Collect the indices. This is typically for arrays of |
| 249 | // structs. |
| 250 | SmallVector<unsigned, 4> LaterIndices; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 251 | |
Chris Lattner | fe74176 | 2012-01-31 02:55:06 +0000 | [diff] [blame] | 252 | Type *EltTy = Init->getType()->getArrayElementType(); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 253 | for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) { |
| 254 | ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 255 | if (!Idx) return nullptr; // Variable index. |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 256 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 257 | uint64_t IdxVal = Idx->getZExtValue(); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 258 | if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index. |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 259 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 260 | if (StructType *STy = dyn_cast<StructType>(EltTy)) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 261 | EltTy = STy->getElementType(IdxVal); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 262 | else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 263 | if (IdxVal >= ATy->getNumElements()) return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 264 | EltTy = ATy->getElementType(); |
| 265 | } else { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 266 | return nullptr; // Unknown type. |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 267 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 268 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 269 | LaterIndices.push_back(IdxVal); |
| 270 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 271 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 272 | enum { Overdefined = -3, Undefined = -2 }; |
| 273 | |
| 274 | // Variables for our state machines. |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 275 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 276 | // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form |
| 277 | // "i == 47 | i == 87", where 47 is the first index the condition is true for, |
| 278 | // and 87 is the second (and last) index. FirstTrueElement is -2 when |
| 279 | // undefined, otherwise set to the first true element. SecondTrueElement is |
| 280 | // -2 when undefined, -3 when overdefined and >= 0 when that index is true. |
| 281 | int FirstTrueElement = Undefined, SecondTrueElement = Undefined; |
| 282 | |
| 283 | // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the |
| 284 | // form "i != 47 & i != 87". Same state transitions as for true elements. |
| 285 | int FirstFalseElement = Undefined, SecondFalseElement = Undefined; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 286 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 287 | /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these |
| 288 | /// define a state machine that triggers for ranges of values that the index |
| 289 | /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'. |
| 290 | /// This is -2 when undefined, -3 when overdefined, and otherwise the last |
| 291 | /// index in the range (inclusive). We use -2 for undefined here because we |
| 292 | /// use relative comparisons and don't want 0-1 to match -1. |
| 293 | int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 294 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 295 | // MagicBitvector - This is a magic bitvector where we set a bit if the |
| 296 | // comparison is true for element 'i'. If there are 64 elements or less in |
| 297 | // the array, this will fully represent all the comparison results. |
| 298 | uint64_t MagicBitvector = 0; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 299 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 300 | // Scan the array and see if one of our patterns matches. |
| 301 | Constant *CompareRHS = cast<Constant>(ICI.getOperand(1)); |
Chris Lattner | fe74176 | 2012-01-31 02:55:06 +0000 | [diff] [blame] | 302 | for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) { |
| 303 | Constant *Elt = Init->getAggregateElement(i); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 304 | if (!Elt) return nullptr; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 305 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 306 | // If this is indexing an array of structures, get the structure element. |
| 307 | if (!LaterIndices.empty()) |
Jay Foad | 57aa636 | 2011-07-13 10:26:04 +0000 | [diff] [blame] | 308 | Elt = ConstantExpr::getExtractValue(Elt, LaterIndices); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 309 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 310 | // If the element is masked, handle it. |
| 311 | if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 312 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 313 | // Find out if the comparison would be true or false for the i'th element. |
| 314 | Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt, |
Justin Bogner | 9979840 | 2016-08-05 01:06:44 +0000 | [diff] [blame] | 315 | CompareRHS, DL, &TLI); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 316 | // If the result is undef for this element, ignore it. |
| 317 | if (isa<UndefValue>(C)) { |
| 318 | // Extend range state machines to cover this element in case there is an |
| 319 | // undef in the middle of the range. |
| 320 | if (TrueRangeEnd == (int)i-1) |
| 321 | TrueRangeEnd = i; |
| 322 | if (FalseRangeEnd == (int)i-1) |
| 323 | FalseRangeEnd = i; |
| 324 | continue; |
| 325 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 326 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 327 | // If we can't compute the result for any of the elements, we have to give |
| 328 | // up evaluating the entire conditional. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 329 | if (!isa<ConstantInt>(C)) return nullptr; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 330 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 331 | // Otherwise, we know if the comparison is true or false for this element, |
| 332 | // update our state machines. |
| 333 | bool IsTrueForElt = !cast<ConstantInt>(C)->isZero(); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 334 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 335 | // State machine for single/double/range index comparison. |
| 336 | if (IsTrueForElt) { |
| 337 | // Update the TrueElement state machine. |
| 338 | if (FirstTrueElement == Undefined) |
| 339 | FirstTrueElement = TrueRangeEnd = i; // First true element. |
| 340 | else { |
| 341 | // Update double-compare state machine. |
| 342 | if (SecondTrueElement == Undefined) |
| 343 | SecondTrueElement = i; |
| 344 | else |
| 345 | SecondTrueElement = Overdefined; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 346 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 347 | // Update range state machine. |
| 348 | if (TrueRangeEnd == (int)i-1) |
| 349 | TrueRangeEnd = i; |
| 350 | else |
| 351 | TrueRangeEnd = Overdefined; |
| 352 | } |
| 353 | } else { |
| 354 | // Update the FalseElement state machine. |
| 355 | if (FirstFalseElement == Undefined) |
| 356 | FirstFalseElement = FalseRangeEnd = i; // First false element. |
| 357 | else { |
| 358 | // Update double-compare state machine. |
| 359 | if (SecondFalseElement == Undefined) |
| 360 | SecondFalseElement = i; |
| 361 | else |
| 362 | SecondFalseElement = Overdefined; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 363 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 364 | // Update range state machine. |
| 365 | if (FalseRangeEnd == (int)i-1) |
| 366 | FalseRangeEnd = i; |
| 367 | else |
| 368 | FalseRangeEnd = Overdefined; |
| 369 | } |
| 370 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 371 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 372 | // If this element is in range, update our magic bitvector. |
| 373 | if (i < 64 && IsTrueForElt) |
| 374 | MagicBitvector |= 1ULL << i; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 375 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 376 | // If all of our states become overdefined, bail out early. Since the |
| 377 | // predicate is expensive, only check it every 8 elements. This is only |
| 378 | // really useful for really huge arrays. |
| 379 | if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined && |
| 380 | SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined && |
| 381 | FalseRangeEnd == Overdefined) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 382 | return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 383 | } |
| 384 | |
| 385 | // Now that we've scanned the entire array, emit our new comparison(s). We |
| 386 | // order the state machines in complexity of the generated code. |
| 387 | Value *Idx = GEP->getOperand(2); |
| 388 | |
Matt Arsenault | 5aeae18 | 2013-08-19 21:40:31 +0000 | [diff] [blame] | 389 | // If the index is larger than the pointer size of the target, truncate the |
| 390 | // index down like the GEP would do implicitly. We don't have to do this for |
| 391 | // an inbounds GEP because the index can't be out of range. |
Matt Arsenault | 8468062 | 2013-09-30 21:11:01 +0000 | [diff] [blame] | 392 | if (!GEP->isInBounds()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 393 | Type *IntPtrTy = DL.getIntPtrType(GEP->getType()); |
Matt Arsenault | 8468062 | 2013-09-30 21:11:01 +0000 | [diff] [blame] | 394 | unsigned PtrSize = IntPtrTy->getIntegerBitWidth(); |
| 395 | if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize) |
| 396 | Idx = Builder->CreateTrunc(Idx, IntPtrTy); |
| 397 | } |
Matt Arsenault | 5aeae18 | 2013-08-19 21:40:31 +0000 | [diff] [blame] | 398 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 399 | // If the comparison is only true for one or two elements, emit direct |
| 400 | // comparisons. |
| 401 | if (SecondTrueElement != Overdefined) { |
| 402 | // None true -> false. |
| 403 | if (FirstTrueElement == Undefined) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 404 | return replaceInstUsesWith(ICI, Builder->getFalse()); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 405 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 406 | Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 407 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 408 | // True for one element -> 'i == 47'. |
| 409 | if (SecondTrueElement == Undefined) |
| 410 | return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 411 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 412 | // True for two elements -> 'i == 47 | i == 72'. |
| 413 | Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx); |
| 414 | Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement); |
| 415 | Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx); |
| 416 | return BinaryOperator::CreateOr(C1, C2); |
| 417 | } |
| 418 | |
| 419 | // If the comparison is only false for one or two elements, emit direct |
| 420 | // comparisons. |
| 421 | if (SecondFalseElement != Overdefined) { |
| 422 | // None false -> true. |
| 423 | if (FirstFalseElement == Undefined) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 424 | return replaceInstUsesWith(ICI, Builder->getTrue()); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 425 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 426 | Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); |
| 427 | |
| 428 | // False for one element -> 'i != 47'. |
| 429 | if (SecondFalseElement == Undefined) |
| 430 | return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 431 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 432 | // False for two elements -> 'i != 47 & i != 72'. |
| 433 | Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx); |
| 434 | Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement); |
| 435 | Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx); |
| 436 | return BinaryOperator::CreateAnd(C1, C2); |
| 437 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 438 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 439 | // If the comparison can be replaced with a range comparison for the elements |
| 440 | // where it is true, emit the range check. |
| 441 | if (TrueRangeEnd != Overdefined) { |
| 442 | assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare"); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 443 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 444 | // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1). |
| 445 | if (FirstTrueElement) { |
| 446 | Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement); |
| 447 | Idx = Builder->CreateAdd(Idx, Offs); |
| 448 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 449 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 450 | Value *End = ConstantInt::get(Idx->getType(), |
| 451 | TrueRangeEnd-FirstTrueElement+1); |
| 452 | return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End); |
| 453 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 454 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 455 | // False range check. |
| 456 | if (FalseRangeEnd != Overdefined) { |
| 457 | assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare"); |
| 458 | // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse). |
| 459 | if (FirstFalseElement) { |
| 460 | Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement); |
| 461 | Idx = Builder->CreateAdd(Idx, Offs); |
| 462 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 463 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 464 | Value *End = ConstantInt::get(Idx->getType(), |
| 465 | FalseRangeEnd-FirstFalseElement); |
| 466 | return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End); |
| 467 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 468 | |
Arnaud A. de Grandmaison | f364bc6 | 2013-03-22 08:25:01 +0000 | [diff] [blame] | 469 | // If a magic bitvector captures the entire comparison state |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 470 | // of this load, replace it with computation that does: |
| 471 | // ((magic_cst >> i) & 1) != 0 |
Arnaud A. de Grandmaison | f364bc6 | 2013-03-22 08:25:01 +0000 | [diff] [blame] | 472 | { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 473 | Type *Ty = nullptr; |
Arnaud A. de Grandmaison | f364bc6 | 2013-03-22 08:25:01 +0000 | [diff] [blame] | 474 | |
| 475 | // Look for an appropriate type: |
| 476 | // - The type of Idx if the magic fits |
| 477 | // - The smallest fitting legal type if we have a DataLayout |
| 478 | // - Default to i32 |
| 479 | if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth()) |
| 480 | Ty = Idx->getType(); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 481 | else |
| 482 | Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount); |
Arnaud A. de Grandmaison | f364bc6 | 2013-03-22 08:25:01 +0000 | [diff] [blame] | 483 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 484 | if (Ty) { |
Arnaud A. de Grandmaison | f364bc6 | 2013-03-22 08:25:01 +0000 | [diff] [blame] | 485 | Value *V = Builder->CreateIntCast(Idx, Ty, false); |
| 486 | V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); |
| 487 | V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V); |
| 488 | return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); |
| 489 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 490 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 491 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 492 | return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 493 | } |
| 494 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 495 | /// Return a value that can be used to compare the *offset* implied by a GEP to |
| 496 | /// zero. For example, if we have &A[i], we want to return 'i' for |
| 497 | /// "icmp ne i, 0". Note that, in general, indices can be complex, and scales |
| 498 | /// are involved. The above expression would also be legal to codegen as |
| 499 | /// "icmp ne (i*4), 0" (assuming A is a pointer to i32). |
| 500 | /// This latter form is less amenable to optimization though, and we are allowed |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 501 | /// to generate the first by knowing that pointer arithmetic doesn't overflow. |
| 502 | /// |
| 503 | /// If we can't emit an optimized form for this expression, this returns null. |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 504 | /// |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 505 | static Value *evaluateGEPOffsetExpression(User *GEP, InstCombiner &IC, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 506 | const DataLayout &DL) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 507 | gep_type_iterator GTI = gep_type_begin(GEP); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 508 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 509 | // Check to see if this gep only has a single variable index. If so, and if |
| 510 | // any constant indices are a multiple of its scale, then we can compute this |
| 511 | // in terms of the scale of the variable index. For example, if the GEP |
| 512 | // implies an offset of "12 + i*4", then we can codegen this as "3 + i", |
| 513 | // because the expression will cross zero at the same point. |
| 514 | unsigned i, e = GEP->getNumOperands(); |
| 515 | int64_t Offset = 0; |
| 516 | for (i = 1; i != e; ++i, ++GTI) { |
| 517 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 518 | // Compute the aggregate offset of constant indices. |
| 519 | if (CI->isZero()) continue; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 520 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 521 | // Handle a struct index, which adds its field offset to the pointer. |
Peter Collingbourne | ab85225b | 2016-12-02 02:24:42 +0000 | [diff] [blame] | 522 | if (StructType *STy = GTI.getStructTypeOrNull()) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 523 | Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 524 | } else { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 525 | uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 526 | Offset += Size*CI->getSExtValue(); |
| 527 | } |
| 528 | } else { |
| 529 | // Found our variable index. |
| 530 | break; |
| 531 | } |
| 532 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 533 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 534 | // If there are no variable indices, we must have a constant offset, just |
| 535 | // evaluate it the general way. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 536 | if (i == e) return nullptr; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 537 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 538 | Value *VariableIdx = GEP->getOperand(i); |
| 539 | // Determine the scale factor of the variable element. For example, this is |
| 540 | // 4 if the variable index is into an array of i32. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 541 | uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType()); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 542 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 543 | // Verify that there are no other variable indices. If so, emit the hard way. |
| 544 | for (++i, ++GTI; i != e; ++i, ++GTI) { |
| 545 | ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 546 | if (!CI) return nullptr; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 547 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 548 | // Compute the aggregate offset of constant indices. |
| 549 | if (CI->isZero()) continue; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 550 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 551 | // Handle a struct index, which adds its field offset to the pointer. |
Peter Collingbourne | ab85225b | 2016-12-02 02:24:42 +0000 | [diff] [blame] | 552 | if (StructType *STy = GTI.getStructTypeOrNull()) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 553 | Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 554 | } else { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 555 | uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 556 | Offset += Size*CI->getSExtValue(); |
| 557 | } |
| 558 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 559 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 560 | // Okay, we know we have a single variable index, which must be a |
| 561 | // pointer/array/vector index. If there is no offset, life is simple, return |
| 562 | // the index. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 563 | Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType()); |
Matt Arsenault | 745101d | 2013-08-21 19:53:10 +0000 | [diff] [blame] | 564 | unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth(); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 565 | if (Offset == 0) { |
| 566 | // Cast to intptrty in case a truncation occurs. If an extension is needed, |
| 567 | // we don't need to bother extending: the extension won't affect where the |
| 568 | // computation crosses zero. |
Eli Friedman | 1754a25 | 2011-05-18 23:11:30 +0000 | [diff] [blame] | 569 | if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) { |
Eli Friedman | 1754a25 | 2011-05-18 23:11:30 +0000 | [diff] [blame] | 570 | VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy); |
| 571 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 572 | return VariableIdx; |
| 573 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 574 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 575 | // Otherwise, there is an index. The computation we will do will be modulo |
| 576 | // the pointer size, so get it. |
| 577 | uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 578 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 579 | Offset &= PtrSizeMask; |
| 580 | VariableScale &= PtrSizeMask; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 581 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 582 | // To do this transformation, any constant index must be a multiple of the |
| 583 | // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i", |
| 584 | // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a |
| 585 | // multiple of the variable scale. |
| 586 | int64_t NewOffs = Offset / (int64_t)VariableScale; |
| 587 | if (Offset != NewOffs*(int64_t)VariableScale) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 588 | return nullptr; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 589 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 590 | // Okay, we can do this evaluation. Start by converting the index to intptr. |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 591 | if (VariableIdx->getType() != IntPtrTy) |
Eli Friedman | 1754a25 | 2011-05-18 23:11:30 +0000 | [diff] [blame] | 592 | VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy, |
| 593 | true /*Signed*/); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 594 | Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs); |
Eli Friedman | 1754a25 | 2011-05-18 23:11:30 +0000 | [diff] [blame] | 595 | return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset"); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 596 | } |
| 597 | |
Silviu Baranga | f29dfd3 | 2016-01-15 15:52:05 +0000 | [diff] [blame] | 598 | /// Returns true if we can rewrite Start as a GEP with pointer Base |
| 599 | /// and some integer offset. The nodes that need to be re-written |
| 600 | /// for this transformation will be added to Explored. |
| 601 | static bool canRewriteGEPAsOffset(Value *Start, Value *Base, |
| 602 | const DataLayout &DL, |
| 603 | SetVector<Value *> &Explored) { |
| 604 | SmallVector<Value *, 16> WorkList(1, Start); |
| 605 | Explored.insert(Base); |
| 606 | |
| 607 | // The following traversal gives us an order which can be used |
| 608 | // when doing the final transformation. Since in the final |
| 609 | // transformation we create the PHI replacement instructions first, |
| 610 | // we don't have to get them in any particular order. |
| 611 | // |
| 612 | // However, for other instructions we will have to traverse the |
| 613 | // operands of an instruction first, which means that we have to |
| 614 | // do a post-order traversal. |
| 615 | while (!WorkList.empty()) { |
| 616 | SetVector<PHINode *> PHIs; |
| 617 | |
| 618 | while (!WorkList.empty()) { |
| 619 | if (Explored.size() >= 100) |
| 620 | return false; |
| 621 | |
| 622 | Value *V = WorkList.back(); |
| 623 | |
| 624 | if (Explored.count(V) != 0) { |
| 625 | WorkList.pop_back(); |
| 626 | continue; |
| 627 | } |
| 628 | |
| 629 | if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) && |
David Majnemer | 8b16da8 | 2016-09-15 20:10:09 +0000 | [diff] [blame] | 630 | !isa<GetElementPtrInst>(V) && !isa<PHINode>(V)) |
Silviu Baranga | f29dfd3 | 2016-01-15 15:52:05 +0000 | [diff] [blame] | 631 | // We've found some value that we can't explore which is different from |
| 632 | // the base. Therefore we can't do this transformation. |
| 633 | return false; |
| 634 | |
| 635 | if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) { |
| 636 | auto *CI = dyn_cast<CastInst>(V); |
| 637 | if (!CI->isNoopCast(DL)) |
| 638 | return false; |
| 639 | |
| 640 | if (Explored.count(CI->getOperand(0)) == 0) |
| 641 | WorkList.push_back(CI->getOperand(0)); |
| 642 | } |
| 643 | |
| 644 | if (auto *GEP = dyn_cast<GEPOperator>(V)) { |
| 645 | // We're limiting the GEP to having one index. This will preserve |
| 646 | // the original pointer type. We could handle more cases in the |
| 647 | // future. |
| 648 | if (GEP->getNumIndices() != 1 || !GEP->isInBounds() || |
| 649 | GEP->getType() != Start->getType()) |
| 650 | return false; |
| 651 | |
| 652 | if (Explored.count(GEP->getOperand(0)) == 0) |
| 653 | WorkList.push_back(GEP->getOperand(0)); |
| 654 | } |
| 655 | |
| 656 | if (WorkList.back() == V) { |
| 657 | WorkList.pop_back(); |
| 658 | // We've finished visiting this node, mark it as such. |
| 659 | Explored.insert(V); |
| 660 | } |
| 661 | |
| 662 | if (auto *PN = dyn_cast<PHINode>(V)) { |
David Majnemer | cdf2873 | 2016-03-19 04:39:52 +0000 | [diff] [blame] | 663 | // We cannot transform PHIs on unsplittable basic blocks. |
| 664 | if (isa<CatchSwitchInst>(PN->getParent()->getTerminator())) |
| 665 | return false; |
Silviu Baranga | f29dfd3 | 2016-01-15 15:52:05 +0000 | [diff] [blame] | 666 | Explored.insert(PN); |
| 667 | PHIs.insert(PN); |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | // Explore the PHI nodes further. |
| 672 | for (auto *PN : PHIs) |
| 673 | for (Value *Op : PN->incoming_values()) |
| 674 | if (Explored.count(Op) == 0) |
| 675 | WorkList.push_back(Op); |
| 676 | } |
| 677 | |
| 678 | // Make sure that we can do this. Since we can't insert GEPs in a basic |
| 679 | // block before a PHI node, we can't easily do this transformation if |
| 680 | // we have PHI node users of transformed instructions. |
| 681 | for (Value *Val : Explored) { |
| 682 | for (Value *Use : Val->uses()) { |
| 683 | |
| 684 | auto *PHI = dyn_cast<PHINode>(Use); |
| 685 | auto *Inst = dyn_cast<Instruction>(Val); |
| 686 | |
| 687 | if (Inst == Base || Inst == PHI || !Inst || !PHI || |
| 688 | Explored.count(PHI) == 0) |
| 689 | continue; |
| 690 | |
| 691 | if (PHI->getParent() == Inst->getParent()) |
| 692 | return false; |
| 693 | } |
| 694 | } |
| 695 | return true; |
| 696 | } |
| 697 | |
| 698 | // Sets the appropriate insert point on Builder where we can add |
| 699 | // a replacement Instruction for V (if that is possible). |
| 700 | static void setInsertionPoint(IRBuilder<> &Builder, Value *V, |
| 701 | bool Before = true) { |
| 702 | if (auto *PHI = dyn_cast<PHINode>(V)) { |
| 703 | Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt()); |
| 704 | return; |
| 705 | } |
| 706 | if (auto *I = dyn_cast<Instruction>(V)) { |
| 707 | if (!Before) |
| 708 | I = &*std::next(I->getIterator()); |
| 709 | Builder.SetInsertPoint(I); |
| 710 | return; |
| 711 | } |
| 712 | if (auto *A = dyn_cast<Argument>(V)) { |
| 713 | // Set the insertion point in the entry block. |
| 714 | BasicBlock &Entry = A->getParent()->getEntryBlock(); |
| 715 | Builder.SetInsertPoint(&*Entry.getFirstInsertionPt()); |
| 716 | return; |
| 717 | } |
| 718 | // Otherwise, this is a constant and we don't need to set a new |
| 719 | // insertion point. |
| 720 | assert(isa<Constant>(V) && "Setting insertion point for unknown value!"); |
| 721 | } |
| 722 | |
| 723 | /// Returns a re-written value of Start as an indexed GEP using Base as a |
| 724 | /// pointer. |
| 725 | static Value *rewriteGEPAsOffset(Value *Start, Value *Base, |
| 726 | const DataLayout &DL, |
| 727 | SetVector<Value *> &Explored) { |
| 728 | // Perform all the substitutions. This is a bit tricky because we can |
| 729 | // have cycles in our use-def chains. |
| 730 | // 1. Create the PHI nodes without any incoming values. |
| 731 | // 2. Create all the other values. |
| 732 | // 3. Add the edges for the PHI nodes. |
| 733 | // 4. Emit GEPs to get the original pointers. |
| 734 | // 5. Remove the original instructions. |
| 735 | Type *IndexType = IntegerType::get( |
| 736 | Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType())); |
| 737 | |
| 738 | DenseMap<Value *, Value *> NewInsts; |
| 739 | NewInsts[Base] = ConstantInt::getNullValue(IndexType); |
| 740 | |
| 741 | // Create the new PHI nodes, without adding any incoming values. |
| 742 | for (Value *Val : Explored) { |
| 743 | if (Val == Base) |
| 744 | continue; |
| 745 | // Create empty phi nodes. This avoids cyclic dependencies when creating |
| 746 | // the remaining instructions. |
| 747 | if (auto *PHI = dyn_cast<PHINode>(Val)) |
| 748 | NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(), |
| 749 | PHI->getName() + ".idx", PHI); |
| 750 | } |
| 751 | IRBuilder<> Builder(Base->getContext()); |
| 752 | |
| 753 | // Create all the other instructions. |
| 754 | for (Value *Val : Explored) { |
| 755 | |
| 756 | if (NewInsts.find(Val) != NewInsts.end()) |
| 757 | continue; |
| 758 | |
| 759 | if (auto *CI = dyn_cast<CastInst>(Val)) { |
| 760 | NewInsts[CI] = NewInsts[CI->getOperand(0)]; |
| 761 | continue; |
| 762 | } |
| 763 | if (auto *GEP = dyn_cast<GEPOperator>(Val)) { |
| 764 | Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)] |
| 765 | : GEP->getOperand(1); |
| 766 | setInsertionPoint(Builder, GEP); |
| 767 | // Indices might need to be sign extended. GEPs will magically do |
| 768 | // this, but we need to do it ourselves here. |
| 769 | if (Index->getType()->getScalarSizeInBits() != |
| 770 | NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) { |
| 771 | Index = Builder.CreateSExtOrTrunc( |
| 772 | Index, NewInsts[GEP->getOperand(0)]->getType(), |
| 773 | GEP->getOperand(0)->getName() + ".sext"); |
| 774 | } |
| 775 | |
| 776 | auto *Op = NewInsts[GEP->getOperand(0)]; |
| 777 | if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero()) |
| 778 | NewInsts[GEP] = Index; |
| 779 | else |
| 780 | NewInsts[GEP] = Builder.CreateNSWAdd( |
| 781 | Op, Index, GEP->getOperand(0)->getName() + ".add"); |
| 782 | continue; |
| 783 | } |
| 784 | if (isa<PHINode>(Val)) |
| 785 | continue; |
| 786 | |
| 787 | llvm_unreachable("Unexpected instruction type"); |
| 788 | } |
| 789 | |
| 790 | // Add the incoming values to the PHI nodes. |
| 791 | for (Value *Val : Explored) { |
| 792 | if (Val == Base) |
| 793 | continue; |
| 794 | // All the instructions have been created, we can now add edges to the |
| 795 | // phi nodes. |
| 796 | if (auto *PHI = dyn_cast<PHINode>(Val)) { |
| 797 | PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]); |
| 798 | for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) { |
| 799 | Value *NewIncoming = PHI->getIncomingValue(I); |
| 800 | |
| 801 | if (NewInsts.find(NewIncoming) != NewInsts.end()) |
| 802 | NewIncoming = NewInsts[NewIncoming]; |
| 803 | |
| 804 | NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I)); |
| 805 | } |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | for (Value *Val : Explored) { |
| 810 | if (Val == Base) |
| 811 | continue; |
| 812 | |
| 813 | // Depending on the type, for external users we have to emit |
| 814 | // a GEP or a GEP + ptrtoint. |
| 815 | setInsertionPoint(Builder, Val, false); |
| 816 | |
| 817 | // If required, create an inttoptr instruction for Base. |
| 818 | Value *NewBase = Base; |
| 819 | if (!Base->getType()->isPointerTy()) |
| 820 | NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(), |
| 821 | Start->getName() + "to.ptr"); |
| 822 | |
| 823 | Value *GEP = Builder.CreateInBoundsGEP( |
| 824 | Start->getType()->getPointerElementType(), NewBase, |
| 825 | makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr"); |
| 826 | |
| 827 | if (!Val->getType()->isPointerTy()) { |
| 828 | Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(), |
| 829 | Val->getName() + ".conv"); |
| 830 | GEP = Cast; |
| 831 | } |
| 832 | Val->replaceAllUsesWith(GEP); |
| 833 | } |
| 834 | |
| 835 | return NewInsts[Start]; |
| 836 | } |
| 837 | |
| 838 | /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express |
| 839 | /// the input Value as a constant indexed GEP. Returns a pair containing |
| 840 | /// the GEPs Pointer and Index. |
| 841 | static std::pair<Value *, Value *> |
| 842 | getAsConstantIndexedAddress(Value *V, const DataLayout &DL) { |
| 843 | Type *IndexType = IntegerType::get(V->getContext(), |
| 844 | DL.getPointerTypeSizeInBits(V->getType())); |
| 845 | |
| 846 | Constant *Index = ConstantInt::getNullValue(IndexType); |
| 847 | while (true) { |
| 848 | if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { |
| 849 | // We accept only inbouds GEPs here to exclude the possibility of |
| 850 | // overflow. |
| 851 | if (!GEP->isInBounds()) |
| 852 | break; |
| 853 | if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 && |
| 854 | GEP->getType() == V->getType()) { |
| 855 | V = GEP->getOperand(0); |
| 856 | Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1)); |
| 857 | Index = ConstantExpr::getAdd( |
| 858 | Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType)); |
| 859 | continue; |
| 860 | } |
| 861 | break; |
| 862 | } |
| 863 | if (auto *CI = dyn_cast<IntToPtrInst>(V)) { |
| 864 | if (!CI->isNoopCast(DL)) |
| 865 | break; |
| 866 | V = CI->getOperand(0); |
| 867 | continue; |
| 868 | } |
| 869 | if (auto *CI = dyn_cast<PtrToIntInst>(V)) { |
| 870 | if (!CI->isNoopCast(DL)) |
| 871 | break; |
| 872 | V = CI->getOperand(0); |
| 873 | continue; |
| 874 | } |
| 875 | break; |
| 876 | } |
| 877 | return {V, Index}; |
| 878 | } |
| 879 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 880 | /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant. |
| 881 | /// We can look through PHIs, GEPs and casts in order to determine a common base |
| 882 | /// between GEPLHS and RHS. |
Silviu Baranga | f29dfd3 | 2016-01-15 15:52:05 +0000 | [diff] [blame] | 883 | static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, |
| 884 | ICmpInst::Predicate Cond, |
| 885 | const DataLayout &DL) { |
| 886 | if (!GEPLHS->hasAllConstantIndices()) |
| 887 | return nullptr; |
| 888 | |
Silviu Baranga | c6d21eb | 2017-01-31 14:04:15 +0000 | [diff] [blame] | 889 | // Make sure the pointers have the same type. |
| 890 | if (GEPLHS->getType() != RHS->getType()) |
| 891 | return nullptr; |
| 892 | |
Silviu Baranga | f29dfd3 | 2016-01-15 15:52:05 +0000 | [diff] [blame] | 893 | Value *PtrBase, *Index; |
| 894 | std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL); |
| 895 | |
| 896 | // The set of nodes that will take part in this transformation. |
| 897 | SetVector<Value *> Nodes; |
| 898 | |
| 899 | if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes)) |
| 900 | return nullptr; |
| 901 | |
| 902 | // We know we can re-write this as |
| 903 | // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) |
| 904 | // Since we've only looked through inbouds GEPs we know that we |
| 905 | // can't have overflow on either side. We can therefore re-write |
| 906 | // this as: |
| 907 | // OFFSET1 cmp OFFSET2 |
| 908 | Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes); |
| 909 | |
| 910 | // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written |
| 911 | // GEP having PtrBase as the pointer base, and has returned in NewRHS the |
| 912 | // offset. Since Index is the offset of LHS to the base pointer, we will now |
| 913 | // compare the offsets instead of comparing the pointers. |
| 914 | return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS); |
| 915 | } |
| 916 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 917 | /// Fold comparisons between a GEP instruction and something else. At this point |
| 918 | /// we know that the GEP is on the LHS of the comparison. |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 919 | Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 920 | ICmpInst::Predicate Cond, |
| 921 | Instruction &I) { |
Benjamin Kramer | 6ee8690 | 2012-02-21 13:31:09 +0000 | [diff] [blame] | 922 | // Don't transform signed compares of GEPs into index compares. Even if the |
| 923 | // GEP is inbounds, the final add of the base pointer can have signed overflow |
| 924 | // and would change the result of the icmp. |
| 925 | // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be |
Benjamin Kramer | c7a22fe | 2012-02-21 13:40:06 +0000 | [diff] [blame] | 926 | // the maximum signed value for the pointer type. |
Benjamin Kramer | 6ee8690 | 2012-02-21 13:31:09 +0000 | [diff] [blame] | 927 | if (ICmpInst::isSigned(Cond)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 928 | return nullptr; |
Benjamin Kramer | 6ee8690 | 2012-02-21 13:31:09 +0000 | [diff] [blame] | 929 | |
Matt Arsenault | 44f60d0 | 2014-06-09 19:20:29 +0000 | [diff] [blame] | 930 | // Look through bitcasts and addrspacecasts. We do not however want to remove |
| 931 | // 0 GEPs. |
| 932 | if (!isa<GetElementPtrInst>(RHS)) |
| 933 | RHS = RHS->stripPointerCasts(); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 934 | |
| 935 | Value *PtrBase = GEPLHS->getOperand(0); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 936 | if (PtrBase == RHS && GEPLHS->isInBounds()) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 937 | // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0). |
| 938 | // This transformation (ignoring the base and scales) is valid because we |
| 939 | // know pointers can't overflow since the gep is inbounds. See if we can |
| 940 | // output an optimized form. |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 941 | Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 942 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 943 | // If not, synthesize the offset the hard way. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 944 | if (!Offset) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 945 | Offset = EmitGEPOffset(GEPLHS); |
| 946 | return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset, |
| 947 | Constant::getNullValue(Offset->getType())); |
| 948 | } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) { |
| 949 | // If the base pointers are different, but the indices are the same, just |
| 950 | // compare the base pointer. |
| 951 | if (PtrBase != GEPRHS->getOperand(0)) { |
| 952 | bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands(); |
| 953 | IndicesTheSame &= GEPLHS->getOperand(0)->getType() == |
| 954 | GEPRHS->getOperand(0)->getType(); |
| 955 | if (IndicesTheSame) |
| 956 | for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) |
| 957 | if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { |
| 958 | IndicesTheSame = false; |
| 959 | break; |
| 960 | } |
| 961 | |
| 962 | // If all indices are the same, just compare the base pointers. |
| 963 | if (IndicesTheSame) |
David Majnemer | 5953d37 | 2013-06-29 10:28:04 +0000 | [diff] [blame] | 964 | return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0)); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 965 | |
Benjamin Kramer | 7adb189 | 2012-02-20 15:07:47 +0000 | [diff] [blame] | 966 | // If we're comparing GEPs with two base pointers that only differ in type |
| 967 | // and both GEPs have only constant indices or just one use, then fold |
| 968 | // the compare with the adjusted indices. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 969 | if (GEPLHS->isInBounds() && GEPRHS->isInBounds() && |
Benjamin Kramer | 7adb189 | 2012-02-20 15:07:47 +0000 | [diff] [blame] | 970 | (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) && |
| 971 | (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) && |
| 972 | PtrBase->stripPointerCasts() == |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 973 | GEPRHS->getOperand(0)->stripPointerCasts()) { |
Matt Arsenault | 44f60d0 | 2014-06-09 19:20:29 +0000 | [diff] [blame] | 974 | Value *LOffset = EmitGEPOffset(GEPLHS); |
| 975 | Value *ROffset = EmitGEPOffset(GEPRHS); |
| 976 | |
| 977 | // If we looked through an addrspacecast between different sized address |
| 978 | // spaces, the LHS and RHS pointers are different sized |
| 979 | // integers. Truncate to the smaller one. |
| 980 | Type *LHSIndexTy = LOffset->getType(); |
| 981 | Type *RHSIndexTy = ROffset->getType(); |
| 982 | if (LHSIndexTy != RHSIndexTy) { |
| 983 | if (LHSIndexTy->getPrimitiveSizeInBits() < |
| 984 | RHSIndexTy->getPrimitiveSizeInBits()) { |
| 985 | ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy); |
| 986 | } else |
| 987 | LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy); |
| 988 | } |
| 989 | |
Benjamin Kramer | 7adb189 | 2012-02-20 15:07:47 +0000 | [diff] [blame] | 990 | Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond), |
Matt Arsenault | 44f60d0 | 2014-06-09 19:20:29 +0000 | [diff] [blame] | 991 | LOffset, ROffset); |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 992 | return replaceInstUsesWith(I, Cmp); |
Benjamin Kramer | 7adb189 | 2012-02-20 15:07:47 +0000 | [diff] [blame] | 993 | } |
| 994 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 995 | // Otherwise, the base pointers are different and the indices are |
Silviu Baranga | f29dfd3 | 2016-01-15 15:52:05 +0000 | [diff] [blame] | 996 | // different. Try convert this to an indexed compare by looking through |
| 997 | // PHIs/casts. |
| 998 | return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 999 | } |
| 1000 | |
| 1001 | // If one of the GEPs has all zero indices, recurse. |
Benjamin Kramer | d0993e0 | 2014-07-07 11:01:16 +0000 | [diff] [blame] | 1002 | if (GEPLHS->hasAllZeroIndices()) |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 1003 | return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0), |
David Majnemer | 92a8a7d | 2013-06-29 09:45:35 +0000 | [diff] [blame] | 1004 | ICmpInst::getSwappedPredicate(Cond), I); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1005 | |
| 1006 | // If the other GEP has all zero indices, recurse. |
Benjamin Kramer | d0993e0 | 2014-07-07 11:01:16 +0000 | [diff] [blame] | 1007 | if (GEPRHS->hasAllZeroIndices()) |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 1008 | return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1009 | |
Stuart Hastings | 66a82b9 | 2011-05-14 05:55:10 +0000 | [diff] [blame] | 1010 | bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds(); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1011 | if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) { |
| 1012 | // If the GEPs only differ by one index, compare it. |
| 1013 | unsigned NumDifferences = 0; // Keep track of # differences. |
| 1014 | unsigned DiffOperand = 0; // The operand that differs. |
| 1015 | for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) |
| 1016 | if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { |
| 1017 | if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() != |
| 1018 | GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) { |
| 1019 | // Irreconcilable differences. |
| 1020 | NumDifferences = 2; |
| 1021 | break; |
| 1022 | } else { |
| 1023 | if (NumDifferences++) break; |
| 1024 | DiffOperand = i; |
| 1025 | } |
| 1026 | } |
| 1027 | |
Rafael Espindola | a7bbc0b | 2013-06-06 17:03:05 +0000 | [diff] [blame] | 1028 | if (NumDifferences == 0) // SAME GEP? |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 1029 | return replaceInstUsesWith(I, // No comparison is needed here. |
Jakub Staszak | bddea11 | 2013-06-06 20:18:46 +0000 | [diff] [blame] | 1030 | Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond))); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1031 | |
Stuart Hastings | 66a82b9 | 2011-05-14 05:55:10 +0000 | [diff] [blame] | 1032 | else if (NumDifferences == 1 && GEPsInBounds) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1033 | Value *LHSV = GEPLHS->getOperand(DiffOperand); |
| 1034 | Value *RHSV = GEPRHS->getOperand(DiffOperand); |
| 1035 | // Make sure we do a signed comparison here. |
| 1036 | return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV); |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | // Only lower this if the icmp is the only user of the GEP or if we expect |
| 1041 | // the result to fold to a constant! |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1042 | if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) && |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1043 | (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) { |
| 1044 | // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2) |
| 1045 | Value *L = EmitGEPOffset(GEPLHS); |
| 1046 | Value *R = EmitGEPOffset(GEPRHS); |
| 1047 | return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R); |
| 1048 | } |
| 1049 | } |
Silviu Baranga | f29dfd3 | 2016-01-15 15:52:05 +0000 | [diff] [blame] | 1050 | |
| 1051 | // Try convert this to an indexed compare by looking through PHIs/casts as a |
| 1052 | // last resort. |
| 1053 | return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1054 | } |
| 1055 | |
Pete Cooper | 980a935 | 2016-08-12 17:13:28 +0000 | [diff] [blame] | 1056 | Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI, |
| 1057 | const AllocaInst *Alloca, |
| 1058 | const Value *Other) { |
Hans Wennborg | f1f3651 | 2015-10-07 00:20:07 +0000 | [diff] [blame] | 1059 | assert(ICI.isEquality() && "Cannot fold non-equality comparison."); |
| 1060 | |
| 1061 | // It would be tempting to fold away comparisons between allocas and any |
| 1062 | // pointer not based on that alloca (e.g. an argument). However, even |
| 1063 | // though such pointers cannot alias, they can still compare equal. |
| 1064 | // |
| 1065 | // But LLVM doesn't specify where allocas get their memory, so if the alloca |
| 1066 | // doesn't escape we can argue that it's impossible to guess its value, and we |
| 1067 | // can therefore act as if any such guesses are wrong. |
| 1068 | // |
| 1069 | // The code below checks that the alloca doesn't escape, and that it's only |
| 1070 | // used in a comparison once (the current instruction). The |
| 1071 | // single-comparison-use condition ensures that we're trivially folding all |
| 1072 | // comparisons against the alloca consistently, and avoids the risk of |
| 1073 | // erroneously folding a comparison of the pointer with itself. |
| 1074 | |
| 1075 | unsigned MaxIter = 32; // Break cycles and bound to constant-time. |
| 1076 | |
Pete Cooper | 980a935 | 2016-08-12 17:13:28 +0000 | [diff] [blame] | 1077 | SmallVector<const Use *, 32> Worklist; |
| 1078 | for (const Use &U : Alloca->uses()) { |
Hans Wennborg | f1f3651 | 2015-10-07 00:20:07 +0000 | [diff] [blame] | 1079 | if (Worklist.size() >= MaxIter) |
| 1080 | return nullptr; |
| 1081 | Worklist.push_back(&U); |
| 1082 | } |
| 1083 | |
| 1084 | unsigned NumCmps = 0; |
| 1085 | while (!Worklist.empty()) { |
| 1086 | assert(Worklist.size() <= MaxIter); |
Pete Cooper | 980a935 | 2016-08-12 17:13:28 +0000 | [diff] [blame] | 1087 | const Use *U = Worklist.pop_back_val(); |
| 1088 | const Value *V = U->getUser(); |
Hans Wennborg | f1f3651 | 2015-10-07 00:20:07 +0000 | [diff] [blame] | 1089 | --MaxIter; |
| 1090 | |
| 1091 | if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) || |
| 1092 | isa<SelectInst>(V)) { |
| 1093 | // Track the uses. |
| 1094 | } else if (isa<LoadInst>(V)) { |
| 1095 | // Loading from the pointer doesn't escape it. |
| 1096 | continue; |
Pete Cooper | 980a935 | 2016-08-12 17:13:28 +0000 | [diff] [blame] | 1097 | } else if (const auto *SI = dyn_cast<StoreInst>(V)) { |
Hans Wennborg | f1f3651 | 2015-10-07 00:20:07 +0000 | [diff] [blame] | 1098 | // Storing *to* the pointer is fine, but storing the pointer escapes it. |
| 1099 | if (SI->getValueOperand() == U->get()) |
| 1100 | return nullptr; |
| 1101 | continue; |
| 1102 | } else if (isa<ICmpInst>(V)) { |
| 1103 | if (NumCmps++) |
| 1104 | return nullptr; // Found more than one cmp. |
| 1105 | continue; |
Pete Cooper | 980a935 | 2016-08-12 17:13:28 +0000 | [diff] [blame] | 1106 | } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) { |
Hans Wennborg | f1f3651 | 2015-10-07 00:20:07 +0000 | [diff] [blame] | 1107 | switch (Intrin->getIntrinsicID()) { |
| 1108 | // These intrinsics don't escape or compare the pointer. Memset is safe |
| 1109 | // because we don't allow ptrtoint. Memcpy and memmove are safe because |
| 1110 | // we don't allow stores, so src cannot point to V. |
| 1111 | case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: |
| 1112 | case Intrinsic::dbg_declare: case Intrinsic::dbg_value: |
| 1113 | case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset: |
| 1114 | continue; |
| 1115 | default: |
| 1116 | return nullptr; |
| 1117 | } |
| 1118 | } else { |
| 1119 | return nullptr; |
| 1120 | } |
Pete Cooper | 980a935 | 2016-08-12 17:13:28 +0000 | [diff] [blame] | 1121 | for (const Use &U : V->uses()) { |
Hans Wennborg | f1f3651 | 2015-10-07 00:20:07 +0000 | [diff] [blame] | 1122 | if (Worklist.size() >= MaxIter) |
| 1123 | return nullptr; |
| 1124 | Worklist.push_back(&U); |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | Type *CmpTy = CmpInst::makeCmpResultType(Other->getType()); |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 1129 | return replaceInstUsesWith( |
Hans Wennborg | f1f3651 | 2015-10-07 00:20:07 +0000 | [diff] [blame] | 1130 | ICI, |
| 1131 | ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate()))); |
| 1132 | } |
| 1133 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 1134 | /// Fold "icmp pred (X+CI), X". |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 1135 | Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI, |
| 1136 | Value *X, ConstantInt *CI, |
| 1137 | ICmpInst::Predicate Pred) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1138 | // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0, |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 1139 | // so the values can never be equal. Similarly for all other "or equals" |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1140 | // operators. |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 1141 | |
Chris Lattner | 8c92b57 | 2010-01-08 17:48:19 +0000 | [diff] [blame] | 1142 | // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255 |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1143 | // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253 |
| 1144 | // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0 |
| 1145 | if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) { |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 1146 | Value *R = |
Chris Lattner | 8c92b57 | 2010-01-08 17:48:19 +0000 | [diff] [blame] | 1147 | ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1148 | return new ICmpInst(ICmpInst::ICMP_UGT, X, R); |
| 1149 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 1150 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1151 | // (X+1) >u X --> X <u (0-1) --> X != 255 |
| 1152 | // (X+2) >u X --> X <u (0-2) --> X <u 254 |
| 1153 | // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0 |
Duncan Sands | e522001 | 2011-02-17 07:46:37 +0000 | [diff] [blame] | 1154 | if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1155 | return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI)); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 1156 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1157 | unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits(); |
| 1158 | ConstantInt *SMax = ConstantInt::get(X->getContext(), |
| 1159 | APInt::getSignedMaxValue(BitWidth)); |
| 1160 | |
| 1161 | // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127 |
| 1162 | // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125 |
| 1163 | // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0 |
| 1164 | // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1 |
| 1165 | // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126 |
| 1166 | // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127 |
Duncan Sands | e522001 | 2011-02-17 07:46:37 +0000 | [diff] [blame] | 1167 | if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1168 | return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI)); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 1169 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1170 | // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127 |
| 1171 | // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126 |
| 1172 | // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1 |
| 1173 | // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2 |
| 1174 | // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126 |
| 1175 | // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128 |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 1176 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1177 | assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE); |
Jakub Staszak | bddea11 | 2013-06-06 20:18:46 +0000 | [diff] [blame] | 1178 | Constant *C = Builder->getInt(CI->getValue()-1); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1179 | return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C)); |
| 1180 | } |
| 1181 | |
Sanjay Patel | 8da42cc | 2016-09-15 22:26:31 +0000 | [diff] [blame] | 1182 | /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" -> |
| 1183 | /// (icmp eq/ne A, Log2(AP2/AP1)) -> |
| 1184 | /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)). |
| 1185 | Instruction *InstCombiner::foldICmpShrConstConst(ICmpInst &I, Value *A, |
| 1186 | const APInt &AP1, |
| 1187 | const APInt &AP2) { |
Suyog Sarda | 3a8c2c1 | 2014-07-22 19:19:36 +0000 | [diff] [blame] | 1188 | assert(I.isEquality() && "Cannot fold icmp gt/lt"); |
| 1189 | |
Suyog Sarda | 3a8c2c1 | 2014-07-22 19:19:36 +0000 | [diff] [blame] | 1190 | auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { |
| 1191 | if (I.getPredicate() == I.ICMP_NE) |
| 1192 | Pred = CmpInst::getInversePredicate(Pred); |
| 1193 | return new ICmpInst(Pred, LHS, RHS); |
| 1194 | }; |
| 1195 | |
David Majnemer | 2abb818 | 2014-10-25 07:13:13 +0000 | [diff] [blame] | 1196 | // Don't bother doing any work for cases which InstSimplify handles. |
| 1197 | if (AP2 == 0) |
| 1198 | return nullptr; |
Sanjay Patel | 8da42cc | 2016-09-15 22:26:31 +0000 | [diff] [blame] | 1199 | |
| 1200 | bool IsAShr = isa<AShrOperator>(I.getOperand(0)); |
David Majnemer | 2abb818 | 2014-10-25 07:13:13 +0000 | [diff] [blame] | 1201 | if (IsAShr) { |
| 1202 | if (AP2.isAllOnesValue()) |
| 1203 | return nullptr; |
| 1204 | if (AP2.isNegative() != AP1.isNegative()) |
| 1205 | return nullptr; |
| 1206 | if (AP2.sgt(AP1)) |
| 1207 | return nullptr; |
| 1208 | } |
Suyog Sarda | 3a8c2c1 | 2014-07-22 19:19:36 +0000 | [diff] [blame] | 1209 | |
David Majnemer | d205602 | 2014-10-21 19:51:55 +0000 | [diff] [blame] | 1210 | if (!AP1) |
Suyog Sarda | 3a8c2c1 | 2014-07-22 19:19:36 +0000 | [diff] [blame] | 1211 | // 'A' must be large enough to shift out the highest set bit. |
| 1212 | return getICmp(I.ICMP_UGT, A, |
| 1213 | ConstantInt::get(A->getType(), AP2.logBase2())); |
Suyog Sarda | 3a8c2c1 | 2014-07-22 19:19:36 +0000 | [diff] [blame] | 1214 | |
David Majnemer | d205602 | 2014-10-21 19:51:55 +0000 | [diff] [blame] | 1215 | if (AP1 == AP2) |
| 1216 | return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); |
Suyog Sarda | 3a8c2c1 | 2014-07-22 19:19:36 +0000 | [diff] [blame] | 1217 | |
Andrea Di Biagio | 5b92b49 | 2014-09-17 11:32:31 +0000 | [diff] [blame] | 1218 | int Shift; |
David Majnemer | d205602 | 2014-10-21 19:51:55 +0000 | [diff] [blame] | 1219 | if (IsAShr && AP1.isNegative()) |
David Majnemer | e5977eb | 2015-09-19 00:48:26 +0000 | [diff] [blame] | 1220 | Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes(); |
Andrea Di Biagio | 5b92b49 | 2014-09-17 11:32:31 +0000 | [diff] [blame] | 1221 | else |
David Majnemer | e5977eb | 2015-09-19 00:48:26 +0000 | [diff] [blame] | 1222 | Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros(); |
Suyog Sarda | 3a8c2c1 | 2014-07-22 19:19:36 +0000 | [diff] [blame] | 1223 | |
David Majnemer | d205602 | 2014-10-21 19:51:55 +0000 | [diff] [blame] | 1224 | if (Shift > 0) { |
David Majnemer | e5977eb | 2015-09-19 00:48:26 +0000 | [diff] [blame] | 1225 | if (IsAShr && AP1 == AP2.ashr(Shift)) { |
| 1226 | // There are multiple solutions if we are comparing against -1 and the LHS |
David Majnemer | 47ce0b8 | 2015-09-19 00:48:31 +0000 | [diff] [blame] | 1227 | // of the ashr is not a power of two. |
David Majnemer | e5977eb | 2015-09-19 00:48:26 +0000 | [diff] [blame] | 1228 | if (AP1.isAllOnesValue() && !AP2.isPowerOf2()) |
| 1229 | return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift)); |
David Majnemer | d205602 | 2014-10-21 19:51:55 +0000 | [diff] [blame] | 1230 | return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); |
David Majnemer | e5977eb | 2015-09-19 00:48:26 +0000 | [diff] [blame] | 1231 | } else if (AP1 == AP2.lshr(Shift)) { |
| 1232 | return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); |
| 1233 | } |
David Majnemer | d205602 | 2014-10-21 19:51:55 +0000 | [diff] [blame] | 1234 | } |
Sanjay Patel | 524fcdf | 2016-09-15 19:04:55 +0000 | [diff] [blame] | 1235 | |
Suyog Sarda | 3a8c2c1 | 2014-07-22 19:19:36 +0000 | [diff] [blame] | 1236 | // Shifting const2 will never be equal to const1. |
Sanjay Patel | 524fcdf | 2016-09-15 19:04:55 +0000 | [diff] [blame] | 1237 | // FIXME: This should always be handled by InstSimplify? |
| 1238 | auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE); |
| 1239 | return replaceInstUsesWith(I, TorF); |
Suyog Sarda | 3a8c2c1 | 2014-07-22 19:19:36 +0000 | [diff] [blame] | 1240 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 1241 | |
Sanjay Patel | 8da42cc | 2016-09-15 22:26:31 +0000 | [diff] [blame] | 1242 | /// Handle "(icmp eq/ne (shl AP2, A), AP1)" -> |
| 1243 | /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)). |
| 1244 | Instruction *InstCombiner::foldICmpShlConstConst(ICmpInst &I, Value *A, |
| 1245 | const APInt &AP1, |
| 1246 | const APInt &AP2) { |
David Majnemer | 59939ac | 2014-10-19 08:23:08 +0000 | [diff] [blame] | 1247 | assert(I.isEquality() && "Cannot fold icmp gt/lt"); |
| 1248 | |
David Majnemer | 59939ac | 2014-10-19 08:23:08 +0000 | [diff] [blame] | 1249 | auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { |
| 1250 | if (I.getPredicate() == I.ICMP_NE) |
| 1251 | Pred = CmpInst::getInversePredicate(Pred); |
| 1252 | return new ICmpInst(Pred, LHS, RHS); |
| 1253 | }; |
| 1254 | |
David Majnemer | 2abb818 | 2014-10-25 07:13:13 +0000 | [diff] [blame] | 1255 | // Don't bother doing any work for cases which InstSimplify handles. |
| 1256 | if (AP2 == 0) |
| 1257 | return nullptr; |
David Majnemer | 59939ac | 2014-10-19 08:23:08 +0000 | [diff] [blame] | 1258 | |
| 1259 | unsigned AP2TrailingZeros = AP2.countTrailingZeros(); |
| 1260 | |
| 1261 | if (!AP1 && AP2TrailingZeros != 0) |
Sanjay Patel | af91d1f | 2016-09-15 21:35:30 +0000 | [diff] [blame] | 1262 | return getICmp( |
| 1263 | I.ICMP_UGE, A, |
| 1264 | ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros)); |
David Majnemer | 59939ac | 2014-10-19 08:23:08 +0000 | [diff] [blame] | 1265 | |
| 1266 | if (AP1 == AP2) |
| 1267 | return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); |
| 1268 | |
| 1269 | // Get the distance between the lowest bits that are set. |
| 1270 | int Shift = AP1.countTrailingZeros() - AP2TrailingZeros; |
| 1271 | |
| 1272 | if (Shift > 0 && AP2.shl(Shift) == AP1) |
| 1273 | return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); |
| 1274 | |
| 1275 | // Shifting const2 will never be equal to const1. |
Sanjay Patel | 524fcdf | 2016-09-15 19:04:55 +0000 | [diff] [blame] | 1276 | // FIXME: This should always be handled by InstSimplify? |
| 1277 | auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE); |
| 1278 | return replaceInstUsesWith(I, TorF); |
David Majnemer | 59939ac | 2014-10-19 08:23:08 +0000 | [diff] [blame] | 1279 | } |
| 1280 | |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 1281 | /// The caller has matched a pattern of the form: |
| 1282 | /// I = icmp ugt (add (add A, B), CI2), CI1 |
| 1283 | /// If this is of the form: |
| 1284 | /// sum = a + b |
| 1285 | /// if (sum+128 >u 255) |
| 1286 | /// Then replace it with llvm.sadd.with.overflow.i8. |
| 1287 | /// |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 1288 | static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 1289 | ConstantInt *CI2, ConstantInt *CI1, |
| 1290 | InstCombiner &IC) { |
| 1291 | // The transformation we're trying to do here is to transform this into an |
| 1292 | // llvm.sadd.with.overflow. To do this, we have to replace the original add |
| 1293 | // with a narrower add, and discard the add-with-constant that is part of the |
| 1294 | // range check (if we can't eliminate it, this isn't profitable). |
| 1295 | |
| 1296 | // In order to eliminate the add-with-constant, the compare can be its only |
| 1297 | // use. |
| 1298 | Instruction *AddWithCst = cast<Instruction>(I.getOperand(0)); |
| 1299 | if (!AddWithCst->hasOneUse()) |
| 1300 | return nullptr; |
| 1301 | |
| 1302 | // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow. |
| 1303 | if (!CI2->getValue().isPowerOf2()) |
| 1304 | return nullptr; |
| 1305 | unsigned NewWidth = CI2->getValue().countTrailingZeros(); |
| 1306 | if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) |
| 1307 | return nullptr; |
| 1308 | |
| 1309 | // The width of the new add formed is 1 more than the bias. |
| 1310 | ++NewWidth; |
| 1311 | |
| 1312 | // Check to see that CI1 is an all-ones value with NewWidth bits. |
| 1313 | if (CI1->getBitWidth() == NewWidth || |
| 1314 | CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth)) |
| 1315 | return nullptr; |
| 1316 | |
| 1317 | // This is only really a signed overflow check if the inputs have been |
| 1318 | // sign-extended; check for that condition. For example, if CI2 is 2^31 and |
| 1319 | // the operands of the add are 64 bits wide, we need at least 33 sign bits. |
| 1320 | unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1; |
| 1321 | if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits || |
| 1322 | IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits) |
| 1323 | return nullptr; |
| 1324 | |
| 1325 | // In order to replace the original add with a narrower |
| 1326 | // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant |
| 1327 | // and truncates that discard the high bits of the add. Verify that this is |
| 1328 | // the case. |
| 1329 | Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0)); |
| 1330 | for (User *U : OrigAdd->users()) { |
| 1331 | if (U == AddWithCst) |
| 1332 | continue; |
| 1333 | |
| 1334 | // Only accept truncates for now. We would really like a nice recursive |
| 1335 | // predicate like SimplifyDemandedBits, but which goes downwards the use-def |
| 1336 | // chain to see which bits of a value are actually demanded. If the |
| 1337 | // original add had another add which was then immediately truncated, we |
| 1338 | // could still do the transformation. |
| 1339 | TruncInst *TI = dyn_cast<TruncInst>(U); |
| 1340 | if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth) |
| 1341 | return nullptr; |
| 1342 | } |
| 1343 | |
| 1344 | // If the pattern matches, truncate the inputs to the narrower type and |
| 1345 | // use the sadd_with_overflow intrinsic to efficiently compute both the |
| 1346 | // result and the overflow bit. |
| 1347 | Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth); |
| 1348 | Value *F = Intrinsic::getDeclaration(I.getModule(), |
| 1349 | Intrinsic::sadd_with_overflow, NewType); |
| 1350 | |
| 1351 | InstCombiner::BuilderTy *Builder = IC.Builder; |
| 1352 | |
| 1353 | // Put the new code above the original add, in case there are any uses of the |
| 1354 | // add between the add and the compare. |
| 1355 | Builder->SetInsertPoint(OrigAdd); |
| 1356 | |
| 1357 | Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName() + ".trunc"); |
| 1358 | Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName() + ".trunc"); |
| 1359 | CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd"); |
| 1360 | Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result"); |
| 1361 | Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType()); |
| 1362 | |
| 1363 | // The inner add was the result of the narrow add, zero extended to the |
| 1364 | // wider type. Replace it with the result computed by the intrinsic. |
| 1365 | IC.replaceInstUsesWith(*OrigAdd, ZExt); |
| 1366 | |
| 1367 | // The original icmp gets replaced with the overflow value. |
| 1368 | return ExtractValueInst::Create(Call, 1, "sadd.overflow"); |
| 1369 | } |
| 1370 | |
| 1371 | // Fold icmp Pred X, C. |
Sanjay Patel | 9745983 | 2016-09-15 15:11:12 +0000 | [diff] [blame] | 1372 | Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &Cmp) { |
| 1373 | CmpInst::Predicate Pred = Cmp.getPredicate(); |
Sanjay Patel | 40c53ea | 2016-09-15 16:23:20 +0000 | [diff] [blame] | 1374 | Value *X = Cmp.getOperand(0); |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 1375 | |
Sanjay Patel | 40c53ea | 2016-09-15 16:23:20 +0000 | [diff] [blame] | 1376 | const APInt *C; |
| 1377 | if (!match(Cmp.getOperand(1), m_APInt(C))) |
Sanjay Patel | 9745983 | 2016-09-15 15:11:12 +0000 | [diff] [blame] | 1378 | return nullptr; |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 1379 | |
Sanjay Patel | 9745983 | 2016-09-15 15:11:12 +0000 | [diff] [blame] | 1380 | Value *A = nullptr, *B = nullptr; |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 1381 | |
Sanjay Patel | 9745983 | 2016-09-15 15:11:12 +0000 | [diff] [blame] | 1382 | // Match the following pattern, which is a common idiom when writing |
| 1383 | // overflow-safe integer arithmetic functions. The source performs an addition |
| 1384 | // in wider type and explicitly checks for overflow using comparisons against |
| 1385 | // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic. |
| 1386 | // |
| 1387 | // TODO: This could probably be generalized to handle other overflow-safe |
| 1388 | // operations if we worked out the formulas to compute the appropriate magic |
| 1389 | // constants. |
| 1390 | // |
| 1391 | // sum = a + b |
| 1392 | // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8 |
| 1393 | { |
| 1394 | ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI |
| 1395 | if (Pred == ICmpInst::ICMP_UGT && |
| 1396 | match(X, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2)))) |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 1397 | if (Instruction *Res = processUGT_ADDCST_ADD( |
Sanjay Patel | 40c53ea | 2016-09-15 16:23:20 +0000 | [diff] [blame] | 1398 | Cmp, A, B, CI2, cast<ConstantInt>(Cmp.getOperand(1)), *this)) |
Sanjay Patel | 9745983 | 2016-09-15 15:11:12 +0000 | [diff] [blame] | 1399 | return Res; |
| 1400 | } |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 1401 | |
Sanjay Patel | 9745983 | 2016-09-15 15:11:12 +0000 | [diff] [blame] | 1402 | // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0) |
Sanjay Patel | 40c53ea | 2016-09-15 16:23:20 +0000 | [diff] [blame] | 1403 | if (*C == 0 && Pred == ICmpInst::ICMP_SGT) { |
| 1404 | SelectPatternResult SPR = matchSelectPattern(X, A, B); |
| 1405 | if (SPR.Flavor == SPF_SMIN) { |
| 1406 | if (isKnownPositive(A, DL)) |
| 1407 | return new ICmpInst(Pred, B, Cmp.getOperand(1)); |
| 1408 | if (isKnownPositive(B, DL)) |
| 1409 | return new ICmpInst(Pred, A, Cmp.getOperand(1)); |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 1410 | } |
Sanjay Patel | 40c53ea | 2016-09-15 16:23:20 +0000 | [diff] [blame] | 1411 | } |
| 1412 | |
| 1413 | // FIXME: Use m_APInt to allow folds for splat constants. |
| 1414 | ConstantInt *CI = dyn_cast<ConstantInt>(Cmp.getOperand(1)); |
| 1415 | if (!CI) |
| 1416 | return nullptr; |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 1417 | |
Sanjay Patel | 9745983 | 2016-09-15 15:11:12 +0000 | [diff] [blame] | 1418 | // Canonicalize icmp instructions based on dominating conditions. |
| 1419 | BasicBlock *Parent = Cmp.getParent(); |
| 1420 | BasicBlock *Dom = Parent->getSinglePredecessor(); |
| 1421 | auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr; |
| 1422 | ICmpInst::Predicate Pred2; |
| 1423 | BasicBlock *TrueBB, *FalseBB; |
| 1424 | ConstantInt *CI2; |
| 1425 | if (BI && match(BI, m_Br(m_ICmp(Pred2, m_Specific(X), m_ConstantInt(CI2)), |
| 1426 | TrueBB, FalseBB)) && |
| 1427 | TrueBB != FalseBB) { |
| 1428 | ConstantRange CR = |
| 1429 | ConstantRange::makeAllowedICmpRegion(Pred, CI->getValue()); |
| 1430 | ConstantRange DominatingCR = |
| 1431 | (Parent == TrueBB) |
| 1432 | ? ConstantRange::makeExactICmpRegion(Pred2, CI2->getValue()) |
| 1433 | : ConstantRange::makeExactICmpRegion( |
| 1434 | CmpInst::getInversePredicate(Pred2), CI2->getValue()); |
| 1435 | ConstantRange Intersection = DominatingCR.intersectWith(CR); |
| 1436 | ConstantRange Difference = DominatingCR.difference(CR); |
| 1437 | if (Intersection.isEmptySet()) |
| 1438 | return replaceInstUsesWith(Cmp, Builder->getFalse()); |
| 1439 | if (Difference.isEmptySet()) |
| 1440 | return replaceInstUsesWith(Cmp, Builder->getTrue()); |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 1441 | |
Sanjay Patel | 9745983 | 2016-09-15 15:11:12 +0000 | [diff] [blame] | 1442 | // If this is a normal comparison, it demands all bits. If it is a sign |
| 1443 | // bit comparison, it only demands the sign bit. |
| 1444 | bool UnusedBit; |
| 1445 | bool IsSignBit = isSignBitCheck(Pred, CI->getValue(), UnusedBit); |
| 1446 | |
| 1447 | // Canonicalizing a sign bit comparison that gets used in a branch, |
| 1448 | // pessimizes codegen by generating branch on zero instruction instead |
| 1449 | // of a test and branch. So we avoid canonicalizing in such situations |
| 1450 | // because test and branch instruction has better branch displacement |
| 1451 | // than compare and branch instruction. |
| 1452 | if (!isBranchOnSignBitCheck(Cmp, IsSignBit) && !Cmp.isEquality()) { |
| 1453 | if (auto *AI = Intersection.getSingleElement()) |
| 1454 | return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder->getInt(*AI)); |
| 1455 | if (auto *AD = Difference.getSingleElement()) |
| 1456 | return new ICmpInst(ICmpInst::ICMP_NE, X, Builder->getInt(*AD)); |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 1457 | } |
| 1458 | } |
| 1459 | |
| 1460 | return nullptr; |
| 1461 | } |
| 1462 | |
Sanjay Patel | 5f4ce4e | 2016-08-18 20:25:16 +0000 | [diff] [blame] | 1463 | /// Fold icmp (trunc X, Y), C. |
| 1464 | Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp, |
| 1465 | Instruction *Trunc, |
| 1466 | const APInt *C) { |
Sanjay Patel | 5f4ce4e | 2016-08-18 20:25:16 +0000 | [diff] [blame] | 1467 | ICmpInst::Predicate Pred = Cmp.getPredicate(); |
| 1468 | Value *X = Trunc->getOperand(0); |
Sanjay Patel | 40e8ca4 | 2016-08-18 20:28:54 +0000 | [diff] [blame] | 1469 | if (*C == 1 && C->getBitWidth() > 1) { |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1470 | // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1 |
| 1471 | Value *V = nullptr; |
Sanjay Patel | 5f4ce4e | 2016-08-18 20:25:16 +0000 | [diff] [blame] | 1472 | if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V)))) |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1473 | return new ICmpInst(ICmpInst::ICMP_SLT, V, |
| 1474 | ConstantInt::get(V->getType(), 1)); |
| 1475 | } |
Sanjay Patel | 5f4ce4e | 2016-08-18 20:25:16 +0000 | [diff] [blame] | 1476 | |
| 1477 | if (Cmp.isEquality() && Trunc->hasOneUse()) { |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1478 | // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all |
| 1479 | // of the high bits truncated out of x are known. |
Sanjay Patel | 40e8ca4 | 2016-08-18 20:28:54 +0000 | [diff] [blame] | 1480 | unsigned DstBits = Trunc->getType()->getScalarSizeInBits(), |
| 1481 | SrcBits = X->getType()->getScalarSizeInBits(); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1482 | APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0); |
Sanjay Patel | 5f4ce4e | 2016-08-18 20:25:16 +0000 | [diff] [blame] | 1483 | computeKnownBits(X, KnownZero, KnownOne, 0, &Cmp); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1484 | |
| 1485 | // If all the high bits are known, we can do this xform. |
| 1486 | if ((KnownZero | KnownOne).countLeadingOnes() >= SrcBits - DstBits) { |
| 1487 | // Pull in the high bits from known-ones set. |
Sanjay Patel | 5f4ce4e | 2016-08-18 20:25:16 +0000 | [diff] [blame] | 1488 | APInt NewRHS = C->zext(SrcBits); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1489 | NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits); |
Sanjay Patel | 40e8ca4 | 2016-08-18 20:28:54 +0000 | [diff] [blame] | 1490 | return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS)); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1491 | } |
| 1492 | } |
Sanjay Patel | 5f4ce4e | 2016-08-18 20:25:16 +0000 | [diff] [blame] | 1493 | |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1494 | return nullptr; |
| 1495 | } |
| 1496 | |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1497 | /// Fold icmp (xor X, Y), C. |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 1498 | Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp, |
| 1499 | BinaryOperator *Xor, |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1500 | const APInt *C) { |
Sanjay Patel | 4c5e60d | 2016-08-18 14:10:48 +0000 | [diff] [blame] | 1501 | Value *X = Xor->getOperand(0); |
| 1502 | Value *Y = Xor->getOperand(1); |
Sanjay Patel | daffec91 | 2016-08-17 19:45:18 +0000 | [diff] [blame] | 1503 | const APInt *XorC; |
Sanjay Patel | 4c5e60d | 2016-08-18 14:10:48 +0000 | [diff] [blame] | 1504 | if (!match(Y, m_APInt(XorC))) |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1505 | return nullptr; |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1506 | |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1507 | // If this is a comparison that tests the signbit (X < 0) or (x > -1), |
| 1508 | // fold the xor. |
| 1509 | ICmpInst::Predicate Pred = Cmp.getPredicate(); |
| 1510 | if ((Pred == ICmpInst::ICMP_SLT && *C == 0) || |
| 1511 | (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())) { |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1512 | |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1513 | // If the sign bit of the XorCst is not set, there is no change to |
| 1514 | // the operation, just stop using the Xor. |
Sanjay Patel | daffec91 | 2016-08-17 19:45:18 +0000 | [diff] [blame] | 1515 | if (!XorC->isNegative()) { |
| 1516 | Cmp.setOperand(0, X); |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1517 | Worklist.Add(Xor); |
| 1518 | return &Cmp; |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1519 | } |
| 1520 | |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1521 | // Was the old condition true if the operand is positive? |
| 1522 | bool isTrueIfPositive = Pred == ICmpInst::ICMP_SGT; |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1523 | |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1524 | // If so, the new one isn't. |
| 1525 | isTrueIfPositive ^= true; |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1526 | |
Sanjay Patel | 4c5e60d | 2016-08-18 14:10:48 +0000 | [diff] [blame] | 1527 | Constant *CmpConstant = cast<Constant>(Cmp.getOperand(1)); |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1528 | if (isTrueIfPositive) |
Sanjay Patel | 4c5e60d | 2016-08-18 14:10:48 +0000 | [diff] [blame] | 1529 | return new ICmpInst(ICmpInst::ICMP_SGT, X, SubOne(CmpConstant)); |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1530 | else |
Sanjay Patel | 4c5e60d | 2016-08-18 14:10:48 +0000 | [diff] [blame] | 1531 | return new ICmpInst(ICmpInst::ICMP_SLT, X, AddOne(CmpConstant)); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1532 | } |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1533 | |
| 1534 | if (Xor->hasOneUse()) { |
Sanjay Patel | daffec91 | 2016-08-17 19:45:18 +0000 | [diff] [blame] | 1535 | // (icmp u/s (xor X SignBit), C) -> (icmp s/u X, (xor C SignBit)) |
| 1536 | if (!Cmp.isEquality() && XorC->isSignBit()) { |
| 1537 | Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate() |
| 1538 | : Cmp.getSignedPredicate(); |
Sanjay Patel | 4c5e60d | 2016-08-18 14:10:48 +0000 | [diff] [blame] | 1539 | return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC)); |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1540 | } |
| 1541 | |
Sanjay Patel | daffec91 | 2016-08-17 19:45:18 +0000 | [diff] [blame] | 1542 | // (icmp u/s (xor X ~SignBit), C) -> (icmp s/u X, (xor C ~SignBit)) |
| 1543 | if (!Cmp.isEquality() && XorC->isMaxSignedValue()) { |
| 1544 | Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate() |
| 1545 | : Cmp.getSignedPredicate(); |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1546 | Pred = Cmp.getSwappedPredicate(Pred); |
Sanjay Patel | 4c5e60d | 2016-08-18 14:10:48 +0000 | [diff] [blame] | 1547 | return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC)); |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1548 | } |
| 1549 | } |
| 1550 | |
| 1551 | // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C) |
| 1552 | // iff -C is a power of 2 |
Sanjay Patel | daffec91 | 2016-08-17 19:45:18 +0000 | [diff] [blame] | 1553 | if (Pred == ICmpInst::ICMP_UGT && *XorC == ~(*C) && (*C + 1).isPowerOf2()) |
Sanjay Patel | 4c5e60d | 2016-08-18 14:10:48 +0000 | [diff] [blame] | 1554 | return new ICmpInst(ICmpInst::ICMP_ULT, X, Y); |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1555 | |
| 1556 | // (icmp ult (xor X, C), -C) -> (icmp uge X, C) |
| 1557 | // iff -C is a power of 2 |
Sanjay Patel | daffec91 | 2016-08-17 19:45:18 +0000 | [diff] [blame] | 1558 | if (Pred == ICmpInst::ICMP_ULT && *XorC == -(*C) && C->isPowerOf2()) |
Sanjay Patel | 4c5e60d | 2016-08-18 14:10:48 +0000 | [diff] [blame] | 1559 | return new ICmpInst(ICmpInst::ICMP_UGE, X, Y); |
Sanjay Patel | 6d5f448 | 2016-08-17 19:23:42 +0000 | [diff] [blame] | 1560 | |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1561 | return nullptr; |
| 1562 | } |
| 1563 | |
Sanjay Patel | 14e0e18 | 2016-08-26 18:28:46 +0000 | [diff] [blame] | 1564 | /// Fold icmp (and (sh X, Y), C2), C1. |
| 1565 | Instruction *InstCombiner::foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And, |
Sanjay Patel | 9b40f98 | 2016-09-07 22:33:03 +0000 | [diff] [blame] | 1566 | const APInt *C1, const APInt *C2) { |
| 1567 | BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0)); |
| 1568 | if (!Shift || !Shift->isShift()) |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1569 | return nullptr; |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1570 | |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1571 | // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could |
| 1572 | // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in |
| 1573 | // code produced by the clang front-end, for bitfield access. |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1574 | // This seemingly simple opportunity to fold away a shift turns out to be |
| 1575 | // rather complicated. See PR17827 for details. |
Sanjay Patel | 9b40f98 | 2016-09-07 22:33:03 +0000 | [diff] [blame] | 1576 | unsigned ShiftOpcode = Shift->getOpcode(); |
| 1577 | bool IsShl = ShiftOpcode == Instruction::Shl; |
| 1578 | const APInt *C3; |
| 1579 | if (match(Shift->getOperand(1), m_APInt(C3))) { |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1580 | bool CanFold = false; |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1581 | if (ShiftOpcode == Instruction::AShr) { |
| 1582 | // There may be some constraints that make this possible, but nothing |
| 1583 | // simple has been discovered yet. |
| 1584 | CanFold = false; |
| 1585 | } else if (ShiftOpcode == Instruction::Shl) { |
| 1586 | // For a left shift, we can fold if the comparison is not signed. We can |
| 1587 | // also fold a signed comparison if the mask value and comparison value |
| 1588 | // are not negative. These constraints may not be obvious, but we can |
| 1589 | // prove that they are correct using an SMT solver. |
Sanjay Patel | 9b40f98 | 2016-09-07 22:33:03 +0000 | [diff] [blame] | 1590 | if (!Cmp.isSigned() || (!C2->isNegative() && !C1->isNegative())) |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1591 | CanFold = true; |
| 1592 | } else if (ShiftOpcode == Instruction::LShr) { |
| 1593 | // For a logical right shift, we can fold if the comparison is not signed. |
| 1594 | // We can also fold a signed comparison if the shifted mask value and the |
| 1595 | // shifted comparison value are not negative. These constraints may not be |
| 1596 | // obvious, but we can prove that they are correct using an SMT solver. |
Sanjay Patel | 9b40f98 | 2016-09-07 22:33:03 +0000 | [diff] [blame] | 1597 | if (!Cmp.isSigned() || |
| 1598 | (!C2->shl(*C3).isNegative() && !C1->shl(*C3).isNegative())) |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1599 | CanFold = true; |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1600 | } |
| 1601 | |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1602 | if (CanFold) { |
Sanjay Patel | 9b40f98 | 2016-09-07 22:33:03 +0000 | [diff] [blame] | 1603 | APInt NewCst = IsShl ? C1->lshr(*C3) : C1->shl(*C3); |
| 1604 | APInt SameAsC1 = IsShl ? NewCst.shl(*C3) : NewCst.lshr(*C3); |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1605 | // Check to see if we are shifting out any of the bits being compared. |
Sanjay Patel | 9b40f98 | 2016-09-07 22:33:03 +0000 | [diff] [blame] | 1606 | if (SameAsC1 != *C1) { |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1607 | // If we shifted bits out, the fold is not going to work out. As a |
| 1608 | // special case, check to see if this means that the result is always |
| 1609 | // true or false now. |
| 1610 | if (Cmp.getPredicate() == ICmpInst::ICMP_EQ) |
Sanjay Patel | 1c608f4 | 2016-09-08 16:54:02 +0000 | [diff] [blame] | 1611 | return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType())); |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1612 | if (Cmp.getPredicate() == ICmpInst::ICMP_NE) |
Sanjay Patel | 1c608f4 | 2016-09-08 16:54:02 +0000 | [diff] [blame] | 1613 | return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType())); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1614 | } else { |
Sanjay Patel | 9b40f98 | 2016-09-07 22:33:03 +0000 | [diff] [blame] | 1615 | Cmp.setOperand(1, ConstantInt::get(And->getType(), NewCst)); |
| 1616 | APInt NewAndCst = IsShl ? C2->lshr(*C3) : C2->shl(*C3); |
| 1617 | And->setOperand(1, ConstantInt::get(And->getType(), NewAndCst)); |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1618 | And->setOperand(0, Shift->getOperand(0)); |
| 1619 | Worklist.Add(Shift); // Shift is dead. |
| 1620 | return &Cmp; |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1621 | } |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1622 | } |
| 1623 | } |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1624 | |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1625 | // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is |
| 1626 | // preferable because it allows the C2 << Y expression to be hoisted out of a |
| 1627 | // loop if Y is invariant and X is not. |
Sanjay Patel | 14e0e18 | 2016-08-26 18:28:46 +0000 | [diff] [blame] | 1628 | if (Shift->hasOneUse() && *C1 == 0 && Cmp.isEquality() && |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1629 | !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) { |
| 1630 | // Compute C2 << Y. |
Sanjay Patel | 9b40f98 | 2016-09-07 22:33:03 +0000 | [diff] [blame] | 1631 | Value *NewShift = |
| 1632 | IsShl ? Builder->CreateLShr(And->getOperand(1), Shift->getOperand(1)) |
| 1633 | : Builder->CreateShl(And->getOperand(1), Shift->getOperand(1)); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1634 | |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1635 | // Compute X & (C2 << Y). |
Sanjay Patel | 9b40f98 | 2016-09-07 22:33:03 +0000 | [diff] [blame] | 1636 | Value *NewAnd = Builder->CreateAnd(Shift->getOperand(0), NewShift); |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1637 | Cmp.setOperand(0, NewAnd); |
| 1638 | return &Cmp; |
| 1639 | } |
| 1640 | |
Sanjay Patel | 14e0e18 | 2016-08-26 18:28:46 +0000 | [diff] [blame] | 1641 | return nullptr; |
| 1642 | } |
| 1643 | |
| 1644 | /// Fold icmp (and X, C2), C1. |
| 1645 | Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp, |
| 1646 | BinaryOperator *And, |
| 1647 | const APInt *C1) { |
Sanjay Patel | 6b49097 | 2016-09-04 14:32:15 +0000 | [diff] [blame] | 1648 | const APInt *C2; |
| 1649 | if (!match(And->getOperand(1), m_APInt(C2))) |
Sanjay Patel | 14e0e18 | 2016-08-26 18:28:46 +0000 | [diff] [blame] | 1650 | return nullptr; |
| 1651 | |
| 1652 | if (!And->hasOneUse() || !And->getOperand(0)->hasOneUse()) |
| 1653 | return nullptr; |
| 1654 | |
Sanjay Patel | 6b49097 | 2016-09-04 14:32:15 +0000 | [diff] [blame] | 1655 | // If the LHS is an 'and' of a truncate and we can widen the and/compare to |
| 1656 | // the input width without changing the value produced, eliminate the cast: |
| 1657 | // |
| 1658 | // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1' |
| 1659 | // |
| 1660 | // We can do this transformation if the constants do not have their sign bits |
| 1661 | // set or if it is an equality comparison. Extending a relational comparison |
| 1662 | // when we're checking the sign bit would not work. |
| 1663 | Value *W; |
| 1664 | if (match(And->getOperand(0), m_Trunc(m_Value(W))) && |
| 1665 | (Cmp.isEquality() || (!C1->isNegative() && !C2->isNegative()))) { |
| 1666 | // TODO: Is this a good transform for vectors? Wider types may reduce |
| 1667 | // throughput. Should this transform be limited (even for scalars) by using |
Sanjay Patel | 2217f75 | 2017-01-31 17:25:42 +0000 | [diff] [blame] | 1668 | // shouldChangeType()? |
Sanjay Patel | 6b49097 | 2016-09-04 14:32:15 +0000 | [diff] [blame] | 1669 | if (!Cmp.getType()->isVectorTy()) { |
| 1670 | Type *WideType = W->getType(); |
| 1671 | unsigned WideScalarBits = WideType->getScalarSizeInBits(); |
| 1672 | Constant *ZextC1 = ConstantInt::get(WideType, C1->zext(WideScalarBits)); |
| 1673 | Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits)); |
| 1674 | Value *NewAnd = Builder->CreateAnd(W, ZextC2, And->getName()); |
| 1675 | return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1); |
Sanjay Patel | 14e0e18 | 2016-08-26 18:28:46 +0000 | [diff] [blame] | 1676 | } |
| 1677 | } |
| 1678 | |
Sanjay Patel | 9b40f98 | 2016-09-07 22:33:03 +0000 | [diff] [blame] | 1679 | if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2)) |
Sanjay Patel | 14e0e18 | 2016-08-26 18:28:46 +0000 | [diff] [blame] | 1680 | return I; |
| 1681 | |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1682 | // (icmp pred (and (or (lshr A, B), A), 1), 0) --> |
Sanjay Patel | 6b49097 | 2016-09-04 14:32:15 +0000 | [diff] [blame] | 1683 | // (icmp pred (and A, (or (shl 1, B), 1), 0)) |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1684 | // |
| 1685 | // iff pred isn't signed |
Sanjay Patel | def931e | 2016-09-07 20:50:44 +0000 | [diff] [blame] | 1686 | if (!Cmp.isSigned() && *C1 == 0 && match(And->getOperand(1), m_One())) { |
| 1687 | Constant *One = cast<Constant>(And->getOperand(1)); |
| 1688 | Value *Or = And->getOperand(0); |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1689 | Value *A, *B, *LShr; |
Sanjay Patel | def931e | 2016-09-07 20:50:44 +0000 | [diff] [blame] | 1690 | if (match(Or, m_Or(m_Value(LShr), m_Value(A))) && |
| 1691 | match(LShr, m_LShr(m_Specific(A), m_Value(B)))) { |
| 1692 | unsigned UsesRemoved = 0; |
| 1693 | if (And->hasOneUse()) |
| 1694 | ++UsesRemoved; |
| 1695 | if (Or->hasOneUse()) |
| 1696 | ++UsesRemoved; |
| 1697 | if (LShr->hasOneUse()) |
| 1698 | ++UsesRemoved; |
| 1699 | |
| 1700 | // Compute A & ((1 << B) | 1) |
| 1701 | Value *NewOr = nullptr; |
| 1702 | if (auto *C = dyn_cast<Constant>(B)) { |
| 1703 | if (UsesRemoved >= 1) |
| 1704 | NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One); |
| 1705 | } else { |
| 1706 | if (UsesRemoved >= 3) |
| 1707 | NewOr = Builder->CreateOr(Builder->CreateShl(One, B, LShr->getName(), |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1708 | /*HasNUW=*/true), |
| 1709 | One, Or->getName()); |
Sanjay Patel | def931e | 2016-09-07 20:50:44 +0000 | [diff] [blame] | 1710 | } |
| 1711 | if (NewOr) { |
| 1712 | Value *NewAnd = Builder->CreateAnd(A, NewOr, And->getName()); |
| 1713 | Cmp.setOperand(0, NewAnd); |
| 1714 | return &Cmp; |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1715 | } |
| 1716 | } |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1717 | } |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1718 | |
Sanjay Patel | def931e | 2016-09-07 20:50:44 +0000 | [diff] [blame] | 1719 | // (X & C2) > C1 --> (X & C2) != 0, if any bit set in (X & C2) will produce a |
| 1720 | // result greater than C1. |
| 1721 | unsigned NumTZ = C2->countTrailingZeros(); |
| 1722 | if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && NumTZ < C2->getBitWidth() && |
| 1723 | APInt::getOneBitSet(C2->getBitWidth(), NumTZ).ugt(*C1)) { |
| 1724 | Constant *Zero = Constant::getNullValue(And->getType()); |
| 1725 | return new ICmpInst(ICmpInst::ICMP_NE, And, Zero); |
Sanjay Patel | da9c562 | 2016-08-26 17:15:22 +0000 | [diff] [blame] | 1726 | } |
| 1727 | |
Sanjay Patel | d3c7bb28 | 2016-08-26 16:42:33 +0000 | [diff] [blame] | 1728 | return nullptr; |
| 1729 | } |
| 1730 | |
| 1731 | /// Fold icmp (and X, Y), C. |
| 1732 | Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp, |
| 1733 | BinaryOperator *And, |
| 1734 | const APInt *C) { |
| 1735 | if (Instruction *I = foldICmpAndConstConst(Cmp, And, C)) |
| 1736 | return I; |
| 1737 | |
Sanjay Patel | 5c5311f | 2016-08-28 18:18:00 +0000 | [diff] [blame] | 1738 | // TODO: These all require that Y is constant too, so refactor with the above. |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1739 | |
Sanjay Patel | 5c5311f | 2016-08-28 18:18:00 +0000 | [diff] [blame] | 1740 | // Try to optimize things like "A[i] & 42 == 0" to index computations. |
| 1741 | Value *X = And->getOperand(0); |
| 1742 | Value *Y = And->getOperand(1); |
| 1743 | if (auto *LI = dyn_cast<LoadInst>(X)) |
| 1744 | if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) |
| 1745 | if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1746 | if (GV->isConstant() && GV->hasDefinitiveInitializer() && |
Sanjay Patel | 5c5311f | 2016-08-28 18:18:00 +0000 | [diff] [blame] | 1747 | !LI->isVolatile() && isa<ConstantInt>(Y)) { |
| 1748 | ConstantInt *C2 = cast<ConstantInt>(Y); |
| 1749 | if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2)) |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1750 | return Res; |
| 1751 | } |
Sanjay Patel | 5c5311f | 2016-08-28 18:18:00 +0000 | [diff] [blame] | 1752 | |
| 1753 | if (!Cmp.isEquality()) |
| 1754 | return nullptr; |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1755 | |
| 1756 | // X & -C == -C -> X > u ~C |
| 1757 | // X & -C != -C -> X <= u ~C |
| 1758 | // iff C is a power of 2 |
Sanjay Patel | 5c5311f | 2016-08-28 18:18:00 +0000 | [diff] [blame] | 1759 | if (Cmp.getOperand(1) == Y && (-(*C)).isPowerOf2()) { |
| 1760 | auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT |
| 1761 | : CmpInst::ICMP_ULE; |
| 1762 | return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1)))); |
| 1763 | } |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1764 | |
Sanjay Patel | 5c5311f | 2016-08-28 18:18:00 +0000 | [diff] [blame] | 1765 | // (X & C2) == 0 -> (trunc X) >= 0 |
| 1766 | // (X & C2) != 0 -> (trunc X) < 0 |
| 1767 | // iff C2 is a power of 2 and it masks the sign bit of a legal integer type. |
| 1768 | const APInt *C2; |
| 1769 | if (And->hasOneUse() && *C == 0 && match(Y, m_APInt(C2))) { |
| 1770 | int32_t ExactLogBase2 = C2->exactLogBase2(); |
| 1771 | if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) { |
| 1772 | Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1); |
| 1773 | if (And->getType()->isVectorTy()) |
| 1774 | NTy = VectorType::get(NTy, And->getType()->getVectorNumElements()); |
| 1775 | Value *Trunc = Builder->CreateTrunc(X, NTy); |
| 1776 | auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE |
| 1777 | : CmpInst::ICMP_SLT; |
| 1778 | return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy)); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1779 | } |
| 1780 | } |
Sanjay Patel | 5c5311f | 2016-08-28 18:18:00 +0000 | [diff] [blame] | 1781 | |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1782 | return nullptr; |
| 1783 | } |
| 1784 | |
Sanjay Patel | 943e92e | 2016-08-17 16:30:43 +0000 | [diff] [blame] | 1785 | /// Fold icmp (or X, Y), C. |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 1786 | Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or, |
Sanjay Patel | 943e92e | 2016-08-17 16:30:43 +0000 | [diff] [blame] | 1787 | const APInt *C) { |
Sanjay Patel | 943e92e | 2016-08-17 16:30:43 +0000 | [diff] [blame] | 1788 | ICmpInst::Predicate Pred = Cmp.getPredicate(); |
| 1789 | if (*C == 1) { |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1790 | // icmp slt signum(V) 1 --> icmp slt V, 1 |
| 1791 | Value *V = nullptr; |
Sanjay Patel | 943e92e | 2016-08-17 16:30:43 +0000 | [diff] [blame] | 1792 | if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V)))) |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1793 | return new ICmpInst(ICmpInst::ICMP_SLT, V, |
| 1794 | ConstantInt::get(V->getType(), 1)); |
| 1795 | } |
| 1796 | |
Sanjay Patel | 943e92e | 2016-08-17 16:30:43 +0000 | [diff] [blame] | 1797 | if (!Cmp.isEquality() || *C != 0 || !Or->hasOneUse()) |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1798 | return nullptr; |
| 1799 | |
| 1800 | Value *P, *Q; |
Sanjay Patel | 943e92e | 2016-08-17 16:30:43 +0000 | [diff] [blame] | 1801 | if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) { |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1802 | // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0 |
| 1803 | // -> and (icmp eq P, null), (icmp eq Q, null). |
Reid Kleckner | a871d38 | 2016-08-19 16:53:18 +0000 | [diff] [blame] | 1804 | Value *CmpP = |
| 1805 | Builder->CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType())); |
| 1806 | Value *CmpQ = |
| 1807 | Builder->CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType())); |
Sanjay Patel | 943e92e | 2016-08-17 16:30:43 +0000 | [diff] [blame] | 1808 | auto LogicOpc = Pred == ICmpInst::Predicate::ICMP_EQ ? Instruction::And |
| 1809 | : Instruction::Or; |
| 1810 | return BinaryOperator::Create(LogicOpc, CmpP, CmpQ); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1811 | } |
Sanjay Patel | 943e92e | 2016-08-17 16:30:43 +0000 | [diff] [blame] | 1812 | |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1813 | return nullptr; |
| 1814 | } |
| 1815 | |
Sanjay Patel | 6347807 | 2016-08-18 15:44:44 +0000 | [diff] [blame] | 1816 | /// Fold icmp (mul X, Y), C. |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 1817 | Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp, |
| 1818 | BinaryOperator *Mul, |
Sanjay Patel | 6347807 | 2016-08-18 15:44:44 +0000 | [diff] [blame] | 1819 | const APInt *C) { |
| 1820 | const APInt *MulC; |
| 1821 | if (!match(Mul->getOperand(1), m_APInt(MulC))) |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1822 | return nullptr; |
| 1823 | |
Sanjay Patel | 6347807 | 2016-08-18 15:44:44 +0000 | [diff] [blame] | 1824 | // If this is a test of the sign bit and the multiply is sign-preserving with |
| 1825 | // a constant operand, use the multiply LHS operand instead. |
| 1826 | ICmpInst::Predicate Pred = Cmp.getPredicate(); |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 1827 | if (isSignTest(Pred, *C) && Mul->hasNoSignedWrap()) { |
Sanjay Patel | 6347807 | 2016-08-18 15:44:44 +0000 | [diff] [blame] | 1828 | if (MulC->isNegative()) |
| 1829 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 1830 | return new ICmpInst(Pred, Mul->getOperand(0), |
| 1831 | Constant::getNullValue(Mul->getType())); |
| 1832 | } |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1833 | |
| 1834 | return nullptr; |
| 1835 | } |
| 1836 | |
Sanjay Patel | 98cd99d | 2016-08-18 21:28:30 +0000 | [diff] [blame] | 1837 | /// Fold icmp (shl 1, Y), C. |
| 1838 | static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl, |
| 1839 | const APInt *C) { |
| 1840 | Value *Y; |
| 1841 | if (!match(Shl, m_Shl(m_One(), m_Value(Y)))) |
| 1842 | return nullptr; |
| 1843 | |
| 1844 | Type *ShiftType = Shl->getType(); |
| 1845 | uint32_t TypeBits = C->getBitWidth(); |
| 1846 | bool CIsPowerOf2 = C->isPowerOf2(); |
| 1847 | ICmpInst::Predicate Pred = Cmp.getPredicate(); |
| 1848 | if (Cmp.isUnsigned()) { |
| 1849 | // (1 << Y) pred C -> Y pred Log2(C) |
| 1850 | if (!CIsPowerOf2) { |
| 1851 | // (1 << Y) < 30 -> Y <= 4 |
| 1852 | // (1 << Y) <= 30 -> Y <= 4 |
| 1853 | // (1 << Y) >= 30 -> Y > 4 |
| 1854 | // (1 << Y) > 30 -> Y > 4 |
| 1855 | if (Pred == ICmpInst::ICMP_ULT) |
| 1856 | Pred = ICmpInst::ICMP_ULE; |
| 1857 | else if (Pred == ICmpInst::ICMP_UGE) |
| 1858 | Pred = ICmpInst::ICMP_UGT; |
| 1859 | } |
| 1860 | |
| 1861 | // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31 |
| 1862 | // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31 |
| 1863 | unsigned CLog2 = C->logBase2(); |
| 1864 | if (CLog2 == TypeBits - 1) { |
| 1865 | if (Pred == ICmpInst::ICMP_UGE) |
| 1866 | Pred = ICmpInst::ICMP_EQ; |
| 1867 | else if (Pred == ICmpInst::ICMP_ULT) |
| 1868 | Pred = ICmpInst::ICMP_NE; |
| 1869 | } |
| 1870 | return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2)); |
| 1871 | } else if (Cmp.isSigned()) { |
| 1872 | Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1); |
| 1873 | if (C->isAllOnesValue()) { |
| 1874 | // (1 << Y) <= -1 -> Y == 31 |
| 1875 | if (Pred == ICmpInst::ICMP_SLE) |
| 1876 | return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne); |
| 1877 | |
| 1878 | // (1 << Y) > -1 -> Y != 31 |
| 1879 | if (Pred == ICmpInst::ICMP_SGT) |
| 1880 | return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne); |
| 1881 | } else if (!(*C)) { |
| 1882 | // (1 << Y) < 0 -> Y == 31 |
| 1883 | // (1 << Y) <= 0 -> Y == 31 |
| 1884 | if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) |
| 1885 | return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne); |
| 1886 | |
| 1887 | // (1 << Y) >= 0 -> Y != 31 |
| 1888 | // (1 << Y) > 0 -> Y != 31 |
| 1889 | if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) |
| 1890 | return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne); |
| 1891 | } |
| 1892 | } else if (Cmp.isEquality() && CIsPowerOf2) { |
| 1893 | return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C->logBase2())); |
| 1894 | } |
| 1895 | |
| 1896 | return nullptr; |
| 1897 | } |
| 1898 | |
Sanjay Patel | 38b7506 | 2016-08-19 17:20:37 +0000 | [diff] [blame] | 1899 | /// Fold icmp (shl X, Y), C. |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 1900 | Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp, |
| 1901 | BinaryOperator *Shl, |
Sanjay Patel | 38b7506 | 2016-08-19 17:20:37 +0000 | [diff] [blame] | 1902 | const APInt *C) { |
Sanjay Patel | 8da42cc | 2016-09-15 22:26:31 +0000 | [diff] [blame] | 1903 | const APInt *ShiftVal; |
| 1904 | if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal))) |
| 1905 | return foldICmpShlConstConst(Cmp, Shl->getOperand(1), *C, *ShiftVal); |
| 1906 | |
Sanjay Patel | fa7de60 | 2016-08-19 22:33:26 +0000 | [diff] [blame] | 1907 | const APInt *ShiftAmt; |
| 1908 | if (!match(Shl->getOperand(1), m_APInt(ShiftAmt))) |
Sanjay Patel | 38b7506 | 2016-08-19 17:20:37 +0000 | [diff] [blame] | 1909 | return foldICmpShlOne(Cmp, Shl, C); |
Sanjay Patel | a867afe | 2016-08-19 16:12:16 +0000 | [diff] [blame] | 1910 | |
Sanjay Patel | 38b7506 | 2016-08-19 17:20:37 +0000 | [diff] [blame] | 1911 | // Check that the shift amount is in range. If not, don't perform undefined |
Sanjay Patel | 940c061 | 2017-01-09 16:27:56 +0000 | [diff] [blame] | 1912 | // shifts. When the shift is visited, it will be simplified. |
Sanjay Patel | 38b7506 | 2016-08-19 17:20:37 +0000 | [diff] [blame] | 1913 | unsigned TypeBits = C->getBitWidth(); |
Sanjay Patel | fa7de60 | 2016-08-19 22:33:26 +0000 | [diff] [blame] | 1914 | if (ShiftAmt->uge(TypeBits)) |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1915 | return nullptr; |
| 1916 | |
Sanjay Patel | e38e79c | 2016-08-19 17:34:05 +0000 | [diff] [blame] | 1917 | ICmpInst::Predicate Pred = Cmp.getPredicate(); |
| 1918 | Value *X = Shl->getOperand(0); |
Sanjay Patel | 14715b3 | 2017-01-17 21:25:16 +0000 | [diff] [blame] | 1919 | Type *ShType = Shl->getType(); |
| 1920 | |
Sanjay Patel | 291c3d8 | 2017-01-19 16:12:10 +0000 | [diff] [blame] | 1921 | // NSW guarantees that we are only shifting out sign bits from the high bits, |
| 1922 | // so we can ASHR the compare constant without needing a mask and eliminate |
| 1923 | // the shift. |
| 1924 | if (Shl->hasNoSignedWrap()) { |
| 1925 | if (Pred == ICmpInst::ICMP_SGT) { |
| 1926 | // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt) |
| 1927 | APInt ShiftedC = C->ashr(*ShiftAmt); |
| 1928 | return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); |
| 1929 | } |
| 1930 | if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) { |
| 1931 | // This is the same code as the SGT case, but assert the pre-condition |
| 1932 | // that is needed for this to work with equality predicates. |
| 1933 | assert(C->ashr(*ShiftAmt).shl(*ShiftAmt) == *C && |
| 1934 | "Compare known true or false was not folded"); |
| 1935 | APInt ShiftedC = C->ashr(*ShiftAmt); |
| 1936 | return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); |
| 1937 | } |
| 1938 | if (Pred == ICmpInst::ICMP_SLT) { |
| 1939 | // SLE is the same as above, but SLE is canonicalized to SLT, so convert: |
| 1940 | // (X << S) <=s C is equiv to X <=s (C >> S) for all C |
| 1941 | // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX |
| 1942 | // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN |
| 1943 | assert(!C->isMinSignedValue() && "Unexpected icmp slt"); |
| 1944 | APInt ShiftedC = (*C - 1).ashr(*ShiftAmt) + 1; |
| 1945 | return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); |
| 1946 | } |
| 1947 | // If this is a signed comparison to 0 and the shift is sign preserving, |
| 1948 | // use the shift LHS operand instead; isSignTest may change 'Pred', so only |
| 1949 | // do that if we're sure to not continue on in this function. |
| 1950 | if (isSignTest(Pred, *C)) |
| 1951 | return new ICmpInst(Pred, X, Constant::getNullValue(ShType)); |
| 1952 | } |
Sanjay Patel | 14715b3 | 2017-01-17 21:25:16 +0000 | [diff] [blame] | 1953 | |
Sanjay Patel | 291c3d8 | 2017-01-19 16:12:10 +0000 | [diff] [blame] | 1954 | // NUW guarantees that we are only shifting out zero bits from the high bits, |
| 1955 | // so we can LSHR the compare constant without needing a mask and eliminate |
| 1956 | // the shift. |
Sanjay Patel | 14715b3 | 2017-01-17 21:25:16 +0000 | [diff] [blame] | 1957 | if (Shl->hasNoUnsignedWrap()) { |
Sanjay Patel | ae23d65 | 2017-01-18 21:16:12 +0000 | [diff] [blame] | 1958 | if (Pred == ICmpInst::ICMP_UGT) { |
Sanjay Patel | 14715b3 | 2017-01-17 21:25:16 +0000 | [diff] [blame] | 1959 | // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt) |
| 1960 | APInt ShiftedC = C->lshr(*ShiftAmt); |
| 1961 | return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); |
| 1962 | } |
Sanjay Patel | ae23d65 | 2017-01-18 21:16:12 +0000 | [diff] [blame] | 1963 | if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) { |
| 1964 | // This is the same code as the UGT case, but assert the pre-condition |
| 1965 | // that is needed for this to work with equality predicates. |
| 1966 | assert(C->lshr(*ShiftAmt).shl(*ShiftAmt) == *C && |
| 1967 | "Compare known true or false was not folded"); |
| 1968 | APInt ShiftedC = C->lshr(*ShiftAmt); |
| 1969 | return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); |
| 1970 | } |
Sanjay Patel | 14715b3 | 2017-01-17 21:25:16 +0000 | [diff] [blame] | 1971 | if (Pred == ICmpInst::ICMP_ULT) { |
| 1972 | // ULE is the same as above, but ULE is canonicalized to ULT, so convert: |
| 1973 | // (X << S) <=u C is equiv to X <=u (C >> S) for all C |
| 1974 | // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u |
| 1975 | // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0 |
| 1976 | assert(C->ugt(0) && "ult 0 should have been eliminated"); |
| 1977 | APInt ShiftedC = (*C - 1).lshr(*ShiftAmt) + 1; |
| 1978 | return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); |
| 1979 | } |
| 1980 | } |
| 1981 | |
Sanjay Patel | 291c3d8 | 2017-01-19 16:12:10 +0000 | [diff] [blame] | 1982 | if (Cmp.isEquality() && Shl->hasOneUse()) { |
| 1983 | // Strength-reduce the shift into an 'and'. |
| 1984 | Constant *Mask = ConstantInt::get( |
| 1985 | ShType, |
| 1986 | APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue())); |
| 1987 | Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask"); |
Sanjay Patel | 14715b3 | 2017-01-17 21:25:16 +0000 | [diff] [blame] | 1988 | Constant *LShrC = ConstantInt::get(ShType, C->lshr(*ShiftAmt)); |
Sanjay Patel | 291c3d8 | 2017-01-19 16:12:10 +0000 | [diff] [blame] | 1989 | return new ICmpInst(Pred, And, LShrC); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1990 | } |
| 1991 | |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1992 | // Otherwise, if this is a comparison of the sign bit, simplify to and/test. |
| 1993 | bool TrueIfSigned = false; |
Sanjay Patel | 7926366 | 2016-08-21 15:07:45 +0000 | [diff] [blame] | 1994 | if (Shl->hasOneUse() && isSignBitCheck(Pred, *C, TrueIfSigned)) { |
Sanjay Patel | 7ffcde7 | 2016-08-21 16:35:34 +0000 | [diff] [blame] | 1995 | // (X << 31) <s 0 --> (X & 1) != 0 |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 1996 | Constant *Mask = ConstantInt::get( |
Sanjay Patel | 14715b3 | 2017-01-17 21:25:16 +0000 | [diff] [blame] | 1997 | ShType, |
Sanjay Patel | fa7de60 | 2016-08-19 22:33:26 +0000 | [diff] [blame] | 1998 | APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1)); |
Sanjay Patel | e38e79c | 2016-08-19 17:34:05 +0000 | [diff] [blame] | 1999 | Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask"); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2000 | return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ, |
Sanjay Patel | 14715b3 | 2017-01-17 21:25:16 +0000 | [diff] [blame] | 2001 | And, Constant::getNullValue(ShType)); |
Sanjay Patel | c0339c7 | 2016-11-01 19:19:29 +0000 | [diff] [blame] | 2002 | } |
| 2003 | |
Sanjay Patel | 643d21a | 2016-08-21 17:10:07 +0000 | [diff] [blame] | 2004 | // Transform (icmp pred iM (shl iM %v, N), C) |
| 2005 | // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N)) |
| 2006 | // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N. |
Sanjay Patel | 940c061 | 2017-01-09 16:27:56 +0000 | [diff] [blame] | 2007 | // This enables us to get rid of the shift in favor of a trunc that may be |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2008 | // free on the target. It has the additional benefit of comparing to a |
Sanjay Patel | 940c061 | 2017-01-09 16:27:56 +0000 | [diff] [blame] | 2009 | // smaller constant that may be more target-friendly. |
Sanjay Patel | fa7de60 | 2016-08-19 22:33:26 +0000 | [diff] [blame] | 2010 | unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1); |
Sanjay Patel | f3dda13 | 2016-10-25 20:11:47 +0000 | [diff] [blame] | 2011 | if (Shl->hasOneUse() && Amt != 0 && C->countTrailingZeros() >= Amt && |
| 2012 | DL.isLegalInteger(TypeBits - Amt)) { |
Sanjay Patel | 643d21a | 2016-08-21 17:10:07 +0000 | [diff] [blame] | 2013 | Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt); |
Sanjay Patel | 14715b3 | 2017-01-17 21:25:16 +0000 | [diff] [blame] | 2014 | if (ShType->isVectorTy()) |
| 2015 | TruncTy = VectorType::get(TruncTy, ShType->getVectorNumElements()); |
Sanjay Patel | 643d21a | 2016-08-21 17:10:07 +0000 | [diff] [blame] | 2016 | Constant *NewC = |
| 2017 | ConstantInt::get(TruncTy, C->ashr(*ShiftAmt).trunc(TypeBits - Amt)); |
| 2018 | return new ICmpInst(Pred, Builder->CreateTrunc(X, TruncTy), NewC); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2019 | } |
| 2020 | |
| 2021 | return nullptr; |
| 2022 | } |
| 2023 | |
Sanjay Patel | a392049 | 2016-08-22 20:45:06 +0000 | [diff] [blame] | 2024 | /// Fold icmp ({al}shr X, Y), C. |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 2025 | Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp, |
| 2026 | BinaryOperator *Shr, |
| 2027 | const APInt *C) { |
Sanjay Patel | a392049 | 2016-08-22 20:45:06 +0000 | [diff] [blame] | 2028 | // An exact shr only shifts out zero bits, so: |
| 2029 | // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0 |
Sanjay Patel | d64e988 | 2016-08-23 22:05:55 +0000 | [diff] [blame] | 2030 | Value *X = Shr->getOperand(0); |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 2031 | CmpInst::Predicate Pred = Cmp.getPredicate(); |
| 2032 | if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() && *C == 0) |
Sanjay Patel | d64e988 | 2016-08-23 22:05:55 +0000 | [diff] [blame] | 2033 | return new ICmpInst(Pred, X, Cmp.getOperand(1)); |
Sanjay Patel | a392049 | 2016-08-22 20:45:06 +0000 | [diff] [blame] | 2034 | |
Sanjay Patel | 8da42cc | 2016-09-15 22:26:31 +0000 | [diff] [blame] | 2035 | const APInt *ShiftVal; |
| 2036 | if (Cmp.isEquality() && match(Shr->getOperand(0), m_APInt(ShiftVal))) |
| 2037 | return foldICmpShrConstConst(Cmp, Shr->getOperand(1), *C, *ShiftVal); |
| 2038 | |
Sanjay Patel | d398d4a | 2016-08-24 22:22:06 +0000 | [diff] [blame] | 2039 | const APInt *ShiftAmt; |
| 2040 | if (!match(Shr->getOperand(1), m_APInt(ShiftAmt))) |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2041 | return nullptr; |
| 2042 | |
Sanjay Patel | d398d4a | 2016-08-24 22:22:06 +0000 | [diff] [blame] | 2043 | // Check that the shift amount is in range. If not, don't perform undefined |
| 2044 | // shifts. When the shift is visited it will be simplified. |
| 2045 | unsigned TypeBits = C->getBitWidth(); |
| 2046 | unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits); |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2047 | if (ShAmtVal >= TypeBits || ShAmtVal == 0) |
| 2048 | return nullptr; |
| 2049 | |
Sanjay Patel | d64e988 | 2016-08-23 22:05:55 +0000 | [diff] [blame] | 2050 | bool IsAShr = Shr->getOpcode() == Instruction::AShr; |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2051 | if (!Cmp.isEquality()) { |
| 2052 | // If we have an unsigned comparison and an ashr, we can't simplify this. |
| 2053 | // Similarly for signed comparisons with lshr. |
Sanjay Patel | d64e988 | 2016-08-23 22:05:55 +0000 | [diff] [blame] | 2054 | if (Cmp.isSigned() != IsAShr) |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2055 | return nullptr; |
| 2056 | |
| 2057 | // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv |
| 2058 | // by a power of 2. Since we already have logic to simplify these, |
| 2059 | // transform to div and then simplify the resultant comparison. |
Sanjay Patel | d64e988 | 2016-08-23 22:05:55 +0000 | [diff] [blame] | 2060 | if (IsAShr && (!Shr->isExact() || ShAmtVal == TypeBits - 1)) |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2061 | return nullptr; |
| 2062 | |
| 2063 | // Revisit the shift (to delete it). |
| 2064 | Worklist.Add(Shr); |
| 2065 | |
| 2066 | Constant *DivCst = ConstantInt::get( |
| 2067 | Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal)); |
| 2068 | |
Sanjay Patel | d64e988 | 2016-08-23 22:05:55 +0000 | [diff] [blame] | 2069 | Value *Tmp = IsAShr ? Builder->CreateSDiv(X, DivCst, "", Shr->isExact()) |
| 2070 | : Builder->CreateUDiv(X, DivCst, "", Shr->isExact()); |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2071 | |
| 2072 | Cmp.setOperand(0, Tmp); |
| 2073 | |
| 2074 | // If the builder folded the binop, just return it. |
| 2075 | BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp); |
| 2076 | if (!TheDiv) |
| 2077 | return &Cmp; |
| 2078 | |
| 2079 | // Otherwise, fold this div/compare. |
| 2080 | assert(TheDiv->getOpcode() == Instruction::SDiv || |
| 2081 | TheDiv->getOpcode() == Instruction::UDiv); |
| 2082 | |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2083 | Instruction *Res = foldICmpDivConstant(Cmp, TheDiv, C); |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2084 | assert(Res && "This div/cst should have folded!"); |
Sanjay Patel | a392049 | 2016-08-22 20:45:06 +0000 | [diff] [blame] | 2085 | return Res; |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2086 | } |
| 2087 | |
Sanjay Patel | d398d4a | 2016-08-24 22:22:06 +0000 | [diff] [blame] | 2088 | // Handle equality comparisons of shift-by-constant. |
| 2089 | |
Sanjay Patel | 8e29774 | 2016-08-24 13:55:55 +0000 | [diff] [blame] | 2090 | // If the comparison constant changes with the shift, the comparison cannot |
| 2091 | // succeed (bits of the comparison constant cannot match the shifted value). |
| 2092 | // This should be known by InstSimplify and already be folded to true/false. |
| 2093 | assert(((IsAShr && C->shl(ShAmtVal).ashr(ShAmtVal) == *C) || |
| 2094 | (!IsAShr && C->shl(ShAmtVal).lshr(ShAmtVal) == *C)) && |
| 2095 | "Expected icmp+shr simplify did not occur."); |
| 2096 | |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2097 | // Check if the bits shifted out are known to be zero. If so, we can compare |
| 2098 | // against the unshifted value: |
| 2099 | // (X & 4) >> 1 == 2 --> (X & 4) == 4. |
Sanjay Patel | d398d4a | 2016-08-24 22:22:06 +0000 | [diff] [blame] | 2100 | Constant *ShiftedCmpRHS = ConstantInt::get(Shr->getType(), *C << ShAmtVal); |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2101 | if (Shr->hasOneUse()) { |
Sanjay Patel | d398d4a | 2016-08-24 22:22:06 +0000 | [diff] [blame] | 2102 | if (Shr->isExact()) |
| 2103 | return new ICmpInst(Pred, X, ShiftedCmpRHS); |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2104 | |
Sanjay Patel | d398d4a | 2016-08-24 22:22:06 +0000 | [diff] [blame] | 2105 | // Otherwise strength reduce the shift into an 'and'. |
| 2106 | APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal)); |
| 2107 | Constant *Mask = ConstantInt::get(Shr->getType(), Val); |
Sanjay Patel | d64e988 | 2016-08-23 22:05:55 +0000 | [diff] [blame] | 2108 | Value *And = Builder->CreateAnd(X, Mask, Shr->getName() + ".mask"); |
Sanjay Patel | dcac0df | 2016-08-23 21:25:13 +0000 | [diff] [blame] | 2109 | return new ICmpInst(Pred, And, ShiftedCmpRHS); |
| 2110 | } |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2111 | |
| 2112 | return nullptr; |
| 2113 | } |
| 2114 | |
Sanjay Patel | 12a4105 | 2016-08-18 17:37:26 +0000 | [diff] [blame] | 2115 | /// Fold icmp (udiv X, Y), C. |
| 2116 | Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp, |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 2117 | BinaryOperator *UDiv, |
Sanjay Patel | 12a4105 | 2016-08-18 17:37:26 +0000 | [diff] [blame] | 2118 | const APInt *C) { |
Sanjay Patel | fa5ca2b | 2016-08-18 17:55:59 +0000 | [diff] [blame] | 2119 | const APInt *C2; |
| 2120 | if (!match(UDiv->getOperand(0), m_APInt(C2))) |
| 2121 | return nullptr; |
| 2122 | |
| 2123 | assert(C2 != 0 && "udiv 0, X should have been simplified already."); |
| 2124 | |
| 2125 | // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1)) |
| 2126 | Value *Y = UDiv->getOperand(1); |
| 2127 | if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) { |
| 2128 | assert(!C->isMaxValue() && |
| 2129 | "icmp ugt X, UINT_MAX should have been simplified already."); |
| 2130 | return new ICmpInst(ICmpInst::ICMP_ULE, Y, |
| 2131 | ConstantInt::get(Y->getType(), C2->udiv(*C + 1))); |
| 2132 | } |
| 2133 | |
| 2134 | // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C) |
| 2135 | if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) { |
| 2136 | assert(C != 0 && "icmp ult X, 0 should have been simplified already."); |
| 2137 | return new ICmpInst(ICmpInst::ICMP_UGT, Y, |
| 2138 | ConstantInt::get(Y->getType(), C2->udiv(*C))); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2139 | } |
| 2140 | |
| 2141 | return nullptr; |
| 2142 | } |
| 2143 | |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2144 | /// Fold icmp ({su}div X, Y), C. |
| 2145 | Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp, |
| 2146 | BinaryOperator *Div, |
| 2147 | const APInt *C) { |
Sanjay Patel | a7cb477 | 2016-08-30 17:10:49 +0000 | [diff] [blame] | 2148 | // Fold: icmp pred ([us]div X, C2), C -> range test |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2149 | // Fold this div into the comparison, producing a range check. |
| 2150 | // Determine, based on the divide type, what the range is being |
| 2151 | // checked. If there is an overflow on the low or high side, remember |
| 2152 | // it, otherwise compute the range [low, hi) bounding the new value. |
| 2153 | // See: InsertRangeTest above for the kinds of replacements possible. |
Sanjay Patel | a7cb477 | 2016-08-30 17:10:49 +0000 | [diff] [blame] | 2154 | const APInt *C2; |
| 2155 | if (!match(Div->getOperand(1), m_APInt(C2))) |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2156 | return nullptr; |
| 2157 | |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2158 | // FIXME: If the operand types don't match the type of the divide |
| 2159 | // then don't attempt this transform. The code below doesn't have the |
| 2160 | // logic to deal with a signed divide and an unsigned compare (and |
Sanjay Patel | a7cb477 | 2016-08-30 17:10:49 +0000 | [diff] [blame] | 2161 | // vice versa). This is because (x /s C2) <s C produces different |
| 2162 | // results than (x /s C2) <u C or (x /u C2) <s C or even |
| 2163 | // (x /u C2) <u C. Simply casting the operands and result won't |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2164 | // work. :( The if statement below tests that condition and bails |
| 2165 | // if it finds it. |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2166 | bool DivIsSigned = Div->getOpcode() == Instruction::SDiv; |
| 2167 | if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2168 | return nullptr; |
Sanjay Patel | a7cb477 | 2016-08-30 17:10:49 +0000 | [diff] [blame] | 2169 | |
Sanjay Patel | eea2ef7 | 2016-09-05 23:38:22 +0000 | [diff] [blame] | 2170 | // The ProdOV computation fails on divide by 0 and divide by -1. Cases with |
| 2171 | // INT_MIN will also fail if the divisor is 1. Although folds of all these |
| 2172 | // division-by-constant cases should be present, we can not assert that they |
| 2173 | // have happened before we reach this icmp instruction. |
| 2174 | if (*C2 == 0 || *C2 == 1 || (DivIsSigned && C2->isAllOnesValue())) |
| 2175 | return nullptr; |
Sanjay Patel | b371457 | 2016-08-30 17:31:34 +0000 | [diff] [blame] | 2176 | |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2177 | // TODO: We could do all of the computations below using APInt. |
| 2178 | Constant *CmpRHS = cast<Constant>(Cmp.getOperand(1)); |
| 2179 | Constant *DivRHS = cast<Constant>(Div->getOperand(1)); |
Sanjay Patel | b371457 | 2016-08-30 17:31:34 +0000 | [diff] [blame] | 2180 | |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2181 | // Compute Prod = CmpRHS * DivRHS. We are essentially solving an equation of |
| 2182 | // form X / C2 = C. We solve for X by multiplying C2 (DivRHS) and C (CmpRHS). |
| 2183 | // By solving for X, we can turn this into a range check instead of computing |
| 2184 | // a divide. |
| 2185 | Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2186 | |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2187 | // Determine if the product overflows by seeing if the product is not equal to |
| 2188 | // the divide. Make sure we do the same kind of divide as in the LHS |
| 2189 | // instruction that we're folding. |
| 2190 | bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) |
| 2191 | : ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS; |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2192 | |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2193 | ICmpInst::Predicate Pred = Cmp.getPredicate(); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2194 | |
| 2195 | // If the division is known to be exact, then there is no remainder from the |
| 2196 | // divide, so the covered range size is unit, otherwise it is the divisor. |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2197 | Constant *RangeSize = |
| 2198 | Div->isExact() ? ConstantInt::get(Div->getType(), 1) : DivRHS; |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2199 | |
| 2200 | // Figure out the interval that is being checked. For example, a comparison |
| 2201 | // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). |
| 2202 | // Compute this interval based on the constants involved and the signedness of |
| 2203 | // the compare/divide. This computes a half-open interval, keeping track of |
| 2204 | // whether either value in the interval overflows. After analysis each |
| 2205 | // overflow variable is set to 0 if it's corresponding bound variable is valid |
| 2206 | // -1 if overflowed off the bottom end, or +1 if overflowed off the top end. |
| 2207 | int LoOverflow = 0, HiOverflow = 0; |
| 2208 | Constant *LoBound = nullptr, *HiBound = nullptr; |
| 2209 | |
| 2210 | if (!DivIsSigned) { // udiv |
| 2211 | // e.g. X/5 op 3 --> [15, 20) |
| 2212 | LoBound = Prod; |
| 2213 | HiOverflow = LoOverflow = ProdOV; |
| 2214 | if (!HiOverflow) { |
| 2215 | // If this is not an exact divide, then many values in the range collapse |
| 2216 | // to the same result value. |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 2217 | HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2218 | } |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2219 | } else if (C2->isStrictlyPositive()) { // Divisor is > 0. |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2220 | if (*C == 0) { // (X / pos) op 0 |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2221 | // Can't overflow. e.g. X/2 op 0 --> [-1, 2) |
| 2222 | LoBound = ConstantExpr::getNeg(SubOne(RangeSize)); |
| 2223 | HiBound = RangeSize; |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2224 | } else if (C->isStrictlyPositive()) { // (X / pos) op pos |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2225 | LoBound = Prod; // e.g. X/5 op 3 --> [15, 20) |
| 2226 | HiOverflow = LoOverflow = ProdOV; |
| 2227 | if (!HiOverflow) |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 2228 | HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2229 | } else { // (X / pos) op neg |
| 2230 | // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14) |
| 2231 | HiBound = AddOne(Prod); |
| 2232 | LoOverflow = HiOverflow = ProdOV ? -1 : 0; |
| 2233 | if (!LoOverflow) { |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2234 | Constant *DivNeg = ConstantExpr::getNeg(RangeSize); |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 2235 | LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0; |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2236 | } |
| 2237 | } |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2238 | } else if (C2->isNegative()) { // Divisor is < 0. |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2239 | if (Div->isExact()) |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2240 | RangeSize = ConstantExpr::getNeg(RangeSize); |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2241 | if (*C == 0) { // (X / neg) op 0 |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2242 | // e.g. X/-5 op 0 --> [-4, 5) |
| 2243 | LoBound = AddOne(RangeSize); |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2244 | HiBound = ConstantExpr::getNeg(RangeSize); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2245 | if (HiBound == DivRHS) { // -INTMIN = INTMIN |
| 2246 | HiOverflow = 1; // [INTMIN+1, overflow) |
| 2247 | HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN |
| 2248 | } |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2249 | } else if (C->isStrictlyPositive()) { // (X / neg) op pos |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2250 | // e.g. X/-5 op 3 --> [-19, -14) |
| 2251 | HiBound = AddOne(Prod); |
| 2252 | HiOverflow = LoOverflow = ProdOV ? -1 : 0; |
| 2253 | if (!LoOverflow) |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 2254 | LoOverflow = addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0; |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2255 | } else { // (X / neg) op neg |
| 2256 | LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20) |
| 2257 | LoOverflow = HiOverflow = ProdOV; |
| 2258 | if (!HiOverflow) |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 2259 | HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2260 | } |
| 2261 | |
| 2262 | // Dividing by a negative swaps the condition. LT <-> GT |
| 2263 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 2264 | } |
| 2265 | |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2266 | Value *X = Div->getOperand(0); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2267 | switch (Pred) { |
| 2268 | default: llvm_unreachable("Unhandled icmp opcode!"); |
| 2269 | case ICmpInst::ICMP_EQ: |
| 2270 | if (LoOverflow && HiOverflow) |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2271 | return replaceInstUsesWith(Cmp, Builder->getFalse()); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2272 | if (HiOverflow) |
| 2273 | return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : |
| 2274 | ICmpInst::ICMP_UGE, X, LoBound); |
| 2275 | if (LoOverflow) |
| 2276 | return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : |
| 2277 | ICmpInst::ICMP_ULT, X, HiBound); |
Sanjay Patel | 85d7974 | 2016-08-31 19:49:56 +0000 | [diff] [blame] | 2278 | return replaceInstUsesWith( |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2279 | Cmp, insertRangeTest(X, LoBound->getUniqueInteger(), |
| 2280 | HiBound->getUniqueInteger(), DivIsSigned, true)); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2281 | case ICmpInst::ICMP_NE: |
| 2282 | if (LoOverflow && HiOverflow) |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2283 | return replaceInstUsesWith(Cmp, Builder->getTrue()); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2284 | if (HiOverflow) |
| 2285 | return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : |
| 2286 | ICmpInst::ICMP_ULT, X, LoBound); |
| 2287 | if (LoOverflow) |
| 2288 | return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : |
| 2289 | ICmpInst::ICMP_UGE, X, HiBound); |
Sanjay Patel | 541aef4 | 2016-08-31 21:57:21 +0000 | [diff] [blame] | 2290 | return replaceInstUsesWith(Cmp, |
| 2291 | insertRangeTest(X, LoBound->getUniqueInteger(), |
| 2292 | HiBound->getUniqueInteger(), |
| 2293 | DivIsSigned, false)); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2294 | case ICmpInst::ICMP_ULT: |
| 2295 | case ICmpInst::ICMP_SLT: |
| 2296 | if (LoOverflow == +1) // Low bound is greater than input range. |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2297 | return replaceInstUsesWith(Cmp, Builder->getTrue()); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2298 | if (LoOverflow == -1) // Low bound is less than input range. |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2299 | return replaceInstUsesWith(Cmp, Builder->getFalse()); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2300 | return new ICmpInst(Pred, X, LoBound); |
| 2301 | case ICmpInst::ICMP_UGT: |
| 2302 | case ICmpInst::ICMP_SGT: |
| 2303 | if (HiOverflow == +1) // High bound greater than input range. |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2304 | return replaceInstUsesWith(Cmp, Builder->getFalse()); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2305 | if (HiOverflow == -1) // High bound less than input range. |
Sanjay Patel | f7ba089 | 2016-08-26 15:53:01 +0000 | [diff] [blame] | 2306 | return replaceInstUsesWith(Cmp, Builder->getTrue()); |
Sanjay Patel | 1655414 | 2016-08-24 23:03:36 +0000 | [diff] [blame] | 2307 | if (Pred == ICmpInst::ICMP_UGT) |
| 2308 | return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound); |
| 2309 | return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound); |
| 2310 | } |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2311 | |
| 2312 | return nullptr; |
| 2313 | } |
| 2314 | |
Sanjay Patel | b9aa67b | 2016-08-16 21:26:10 +0000 | [diff] [blame] | 2315 | /// Fold icmp (sub X, Y), C. |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 2316 | Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp, |
| 2317 | BinaryOperator *Sub, |
Sanjay Patel | b9aa67b | 2016-08-16 21:26:10 +0000 | [diff] [blame] | 2318 | const APInt *C) { |
Sanjay Patel | 886a542 | 2016-09-15 18:05:17 +0000 | [diff] [blame] | 2319 | Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1); |
| 2320 | ICmpInst::Predicate Pred = Cmp.getPredicate(); |
| 2321 | |
| 2322 | // The following transforms are only worth it if the only user of the subtract |
| 2323 | // is the icmp. |
| 2324 | if (!Sub->hasOneUse()) |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2325 | return nullptr; |
| 2326 | |
Sanjay Patel | 886a542 | 2016-09-15 18:05:17 +0000 | [diff] [blame] | 2327 | if (Sub->hasNoSignedWrap()) { |
| 2328 | // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y) |
| 2329 | if (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue()) |
| 2330 | return new ICmpInst(ICmpInst::ICMP_SGE, X, Y); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2331 | |
Sanjay Patel | 886a542 | 2016-09-15 18:05:17 +0000 | [diff] [blame] | 2332 | // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y) |
| 2333 | if (Pred == ICmpInst::ICMP_SGT && *C == 0) |
| 2334 | return new ICmpInst(ICmpInst::ICMP_SGT, X, Y); |
| 2335 | |
| 2336 | // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y) |
| 2337 | if (Pred == ICmpInst::ICMP_SLT && *C == 0) |
| 2338 | return new ICmpInst(ICmpInst::ICMP_SLT, X, Y); |
| 2339 | |
| 2340 | // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y) |
| 2341 | if (Pred == ICmpInst::ICMP_SLT && *C == 1) |
| 2342 | return new ICmpInst(ICmpInst::ICMP_SLE, X, Y); |
| 2343 | } |
| 2344 | |
| 2345 | const APInt *C2; |
| 2346 | if (!match(X, m_APInt(C2))) |
| 2347 | return nullptr; |
| 2348 | |
| 2349 | // C2 - Y <u C -> (Y | (C - 1)) == C2 |
| 2350 | // iff (C2 & (C - 1)) == C - 1 and C is a power of 2 |
| 2351 | if (Pred == ICmpInst::ICMP_ULT && C->isPowerOf2() && |
| 2352 | (*C2 & (*C - 1)) == (*C - 1)) |
| 2353 | return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateOr(Y, *C - 1), X); |
| 2354 | |
| 2355 | // C2 - Y >u C -> (Y | C) != C2 |
| 2356 | // iff C2 & C == C and C + 1 is a power of 2 |
| 2357 | if (Pred == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() && (*C2 & *C) == *C) |
| 2358 | return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateOr(Y, *C), X); |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2359 | |
| 2360 | return nullptr; |
| 2361 | } |
| 2362 | |
Sanjay Patel | 60ea1b4 | 2016-08-16 22:34:42 +0000 | [diff] [blame] | 2363 | /// Fold icmp (add X, Y), C. |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 2364 | Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp, |
| 2365 | BinaryOperator *Add, |
Sanjay Patel | 60ea1b4 | 2016-08-16 22:34:42 +0000 | [diff] [blame] | 2366 | const APInt *C) { |
Sanjay Patel | 4f7eb2a | 2016-08-17 15:24:30 +0000 | [diff] [blame] | 2367 | Value *Y = Add->getOperand(1); |
| 2368 | const APInt *C2; |
| 2369 | if (Cmp.isEquality() || !match(Y, m_APInt(C2))) |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2370 | return nullptr; |
| 2371 | |
Sanjay Patel | 4f7eb2a | 2016-08-17 15:24:30 +0000 | [diff] [blame] | 2372 | // Fold icmp pred (add X, C2), C. |
Sanjay Patel | 60ea1b4 | 2016-08-16 22:34:42 +0000 | [diff] [blame] | 2373 | Value *X = Add->getOperand(0); |
Sanjay Patel | 4f7eb2a | 2016-08-17 15:24:30 +0000 | [diff] [blame] | 2374 | Type *Ty = Add->getType(); |
Sanjoy Das | 1f7b813 | 2016-10-02 00:09:57 +0000 | [diff] [blame] | 2375 | auto CR = |
| 2376 | ConstantRange::makeExactICmpRegion(Cmp.getPredicate(), *C).subtract(*C2); |
Sanjay Patel | 60ea1b4 | 2016-08-16 22:34:42 +0000 | [diff] [blame] | 2377 | const APInt &Upper = CR.getUpper(); |
| 2378 | const APInt &Lower = CR.getLower(); |
| 2379 | if (Cmp.isSigned()) { |
| 2380 | if (Lower.isSignBit()) |
Sanjay Patel | 4f7eb2a | 2016-08-17 15:24:30 +0000 | [diff] [blame] | 2381 | return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper)); |
Sanjay Patel | 60ea1b4 | 2016-08-16 22:34:42 +0000 | [diff] [blame] | 2382 | if (Upper.isSignBit()) |
Sanjay Patel | 4f7eb2a | 2016-08-17 15:24:30 +0000 | [diff] [blame] | 2383 | return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower)); |
Sanjay Patel | 60ea1b4 | 2016-08-16 22:34:42 +0000 | [diff] [blame] | 2384 | } else { |
| 2385 | if (Lower.isMinValue()) |
Sanjay Patel | 4f7eb2a | 2016-08-17 15:24:30 +0000 | [diff] [blame] | 2386 | return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper)); |
Sanjay Patel | 60ea1b4 | 2016-08-16 22:34:42 +0000 | [diff] [blame] | 2387 | if (Upper.isMinValue()) |
Sanjay Patel | 4f7eb2a | 2016-08-17 15:24:30 +0000 | [diff] [blame] | 2388 | return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower)); |
Sanjay Patel | 60ea1b4 | 2016-08-16 22:34:42 +0000 | [diff] [blame] | 2389 | } |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2390 | |
Sanjay Patel | 4f7eb2a | 2016-08-17 15:24:30 +0000 | [diff] [blame] | 2391 | if (!Add->hasOneUse()) |
| 2392 | return nullptr; |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2393 | |
Sanjay Patel | 4f7eb2a | 2016-08-17 15:24:30 +0000 | [diff] [blame] | 2394 | // X+C <u C2 -> (X & -C2) == C |
| 2395 | // iff C & (C2-1) == 0 |
| 2396 | // C2 is a power of 2 |
| 2397 | if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() && |
| 2398 | (*C2 & (*C - 1)) == 0) |
| 2399 | return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(X, -(*C)), |
| 2400 | ConstantExpr::getNeg(cast<Constant>(Y))); |
| 2401 | |
| 2402 | // X+C >u C2 -> (X & ~C2) != C |
| 2403 | // iff C & C2 == 0 |
| 2404 | // C2+1 is a power of 2 |
| 2405 | if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() && |
| 2406 | (*C2 & *C) == 0) |
| 2407 | return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(X, ~(*C)), |
| 2408 | ConstantExpr::getNeg(cast<Constant>(Y))); |
| 2409 | |
Sanjay Patel | a3f4f08 | 2016-08-16 17:54:36 +0000 | [diff] [blame] | 2410 | return nullptr; |
| 2411 | } |
| 2412 | |
Sanjay Patel | f58f68c | 2016-09-10 15:03:44 +0000 | [diff] [blame] | 2413 | /// Try to fold integer comparisons with a constant operand: icmp Pred X, C |
| 2414 | /// where X is some kind of instruction. |
| 2415 | Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) { |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 2416 | const APInt *C; |
| 2417 | if (!match(Cmp.getOperand(1), m_APInt(C))) |
Sanjay Patel | 1e5b2d1 | 2016-08-16 16:08:11 +0000 | [diff] [blame] | 2418 | return nullptr; |
| 2419 | |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 2420 | BinaryOperator *BO; |
| 2421 | if (match(Cmp.getOperand(0), m_BinOp(BO))) { |
| 2422 | switch (BO->getOpcode()) { |
| 2423 | case Instruction::Xor: |
| 2424 | if (Instruction *I = foldICmpXorConstant(Cmp, BO, C)) |
| 2425 | return I; |
| 2426 | break; |
| 2427 | case Instruction::And: |
| 2428 | if (Instruction *I = foldICmpAndConstant(Cmp, BO, C)) |
| 2429 | return I; |
| 2430 | break; |
| 2431 | case Instruction::Or: |
| 2432 | if (Instruction *I = foldICmpOrConstant(Cmp, BO, C)) |
| 2433 | return I; |
| 2434 | break; |
| 2435 | case Instruction::Mul: |
| 2436 | if (Instruction *I = foldICmpMulConstant(Cmp, BO, C)) |
| 2437 | return I; |
| 2438 | break; |
| 2439 | case Instruction::Shl: |
| 2440 | if (Instruction *I = foldICmpShlConstant(Cmp, BO, C)) |
| 2441 | return I; |
| 2442 | break; |
| 2443 | case Instruction::LShr: |
| 2444 | case Instruction::AShr: |
| 2445 | if (Instruction *I = foldICmpShrConstant(Cmp, BO, C)) |
| 2446 | return I; |
| 2447 | break; |
| 2448 | case Instruction::UDiv: |
| 2449 | if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C)) |
| 2450 | return I; |
| 2451 | LLVM_FALLTHROUGH; |
| 2452 | case Instruction::SDiv: |
| 2453 | if (Instruction *I = foldICmpDivConstant(Cmp, BO, C)) |
| 2454 | return I; |
| 2455 | break; |
| 2456 | case Instruction::Sub: |
| 2457 | if (Instruction *I = foldICmpSubConstant(Cmp, BO, C)) |
| 2458 | return I; |
| 2459 | break; |
| 2460 | case Instruction::Add: |
| 2461 | if (Instruction *I = foldICmpAddConstant(Cmp, BO, C)) |
| 2462 | return I; |
| 2463 | break; |
| 2464 | default: |
| 2465 | break; |
| 2466 | } |
Sanjay Patel | f58f68c | 2016-09-10 15:03:44 +0000 | [diff] [blame] | 2467 | // TODO: These folds could be refactored to be part of the above calls. |
| 2468 | if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C)) |
| 2469 | return I; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 2470 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 2471 | |
Sanjay Patel | c9196c4 | 2016-08-22 21:24:29 +0000 | [diff] [blame] | 2472 | Instruction *LHSI; |
| 2473 | if (match(Cmp.getOperand(0), m_Instruction(LHSI)) && |
| 2474 | LHSI->getOpcode() == Instruction::Trunc) |
| 2475 | if (Instruction *I = foldICmpTruncConstant(Cmp, LHSI, C)) |
| 2476 | return I; |
| 2477 | |
Sanjay Patel | f58f68c | 2016-09-10 15:03:44 +0000 | [diff] [blame] | 2478 | if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, C)) |
| 2479 | return I; |
| 2480 | |
Sanjay Patel | 1710e7c | 2016-07-21 17:15:49 +0000 | [diff] [blame] | 2481 | return nullptr; |
| 2482 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 2483 | |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2484 | /// Fold an icmp equality instruction with binary operator LHS and constant RHS: |
| 2485 | /// icmp eq/ne BO, C. |
| 2486 | Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp, |
| 2487 | BinaryOperator *BO, |
| 2488 | const APInt *C) { |
| 2489 | // TODO: Some of these folds could work with arbitrary constants, but this |
| 2490 | // function is limited to scalar and vector splat constants. |
| 2491 | if (!Cmp.isEquality()) |
Sanjay Patel | 1710e7c | 2016-07-21 17:15:49 +0000 | [diff] [blame] | 2492 | return nullptr; |
| 2493 | |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2494 | ICmpInst::Predicate Pred = Cmp.getPredicate(); |
| 2495 | bool isICMP_NE = Pred == ICmpInst::ICMP_NE; |
| 2496 | Constant *RHS = cast<Constant>(Cmp.getOperand(1)); |
Sanjay Patel | 51a767c | 2016-08-03 17:23:08 +0000 | [diff] [blame] | 2497 | Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); |
Sanjay Patel | 1710e7c | 2016-07-21 17:15:49 +0000 | [diff] [blame] | 2498 | |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2499 | switch (BO->getOpcode()) { |
| 2500 | case Instruction::SRem: |
| 2501 | // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2502 | if (*C == 0 && BO->hasOneUse()) { |
Sanjay Patel | 2e9675f | 2016-08-03 19:48:40 +0000 | [diff] [blame] | 2503 | const APInt *BOC; |
| 2504 | if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) { |
Sanjay Patel | 51a767c | 2016-08-03 17:23:08 +0000 | [diff] [blame] | 2505 | Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName()); |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2506 | return new ICmpInst(Pred, NewRem, |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2507 | Constant::getNullValue(BO->getType())); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 2508 | } |
Sanjay Patel | 1710e7c | 2016-07-21 17:15:49 +0000 | [diff] [blame] | 2509 | } |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2510 | break; |
Sanjay Patel | 00a324e | 2016-08-03 22:08:44 +0000 | [diff] [blame] | 2511 | case Instruction::Add: { |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2512 | // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. |
Sanjay Patel | 00a324e | 2016-08-03 22:08:44 +0000 | [diff] [blame] | 2513 | const APInt *BOC; |
| 2514 | if (match(BOp1, m_APInt(BOC))) { |
| 2515 | if (BO->hasOneUse()) { |
| 2516 | Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1)); |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2517 | return new ICmpInst(Pred, BOp0, SubC); |
Sanjay Patel | 00a324e | 2016-08-03 22:08:44 +0000 | [diff] [blame] | 2518 | } |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2519 | } else if (*C == 0) { |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2520 | // Replace ((add A, B) != 0) with (A != -B) if A or B is |
| 2521 | // efficiently invertible, or if the add has just this one use. |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2522 | if (Value *NegVal = dyn_castNegVal(BOp1)) |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2523 | return new ICmpInst(Pred, BOp0, NegVal); |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2524 | if (Value *NegVal = dyn_castNegVal(BOp0)) |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2525 | return new ICmpInst(Pred, NegVal, BOp1); |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2526 | if (BO->hasOneUse()) { |
| 2527 | Value *Neg = Builder->CreateNeg(BOp1); |
| 2528 | Neg->takeName(BO); |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2529 | return new ICmpInst(Pred, BOp0, Neg); |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2530 | } |
| 2531 | } |
| 2532 | break; |
Sanjay Patel | 00a324e | 2016-08-03 22:08:44 +0000 | [diff] [blame] | 2533 | } |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2534 | case Instruction::Xor: |
| 2535 | if (BO->hasOneUse()) { |
Sanjay Patel | 51a767c | 2016-08-03 17:23:08 +0000 | [diff] [blame] | 2536 | if (Constant *BOC = dyn_cast<Constant>(BOp1)) { |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2537 | // For the xor case, we can xor two constants together, eliminating |
| 2538 | // the explicit xor. |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2539 | return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC)); |
| 2540 | } else if (*C == 0) { |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2541 | // Replace ((xor A, B) != 0) with (A != B) |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2542 | return new ICmpInst(Pred, BOp0, BOp1); |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2543 | } |
| 2544 | } |
| 2545 | break; |
| 2546 | case Instruction::Sub: |
| 2547 | if (BO->hasOneUse()) { |
Sanjay Patel | 9d591d1 | 2016-08-04 15:19:25 +0000 | [diff] [blame] | 2548 | const APInt *BOC; |
| 2549 | if (match(BOp0, m_APInt(BOC))) { |
Sanjay Patel | 362ff5c | 2016-09-15 17:01:17 +0000 | [diff] [blame] | 2550 | // Replace ((sub BOC, B) != C) with (B != BOC-C). |
Sanjay Patel | 9d591d1 | 2016-08-04 15:19:25 +0000 | [diff] [blame] | 2551 | Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS); |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2552 | return new ICmpInst(Pred, BOp1, SubC); |
| 2553 | } else if (*C == 0) { |
Sanjay Patel | 362ff5c | 2016-09-15 17:01:17 +0000 | [diff] [blame] | 2554 | // Replace ((sub A, B) != 0) with (A != B). |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2555 | return new ICmpInst(Pred, BOp0, BOp1); |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2556 | } |
| 2557 | } |
| 2558 | break; |
Sanjay Patel | b3de75d | 2016-08-04 19:12:12 +0000 | [diff] [blame] | 2559 | case Instruction::Or: { |
| 2560 | const APInt *BOC; |
| 2561 | if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) { |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2562 | // Comparing if all bits outside of a constant mask are set? |
| 2563 | // Replace (X | C) == -1 with (X & ~C) == ~C. |
| 2564 | // This removes the -1 constant. |
Sanjay Patel | b3de75d | 2016-08-04 19:12:12 +0000 | [diff] [blame] | 2565 | Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1)); |
| 2566 | Value *And = Builder->CreateAnd(BOp0, NotBOC); |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2567 | return new ICmpInst(Pred, And, NotBOC); |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2568 | } |
| 2569 | break; |
Sanjay Patel | b3de75d | 2016-08-04 19:12:12 +0000 | [diff] [blame] | 2570 | } |
Sanjay Patel | d938e88 | 2016-08-04 20:05:02 +0000 | [diff] [blame] | 2571 | case Instruction::And: { |
| 2572 | const APInt *BOC; |
| 2573 | if (match(BOp1, m_APInt(BOC))) { |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2574 | // If we have ((X & C) == C), turn it into ((X & C) != 0). |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2575 | if (C == BOC && C->isPowerOf2()) |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2576 | return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, |
Sanjay Patel | ab50a93 | 2016-08-02 22:38:33 +0000 | [diff] [blame] | 2577 | BO, Constant::getNullValue(RHS->getType())); |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2578 | |
| 2579 | // Don't perform the following transforms if the AND has multiple uses |
| 2580 | if (!BO->hasOneUse()) |
| 2581 | break; |
| 2582 | |
| 2583 | // Replace (and X, (1 << size(X)-1) != 0) with x s< 0 |
Sanjay Patel | d938e88 | 2016-08-04 20:05:02 +0000 | [diff] [blame] | 2584 | if (BOC->isSignBit()) { |
Sanjay Patel | 51a767c | 2016-08-03 17:23:08 +0000 | [diff] [blame] | 2585 | Constant *Zero = Constant::getNullValue(BOp0->getType()); |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2586 | auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE; |
| 2587 | return new ICmpInst(NewPred, BOp0, Zero); |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2588 | } |
| 2589 | |
| 2590 | // ((X & ~7) == 0) --> X < 8 |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2591 | if (*C == 0 && (~(*BOC) + 1).isPowerOf2()) { |
Sanjay Patel | d938e88 | 2016-08-04 20:05:02 +0000 | [diff] [blame] | 2592 | Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1)); |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2593 | auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; |
| 2594 | return new ICmpInst(NewPred, BOp0, NegBOC); |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2595 | } |
| 2596 | } |
| 2597 | break; |
Sanjay Patel | d938e88 | 2016-08-04 20:05:02 +0000 | [diff] [blame] | 2598 | } |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2599 | case Instruction::Mul: |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2600 | if (*C == 0 && BO->hasNoSignedWrap()) { |
Sanjay Patel | 3bade13 | 2016-08-04 22:19:27 +0000 | [diff] [blame] | 2601 | const APInt *BOC; |
| 2602 | if (match(BOp1, m_APInt(BOC)) && *BOC != 0) { |
| 2603 | // The trivial case (mul X, 0) is handled by InstSimplify. |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2604 | // General case : (mul X, C) != 0 iff X != 0 |
| 2605 | // (mul X, C) == 0 iff X == 0 |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2606 | return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType())); |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2607 | } |
| 2608 | } |
| 2609 | break; |
Sanjay Patel | 6ebd585 | 2016-07-23 00:28:39 +0000 | [diff] [blame] | 2610 | case Instruction::UDiv: |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2611 | if (*C == 0) { |
Sanjay Patel | 6ebd585 | 2016-07-23 00:28:39 +0000 | [diff] [blame] | 2612 | // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A) |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2613 | auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT; |
| 2614 | return new ICmpInst(NewPred, BOp1, BOp0); |
Sanjay Patel | 6ebd585 | 2016-07-23 00:28:39 +0000 | [diff] [blame] | 2615 | } |
| 2616 | break; |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2617 | default: |
| 2618 | break; |
| 2619 | } |
| 2620 | return nullptr; |
| 2621 | } |
| 2622 | |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2623 | /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C. |
| 2624 | Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp, |
| 2625 | const APInt *C) { |
| 2626 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)); |
| 2627 | if (!II || !Cmp.isEquality()) |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2628 | return nullptr; |
| 2629 | |
| 2630 | // Handle icmp {eq|ne} <intrinsic>, intcst. |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2631 | switch (II->getIntrinsicID()) { |
| 2632 | case Intrinsic::bswap: |
| 2633 | Worklist.Add(II); |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2634 | Cmp.setOperand(0, II->getArgOperand(0)); |
| 2635 | Cmp.setOperand(1, Builder->getInt(C->byteSwap())); |
| 2636 | return &Cmp; |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2637 | case Intrinsic::ctlz: |
| 2638 | case Intrinsic::cttz: |
Amaury Sechet | 6bea674 | 2016-08-04 05:27:20 +0000 | [diff] [blame] | 2639 | // ctz(A) == bitwidth(A) -> A == 0 and likewise for != |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2640 | if (*C == C->getBitWidth()) { |
Sanjay Patel | 1710e7c | 2016-07-21 17:15:49 +0000 | [diff] [blame] | 2641 | Worklist.Add(II); |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2642 | Cmp.setOperand(0, II->getArgOperand(0)); |
| 2643 | Cmp.setOperand(1, ConstantInt::getNullValue(II->getType())); |
| 2644 | return &Cmp; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 2645 | } |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2646 | break; |
Amaury Sechet | 6bea674 | 2016-08-04 05:27:20 +0000 | [diff] [blame] | 2647 | case Intrinsic::ctpop: { |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2648 | // popcount(A) == 0 -> A == 0 and likewise for != |
Amaury Sechet | 6bea674 | 2016-08-04 05:27:20 +0000 | [diff] [blame] | 2649 | // popcount(A) == bitwidth(A) -> A == -1 and likewise for != |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2650 | bool IsZero = *C == 0; |
| 2651 | if (IsZero || *C == C->getBitWidth()) { |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2652 | Worklist.Add(II); |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2653 | Cmp.setOperand(0, II->getArgOperand(0)); |
| 2654 | auto *NewOp = IsZero ? Constant::getNullValue(II->getType()) |
| 2655 | : Constant::getAllOnesValue(II->getType()); |
| 2656 | Cmp.setOperand(1, NewOp); |
| 2657 | return &Cmp; |
Amaury Sechet | 6bea674 | 2016-08-04 05:27:20 +0000 | [diff] [blame] | 2658 | } |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2659 | break; |
Sanjay Patel | 0a3d72b | 2016-09-10 15:33:39 +0000 | [diff] [blame] | 2660 | } |
Sanjay Patel | 18fa9d3 | 2016-07-21 23:27:36 +0000 | [diff] [blame] | 2661 | default: |
| 2662 | break; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 2663 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2664 | return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 2665 | } |
| 2666 | |
Sanjay Patel | 10494b2 | 2016-09-16 16:10:22 +0000 | [diff] [blame] | 2667 | /// Handle icmp with constant (but not simple integer constant) RHS. |
| 2668 | Instruction *InstCombiner::foldICmpInstWithConstantNotInt(ICmpInst &I) { |
| 2669 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 2670 | Constant *RHSC = dyn_cast<Constant>(Op1); |
| 2671 | Instruction *LHSI = dyn_cast<Instruction>(Op0); |
| 2672 | if (!RHSC || !LHSI) |
| 2673 | return nullptr; |
| 2674 | |
| 2675 | switch (LHSI->getOpcode()) { |
| 2676 | case Instruction::GetElementPtr: |
| 2677 | // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null |
| 2678 | if (RHSC->isNullValue() && |
| 2679 | cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices()) |
| 2680 | return new ICmpInst( |
| 2681 | I.getPredicate(), LHSI->getOperand(0), |
| 2682 | Constant::getNullValue(LHSI->getOperand(0)->getType())); |
| 2683 | break; |
| 2684 | case Instruction::PHI: |
| 2685 | // Only fold icmp into the PHI if the phi and icmp are in the same |
| 2686 | // block. If in the same block, we're encouraging jump threading. If |
| 2687 | // not, we are just pessimizing the code by making an i1 phi. |
| 2688 | if (LHSI->getParent() == I.getParent()) |
| 2689 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 2690 | return NV; |
| 2691 | break; |
| 2692 | case Instruction::Select: { |
| 2693 | // If either operand of the select is a constant, we can fold the |
| 2694 | // comparison into the select arms, which will cause one to be |
| 2695 | // constant folded and the select turned into a bitwise or. |
| 2696 | Value *Op1 = nullptr, *Op2 = nullptr; |
| 2697 | ConstantInt *CI = nullptr; |
| 2698 | if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) { |
| 2699 | Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); |
| 2700 | CI = dyn_cast<ConstantInt>(Op1); |
| 2701 | } |
| 2702 | if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) { |
| 2703 | Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); |
| 2704 | CI = dyn_cast<ConstantInt>(Op2); |
| 2705 | } |
| 2706 | |
| 2707 | // We only want to perform this transformation if it will not lead to |
| 2708 | // additional code. This is true if either both sides of the select |
| 2709 | // fold to a constant (in which case the icmp is replaced with a select |
| 2710 | // which will usually simplify) or this is the only user of the |
| 2711 | // select (in which case we are trading a select+icmp for a simpler |
| 2712 | // select+icmp) or all uses of the select can be replaced based on |
| 2713 | // dominance information ("Global cases"). |
| 2714 | bool Transform = false; |
| 2715 | if (Op1 && Op2) |
| 2716 | Transform = true; |
| 2717 | else if (Op1 || Op2) { |
| 2718 | // Local case |
| 2719 | if (LHSI->hasOneUse()) |
| 2720 | Transform = true; |
| 2721 | // Global cases |
| 2722 | else if (CI && !CI->isZero()) |
| 2723 | // When Op1 is constant try replacing select with second operand. |
| 2724 | // Otherwise Op2 is constant and try replacing select with first |
| 2725 | // operand. |
| 2726 | Transform = |
| 2727 | replacedSelectWithOperand(cast<SelectInst>(LHSI), &I, Op1 ? 2 : 1); |
| 2728 | } |
| 2729 | if (Transform) { |
| 2730 | if (!Op1) |
| 2731 | Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1), RHSC, |
| 2732 | I.getName()); |
| 2733 | if (!Op2) |
| 2734 | Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2), RHSC, |
| 2735 | I.getName()); |
| 2736 | return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); |
| 2737 | } |
| 2738 | break; |
| 2739 | } |
| 2740 | case Instruction::IntToPtr: |
| 2741 | // icmp pred inttoptr(X), null -> icmp pred X, 0 |
| 2742 | if (RHSC->isNullValue() && |
| 2743 | DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType()) |
| 2744 | return new ICmpInst( |
| 2745 | I.getPredicate(), LHSI->getOperand(0), |
| 2746 | Constant::getNullValue(LHSI->getOperand(0)->getType())); |
| 2747 | break; |
| 2748 | |
| 2749 | case Instruction::Load: |
| 2750 | // Try to optimize things like "A[i] > 4" to index computations. |
| 2751 | if (GetElementPtrInst *GEP = |
| 2752 | dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { |
| 2753 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) |
| 2754 | if (GV->isConstant() && GV->hasDefinitiveInitializer() && |
| 2755 | !cast<LoadInst>(LHSI)->isVolatile()) |
| 2756 | if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I)) |
| 2757 | return Res; |
| 2758 | } |
| 2759 | break; |
| 2760 | } |
| 2761 | |
| 2762 | return nullptr; |
| 2763 | } |
| 2764 | |
| 2765 | /// Try to fold icmp (binop), X or icmp X, (binop). |
| 2766 | Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) { |
| 2767 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 2768 | |
| 2769 | // Special logic for binary operators. |
| 2770 | BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0); |
| 2771 | BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1); |
| 2772 | if (!BO0 && !BO1) |
| 2773 | return nullptr; |
| 2774 | |
| 2775 | CmpInst::Predicate Pred = I.getPredicate(); |
| 2776 | bool NoOp0WrapProblem = false, NoOp1WrapProblem = false; |
| 2777 | if (BO0 && isa<OverflowingBinaryOperator>(BO0)) |
| 2778 | NoOp0WrapProblem = |
| 2779 | ICmpInst::isEquality(Pred) || |
| 2780 | (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) || |
| 2781 | (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap()); |
| 2782 | if (BO1 && isa<OverflowingBinaryOperator>(BO1)) |
| 2783 | NoOp1WrapProblem = |
| 2784 | ICmpInst::isEquality(Pred) || |
| 2785 | (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) || |
| 2786 | (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap()); |
| 2787 | |
| 2788 | // Analyze the case when either Op0 or Op1 is an add instruction. |
| 2789 | // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null). |
| 2790 | Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; |
| 2791 | if (BO0 && BO0->getOpcode() == Instruction::Add) { |
| 2792 | A = BO0->getOperand(0); |
| 2793 | B = BO0->getOperand(1); |
| 2794 | } |
| 2795 | if (BO1 && BO1->getOpcode() == Instruction::Add) { |
| 2796 | C = BO1->getOperand(0); |
| 2797 | D = BO1->getOperand(1); |
| 2798 | } |
| 2799 | |
| 2800 | // icmp (X+cst) < 0 --> X < -cst |
| 2801 | if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero())) |
| 2802 | if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B)) |
| 2803 | if (!RHSC->isMinValue(/*isSigned=*/true)) |
| 2804 | return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC)); |
| 2805 | |
| 2806 | // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. |
| 2807 | if ((A == Op1 || B == Op1) && NoOp0WrapProblem) |
| 2808 | return new ICmpInst(Pred, A == Op1 ? B : A, |
| 2809 | Constant::getNullValue(Op1->getType())); |
| 2810 | |
| 2811 | // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. |
| 2812 | if ((C == Op0 || D == Op0) && NoOp1WrapProblem) |
| 2813 | return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()), |
| 2814 | C == Op0 ? D : C); |
| 2815 | |
| 2816 | // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow. |
| 2817 | if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem && |
| 2818 | NoOp1WrapProblem && |
| 2819 | // Try not to increase register pressure. |
| 2820 | BO0->hasOneUse() && BO1->hasOneUse()) { |
| 2821 | // Determine Y and Z in the form icmp (X+Y), (X+Z). |
| 2822 | Value *Y, *Z; |
| 2823 | if (A == C) { |
| 2824 | // C + B == C + D -> B == D |
| 2825 | Y = B; |
| 2826 | Z = D; |
| 2827 | } else if (A == D) { |
| 2828 | // D + B == C + D -> B == C |
| 2829 | Y = B; |
| 2830 | Z = C; |
| 2831 | } else if (B == C) { |
| 2832 | // A + C == C + D -> A == D |
| 2833 | Y = A; |
| 2834 | Z = D; |
| 2835 | } else { |
| 2836 | assert(B == D); |
| 2837 | // A + D == C + D -> A == C |
| 2838 | Y = A; |
| 2839 | Z = C; |
| 2840 | } |
| 2841 | return new ICmpInst(Pred, Y, Z); |
| 2842 | } |
| 2843 | |
| 2844 | // icmp slt (X + -1), Y -> icmp sle X, Y |
| 2845 | if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT && |
| 2846 | match(B, m_AllOnes())) |
| 2847 | return new ICmpInst(CmpInst::ICMP_SLE, A, Op1); |
| 2848 | |
| 2849 | // icmp sge (X + -1), Y -> icmp sgt X, Y |
| 2850 | if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE && |
| 2851 | match(B, m_AllOnes())) |
| 2852 | return new ICmpInst(CmpInst::ICMP_SGT, A, Op1); |
| 2853 | |
| 2854 | // icmp sle (X + 1), Y -> icmp slt X, Y |
| 2855 | if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One())) |
| 2856 | return new ICmpInst(CmpInst::ICMP_SLT, A, Op1); |
| 2857 | |
| 2858 | // icmp sgt (X + 1), Y -> icmp sge X, Y |
| 2859 | if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One())) |
| 2860 | return new ICmpInst(CmpInst::ICMP_SGE, A, Op1); |
| 2861 | |
| 2862 | // icmp sgt X, (Y + -1) -> icmp sge X, Y |
| 2863 | if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT && |
| 2864 | match(D, m_AllOnes())) |
| 2865 | return new ICmpInst(CmpInst::ICMP_SGE, Op0, C); |
| 2866 | |
| 2867 | // icmp sle X, (Y + -1) -> icmp slt X, Y |
| 2868 | if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE && |
| 2869 | match(D, m_AllOnes())) |
| 2870 | return new ICmpInst(CmpInst::ICMP_SLT, Op0, C); |
| 2871 | |
| 2872 | // icmp sge X, (Y + 1) -> icmp sgt X, Y |
| 2873 | if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One())) |
| 2874 | return new ICmpInst(CmpInst::ICMP_SGT, Op0, C); |
| 2875 | |
| 2876 | // icmp slt X, (Y + 1) -> icmp sle X, Y |
| 2877 | if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One())) |
| 2878 | return new ICmpInst(CmpInst::ICMP_SLE, Op0, C); |
| 2879 | |
Sanjay Patel | 40f4017 | 2017-01-13 23:25:46 +0000 | [diff] [blame] | 2880 | // TODO: The subtraction-related identities shown below also hold, but |
| 2881 | // canonicalization from (X -nuw 1) to (X + -1) means that the combinations |
| 2882 | // wouldn't happen even if they were implemented. |
| 2883 | // |
| 2884 | // icmp ult (X - 1), Y -> icmp ule X, Y |
| 2885 | // icmp uge (X - 1), Y -> icmp ugt X, Y |
| 2886 | // icmp ugt X, (Y - 1) -> icmp uge X, Y |
| 2887 | // icmp ule X, (Y - 1) -> icmp ult X, Y |
| 2888 | |
| 2889 | // icmp ule (X + 1), Y -> icmp ult X, Y |
| 2890 | if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One())) |
| 2891 | return new ICmpInst(CmpInst::ICMP_ULT, A, Op1); |
| 2892 | |
| 2893 | // icmp ugt (X + 1), Y -> icmp uge X, Y |
| 2894 | if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One())) |
| 2895 | return new ICmpInst(CmpInst::ICMP_UGE, A, Op1); |
| 2896 | |
| 2897 | // icmp uge X, (Y + 1) -> icmp ugt X, Y |
| 2898 | if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One())) |
| 2899 | return new ICmpInst(CmpInst::ICMP_UGT, Op0, C); |
| 2900 | |
| 2901 | // icmp ult X, (Y + 1) -> icmp ule X, Y |
| 2902 | if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One())) |
| 2903 | return new ICmpInst(CmpInst::ICMP_ULE, Op0, C); |
| 2904 | |
Sanjay Patel | 10494b2 | 2016-09-16 16:10:22 +0000 | [diff] [blame] | 2905 | // if C1 has greater magnitude than C2: |
| 2906 | // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y |
| 2907 | // s.t. C3 = C1 - C2 |
| 2908 | // |
| 2909 | // if C2 has greater magnitude than C1: |
| 2910 | // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3) |
| 2911 | // s.t. C3 = C2 - C1 |
| 2912 | if (A && C && NoOp0WrapProblem && NoOp1WrapProblem && |
| 2913 | (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) |
| 2914 | if (ConstantInt *C1 = dyn_cast<ConstantInt>(B)) |
| 2915 | if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) { |
| 2916 | const APInt &AP1 = C1->getValue(); |
| 2917 | const APInt &AP2 = C2->getValue(); |
| 2918 | if (AP1.isNegative() == AP2.isNegative()) { |
| 2919 | APInt AP1Abs = C1->getValue().abs(); |
| 2920 | APInt AP2Abs = C2->getValue().abs(); |
| 2921 | if (AP1Abs.uge(AP2Abs)) { |
| 2922 | ConstantInt *C3 = Builder->getInt(AP1 - AP2); |
| 2923 | Value *NewAdd = Builder->CreateNSWAdd(A, C3); |
| 2924 | return new ICmpInst(Pred, NewAdd, C); |
| 2925 | } else { |
| 2926 | ConstantInt *C3 = Builder->getInt(AP2 - AP1); |
| 2927 | Value *NewAdd = Builder->CreateNSWAdd(C, C3); |
| 2928 | return new ICmpInst(Pred, A, NewAdd); |
| 2929 | } |
| 2930 | } |
| 2931 | } |
| 2932 | |
| 2933 | // Analyze the case when either Op0 or Op1 is a sub instruction. |
| 2934 | // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null). |
| 2935 | A = nullptr; |
| 2936 | B = nullptr; |
| 2937 | C = nullptr; |
| 2938 | D = nullptr; |
| 2939 | if (BO0 && BO0->getOpcode() == Instruction::Sub) { |
| 2940 | A = BO0->getOperand(0); |
| 2941 | B = BO0->getOperand(1); |
| 2942 | } |
| 2943 | if (BO1 && BO1->getOpcode() == Instruction::Sub) { |
| 2944 | C = BO1->getOperand(0); |
| 2945 | D = BO1->getOperand(1); |
| 2946 | } |
| 2947 | |
| 2948 | // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow. |
| 2949 | if (A == Op1 && NoOp0WrapProblem) |
| 2950 | return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B); |
| 2951 | |
| 2952 | // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow. |
| 2953 | if (C == Op0 && NoOp1WrapProblem) |
| 2954 | return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType())); |
| 2955 | |
| 2956 | // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow. |
| 2957 | if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem && |
| 2958 | // Try not to increase register pressure. |
| 2959 | BO0->hasOneUse() && BO1->hasOneUse()) |
| 2960 | return new ICmpInst(Pred, A, C); |
| 2961 | |
| 2962 | // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow. |
| 2963 | if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem && |
| 2964 | // Try not to increase register pressure. |
| 2965 | BO0->hasOneUse() && BO1->hasOneUse()) |
| 2966 | return new ICmpInst(Pred, D, B); |
| 2967 | |
| 2968 | // icmp (0-X) < cst --> x > -cst |
| 2969 | if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) { |
| 2970 | Value *X; |
| 2971 | if (match(BO0, m_Neg(m_Value(X)))) |
| 2972 | if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) |
| 2973 | if (!RHSC->isMinValue(/*isSigned=*/true)) |
| 2974 | return new ICmpInst(I.getSwappedPredicate(), X, |
| 2975 | ConstantExpr::getNeg(RHSC)); |
| 2976 | } |
| 2977 | |
| 2978 | BinaryOperator *SRem = nullptr; |
| 2979 | // icmp (srem X, Y), Y |
| 2980 | if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1)) |
| 2981 | SRem = BO0; |
| 2982 | // icmp Y, (srem X, Y) |
| 2983 | else if (BO1 && BO1->getOpcode() == Instruction::SRem && |
| 2984 | Op0 == BO1->getOperand(1)) |
| 2985 | SRem = BO1; |
| 2986 | if (SRem) { |
| 2987 | // We don't check hasOneUse to avoid increasing register pressure because |
| 2988 | // the value we use is the same value this instruction was already using. |
| 2989 | switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) { |
| 2990 | default: |
| 2991 | break; |
| 2992 | case ICmpInst::ICMP_EQ: |
| 2993 | return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); |
| 2994 | case ICmpInst::ICMP_NE: |
| 2995 | return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); |
| 2996 | case ICmpInst::ICMP_SGT: |
| 2997 | case ICmpInst::ICMP_SGE: |
| 2998 | return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1), |
| 2999 | Constant::getAllOnesValue(SRem->getType())); |
| 3000 | case ICmpInst::ICMP_SLT: |
| 3001 | case ICmpInst::ICMP_SLE: |
| 3002 | return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1), |
| 3003 | Constant::getNullValue(SRem->getType())); |
| 3004 | } |
| 3005 | } |
| 3006 | |
| 3007 | if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() && |
| 3008 | BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) { |
| 3009 | switch (BO0->getOpcode()) { |
| 3010 | default: |
| 3011 | break; |
| 3012 | case Instruction::Add: |
| 3013 | case Instruction::Sub: |
| 3014 | case Instruction::Xor: |
| 3015 | if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b |
| 3016 | return new ICmpInst(I.getPredicate(), BO0->getOperand(0), |
| 3017 | BO1->getOperand(0)); |
| 3018 | // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b |
| 3019 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) { |
| 3020 | if (CI->getValue().isSignBit()) { |
| 3021 | ICmpInst::Predicate Pred = |
| 3022 | I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate(); |
| 3023 | return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); |
| 3024 | } |
| 3025 | |
| 3026 | if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) { |
| 3027 | ICmpInst::Predicate Pred = |
| 3028 | I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate(); |
| 3029 | Pred = I.getSwappedPredicate(Pred); |
| 3030 | return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); |
| 3031 | } |
| 3032 | } |
| 3033 | break; |
| 3034 | case Instruction::Mul: |
| 3035 | if (!I.isEquality()) |
| 3036 | break; |
| 3037 | |
| 3038 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) { |
| 3039 | // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask |
| 3040 | // Mask = -1 >> count-trailing-zeros(Cst). |
| 3041 | if (!CI->isZero() && !CI->isOne()) { |
| 3042 | const APInt &AP = CI->getValue(); |
| 3043 | ConstantInt *Mask = ConstantInt::get( |
| 3044 | I.getContext(), |
| 3045 | APInt::getLowBitsSet(AP.getBitWidth(), |
| 3046 | AP.getBitWidth() - AP.countTrailingZeros())); |
| 3047 | Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask); |
| 3048 | Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask); |
| 3049 | return new ICmpInst(I.getPredicate(), And1, And2); |
| 3050 | } |
| 3051 | } |
| 3052 | break; |
| 3053 | case Instruction::UDiv: |
| 3054 | case Instruction::LShr: |
| 3055 | if (I.isSigned()) |
| 3056 | break; |
| 3057 | LLVM_FALLTHROUGH; |
| 3058 | case Instruction::SDiv: |
| 3059 | case Instruction::AShr: |
| 3060 | if (!BO0->isExact() || !BO1->isExact()) |
| 3061 | break; |
| 3062 | return new ICmpInst(I.getPredicate(), BO0->getOperand(0), |
| 3063 | BO1->getOperand(0)); |
| 3064 | case Instruction::Shl: { |
| 3065 | bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap(); |
| 3066 | bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap(); |
| 3067 | if (!NUW && !NSW) |
| 3068 | break; |
| 3069 | if (!NSW && I.isSigned()) |
| 3070 | break; |
| 3071 | return new ICmpInst(I.getPredicate(), BO0->getOperand(0), |
| 3072 | BO1->getOperand(0)); |
| 3073 | } |
| 3074 | } |
| 3075 | } |
| 3076 | |
| 3077 | if (BO0) { |
| 3078 | // Transform A & (L - 1) `ult` L --> L != 0 |
| 3079 | auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes()); |
| 3080 | auto BitwiseAnd = |
| 3081 | m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value())); |
| 3082 | |
| 3083 | if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) { |
| 3084 | auto *Zero = Constant::getNullValue(BO0->getType()); |
| 3085 | return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero); |
| 3086 | } |
| 3087 | } |
| 3088 | |
| 3089 | return nullptr; |
| 3090 | } |
| 3091 | |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 3092 | /// Fold icmp Pred min|max(X, Y), X. |
| 3093 | static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) { |
Sanjay Patel | d640641 | 2016-12-15 19:13:37 +0000 | [diff] [blame] | 3094 | ICmpInst::Predicate Pred = Cmp.getPredicate(); |
| 3095 | Value *Op0 = Cmp.getOperand(0); |
| 3096 | Value *X = Cmp.getOperand(1); |
| 3097 | |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 3098 | // Canonicalize minimum or maximum operand to LHS of the icmp. |
Sanjay Patel | 8296c6c | 2016-12-19 16:28:53 +0000 | [diff] [blame] | 3099 | if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) || |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 3100 | match(X, m_c_SMax(m_Specific(Op0), m_Value())) || |
| 3101 | match(X, m_c_UMin(m_Specific(Op0), m_Value())) || |
| 3102 | match(X, m_c_UMax(m_Specific(Op0), m_Value()))) { |
Sanjay Patel | d640641 | 2016-12-15 19:13:37 +0000 | [diff] [blame] | 3103 | std::swap(Op0, X); |
| 3104 | Pred = Cmp.getSwappedPredicate(); |
| 3105 | } |
| 3106 | |
| 3107 | Value *Y; |
Sanjay Patel | 8296c6c | 2016-12-19 16:28:53 +0000 | [diff] [blame] | 3108 | if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) { |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 3109 | // smin(X, Y) == X --> X s<= Y |
| 3110 | // smin(X, Y) s>= X --> X s<= Y |
Sanjay Patel | 8296c6c | 2016-12-19 16:28:53 +0000 | [diff] [blame] | 3111 | if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE) |
| 3112 | return new ICmpInst(ICmpInst::ICMP_SLE, X, Y); |
| 3113 | |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 3114 | // smin(X, Y) != X --> X s> Y |
| 3115 | // smin(X, Y) s< X --> X s> Y |
Sanjay Patel | 8296c6c | 2016-12-19 16:28:53 +0000 | [diff] [blame] | 3116 | if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT) |
| 3117 | return new ICmpInst(ICmpInst::ICMP_SGT, X, Y); |
| 3118 | |
| 3119 | // These cases should be handled in InstSimplify: |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 3120 | // smin(X, Y) s<= X --> true |
| 3121 | // smin(X, Y) s> X --> false |
Sanjay Patel | d640641 | 2016-12-15 19:13:37 +0000 | [diff] [blame] | 3122 | return nullptr; |
Sanjay Patel | 8296c6c | 2016-12-19 16:28:53 +0000 | [diff] [blame] | 3123 | } |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 3124 | |
Sanjay Patel | 8296c6c | 2016-12-19 16:28:53 +0000 | [diff] [blame] | 3125 | if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) { |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 3126 | // smax(X, Y) == X --> X s>= Y |
| 3127 | // smax(X, Y) s<= X --> X s>= Y |
Sanjay Patel | 8296c6c | 2016-12-19 16:28:53 +0000 | [diff] [blame] | 3128 | if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE) |
| 3129 | return new ICmpInst(ICmpInst::ICMP_SGE, X, Y); |
Sanjay Patel | d640641 | 2016-12-15 19:13:37 +0000 | [diff] [blame] | 3130 | |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 3131 | // smax(X, Y) != X --> X s< Y |
| 3132 | // smax(X, Y) s> X --> X s< Y |
Sanjay Patel | 8296c6c | 2016-12-19 16:28:53 +0000 | [diff] [blame] | 3133 | if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT) |
| 3134 | return new ICmpInst(ICmpInst::ICMP_SLT, X, Y); |
Sanjay Patel | d640641 | 2016-12-15 19:13:37 +0000 | [diff] [blame] | 3135 | |
Sanjay Patel | 8296c6c | 2016-12-19 16:28:53 +0000 | [diff] [blame] | 3136 | // These cases should be handled in InstSimplify: |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 3137 | // smax(X, Y) s>= X --> true |
| 3138 | // smax(X, Y) s< X --> false |
| 3139 | return nullptr; |
| 3140 | } |
| 3141 | |
| 3142 | if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) { |
| 3143 | // umin(X, Y) == X --> X u<= Y |
| 3144 | // umin(X, Y) u>= X --> X u<= Y |
| 3145 | if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE) |
| 3146 | return new ICmpInst(ICmpInst::ICMP_ULE, X, Y); |
| 3147 | |
| 3148 | // umin(X, Y) != X --> X u> Y |
| 3149 | // umin(X, Y) u< X --> X u> Y |
| 3150 | if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT) |
| 3151 | return new ICmpInst(ICmpInst::ICMP_UGT, X, Y); |
| 3152 | |
| 3153 | // These cases should be handled in InstSimplify: |
| 3154 | // umin(X, Y) u<= X --> true |
| 3155 | // umin(X, Y) u> X --> false |
| 3156 | return nullptr; |
| 3157 | } |
| 3158 | |
| 3159 | if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) { |
| 3160 | // umax(X, Y) == X --> X u>= Y |
| 3161 | // umax(X, Y) u<= X --> X u>= Y |
| 3162 | if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE) |
| 3163 | return new ICmpInst(ICmpInst::ICMP_UGE, X, Y); |
| 3164 | |
| 3165 | // umax(X, Y) != X --> X u< Y |
| 3166 | // umax(X, Y) u> X --> X u< Y |
| 3167 | if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT) |
| 3168 | return new ICmpInst(ICmpInst::ICMP_ULT, X, Y); |
| 3169 | |
| 3170 | // These cases should be handled in InstSimplify: |
| 3171 | // umax(X, Y) u>= X --> true |
| 3172 | // umax(X, Y) u< X --> false |
Sanjay Patel | 8296c6c | 2016-12-19 16:28:53 +0000 | [diff] [blame] | 3173 | return nullptr; |
| 3174 | } |
Sanjay Patel | d640641 | 2016-12-15 19:13:37 +0000 | [diff] [blame] | 3175 | |
Sanjay Patel | d640641 | 2016-12-15 19:13:37 +0000 | [diff] [blame] | 3176 | return nullptr; |
| 3177 | } |
| 3178 | |
Sanjay Patel | 10494b2 | 2016-09-16 16:10:22 +0000 | [diff] [blame] | 3179 | Instruction *InstCombiner::foldICmpEquality(ICmpInst &I) { |
| 3180 | if (!I.isEquality()) |
| 3181 | return nullptr; |
| 3182 | |
| 3183 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 3184 | Value *A, *B, *C, *D; |
| 3185 | if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) { |
| 3186 | if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0 |
| 3187 | Value *OtherVal = A == Op1 ? B : A; |
| 3188 | return new ICmpInst(I.getPredicate(), OtherVal, |
| 3189 | Constant::getNullValue(A->getType())); |
| 3190 | } |
| 3191 | |
| 3192 | if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) { |
| 3193 | // A^c1 == C^c2 --> A == C^(c1^c2) |
| 3194 | ConstantInt *C1, *C2; |
| 3195 | if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) && |
| 3196 | Op1->hasOneUse()) { |
| 3197 | Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue()); |
| 3198 | Value *Xor = Builder->CreateXor(C, NC); |
| 3199 | return new ICmpInst(I.getPredicate(), A, Xor); |
| 3200 | } |
| 3201 | |
| 3202 | // A^B == A^D -> B == D |
| 3203 | if (A == C) |
| 3204 | return new ICmpInst(I.getPredicate(), B, D); |
| 3205 | if (A == D) |
| 3206 | return new ICmpInst(I.getPredicate(), B, C); |
| 3207 | if (B == C) |
| 3208 | return new ICmpInst(I.getPredicate(), A, D); |
| 3209 | if (B == D) |
| 3210 | return new ICmpInst(I.getPredicate(), A, C); |
| 3211 | } |
| 3212 | } |
| 3213 | |
| 3214 | if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) { |
| 3215 | // A == (A^B) -> B == 0 |
| 3216 | Value *OtherVal = A == Op0 ? B : A; |
| 3217 | return new ICmpInst(I.getPredicate(), OtherVal, |
| 3218 | Constant::getNullValue(A->getType())); |
| 3219 | } |
| 3220 | |
| 3221 | // (X&Z) == (Y&Z) -> (X^Y) & Z == 0 |
| 3222 | if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) && |
| 3223 | match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) { |
| 3224 | Value *X = nullptr, *Y = nullptr, *Z = nullptr; |
| 3225 | |
| 3226 | if (A == C) { |
| 3227 | X = B; |
| 3228 | Y = D; |
| 3229 | Z = A; |
| 3230 | } else if (A == D) { |
| 3231 | X = B; |
| 3232 | Y = C; |
| 3233 | Z = A; |
| 3234 | } else if (B == C) { |
| 3235 | X = A; |
| 3236 | Y = D; |
| 3237 | Z = B; |
| 3238 | } else if (B == D) { |
| 3239 | X = A; |
| 3240 | Y = C; |
| 3241 | Z = B; |
| 3242 | } |
| 3243 | |
| 3244 | if (X) { // Build (X^Y) & Z |
| 3245 | Op1 = Builder->CreateXor(X, Y); |
| 3246 | Op1 = Builder->CreateAnd(Op1, Z); |
| 3247 | I.setOperand(0, Op1); |
| 3248 | I.setOperand(1, Constant::getNullValue(Op1->getType())); |
| 3249 | return &I; |
| 3250 | } |
| 3251 | } |
| 3252 | |
| 3253 | // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B) |
| 3254 | // and (B & (1<<X)-1) == (zext A) --> A == (trunc B) |
| 3255 | ConstantInt *Cst1; |
| 3256 | if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) && |
| 3257 | match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) || |
| 3258 | (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) && |
| 3259 | match(Op1, m_ZExt(m_Value(A))))) { |
| 3260 | APInt Pow2 = Cst1->getValue() + 1; |
| 3261 | if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) && |
| 3262 | Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth()) |
| 3263 | return new ICmpInst(I.getPredicate(), A, |
| 3264 | Builder->CreateTrunc(B, A->getType())); |
| 3265 | } |
| 3266 | |
| 3267 | // (A >> C) == (B >> C) --> (A^B) u< (1 << C) |
| 3268 | // For lshr and ashr pairs. |
| 3269 | if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) && |
| 3270 | match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) || |
| 3271 | (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) && |
| 3272 | match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) { |
| 3273 | unsigned TypeBits = Cst1->getBitWidth(); |
| 3274 | unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits); |
| 3275 | if (ShAmt < TypeBits && ShAmt != 0) { |
| 3276 | ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE |
| 3277 | ? ICmpInst::ICMP_UGE |
| 3278 | : ICmpInst::ICMP_ULT; |
| 3279 | Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted"); |
| 3280 | APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt); |
| 3281 | return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal)); |
| 3282 | } |
| 3283 | } |
| 3284 | |
| 3285 | // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0 |
| 3286 | if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) && |
| 3287 | match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) { |
| 3288 | unsigned TypeBits = Cst1->getBitWidth(); |
| 3289 | unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits); |
| 3290 | if (ShAmt < TypeBits && ShAmt != 0) { |
| 3291 | Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted"); |
| 3292 | APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt); |
| 3293 | Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal), |
| 3294 | I.getName() + ".mask"); |
| 3295 | return new ICmpInst(I.getPredicate(), And, |
| 3296 | Constant::getNullValue(Cst1->getType())); |
| 3297 | } |
| 3298 | } |
| 3299 | |
| 3300 | // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to |
| 3301 | // "icmp (and X, mask), cst" |
| 3302 | uint64_t ShAmt = 0; |
| 3303 | if (Op0->hasOneUse() && |
| 3304 | match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) && |
| 3305 | match(Op1, m_ConstantInt(Cst1)) && |
| 3306 | // Only do this when A has multiple uses. This is most important to do |
| 3307 | // when it exposes other optimizations. |
| 3308 | !A->hasOneUse()) { |
| 3309 | unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits(); |
| 3310 | |
| 3311 | if (ShAmt < ASize) { |
| 3312 | APInt MaskV = |
| 3313 | APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits()); |
| 3314 | MaskV <<= ShAmt; |
| 3315 | |
| 3316 | APInt CmpV = Cst1->getValue().zext(ASize); |
| 3317 | CmpV <<= ShAmt; |
| 3318 | |
| 3319 | Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV)); |
| 3320 | return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV)); |
| 3321 | } |
| 3322 | } |
| 3323 | |
| 3324 | return nullptr; |
| 3325 | } |
| 3326 | |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3327 | /// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so |
| 3328 | /// far. |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 3329 | Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) { |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3330 | const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0)); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3331 | Value *LHSCIOp = LHSCI->getOperand(0); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3332 | Type *SrcTy = LHSCIOp->getType(); |
| 3333 | Type *DestTy = LHSCI->getType(); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3334 | Value *RHSCIOp; |
| 3335 | |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 3336 | // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3337 | // integer type is the same size as the pointer type. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3338 | if (LHSCI->getOpcode() == Instruction::PtrToInt && |
| 3339 | DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3340 | Value *RHSOp = nullptr; |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3341 | if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) { |
Michael Liao | d266b92 | 2015-02-13 04:51:26 +0000 | [diff] [blame] | 3342 | Value *RHSCIOp = RHSC->getOperand(0); |
| 3343 | if (RHSCIOp->getType()->getPointerAddressSpace() == |
| 3344 | LHSCIOp->getType()->getPointerAddressSpace()) { |
| 3345 | RHSOp = RHSC->getOperand(0); |
| 3346 | // If the pointer types don't match, insert a bitcast. |
| 3347 | if (LHSCIOp->getType() != RHSOp->getType()) |
| 3348 | RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType()); |
| 3349 | } |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3350 | } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3351 | RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy); |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3352 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3353 | |
| 3354 | if (RHSOp) |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3355 | return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3356 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 3357 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3358 | // The code below only handles extension cast instructions, so far. |
| 3359 | // Enforce this. |
| 3360 | if (LHSCI->getOpcode() != Instruction::ZExt && |
| 3361 | LHSCI->getOpcode() != Instruction::SExt) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3362 | return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3363 | |
| 3364 | bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt; |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3365 | bool isSignedCmp = ICmp.isSigned(); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3366 | |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3367 | if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3368 | // Not an extension from the same type? |
| 3369 | RHSCIOp = CI->getOperand(0); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 3370 | if (RHSCIOp->getType() != LHSCIOp->getType()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3371 | return nullptr; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 3372 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3373 | // If the signedness of the two casts doesn't agree (i.e. one is a sext |
| 3374 | // and the other is a zext), then we can't handle this. |
| 3375 | if (CI->getOpcode() != LHSCI->getOpcode()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3376 | return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3377 | |
| 3378 | // Deal with equality cases early. |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3379 | if (ICmp.isEquality()) |
| 3380 | return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3381 | |
| 3382 | // A signed comparison of sign extended values simplifies into a |
| 3383 | // signed comparison. |
| 3384 | if (isSignedCmp && isSignedExt) |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3385 | return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3386 | |
| 3387 | // The other three cases all fold into an unsigned comparison. |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3388 | return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3389 | } |
| 3390 | |
Sanjay Patel | 4c20423 | 2016-06-04 20:39:22 +0000 | [diff] [blame] | 3391 | // If we aren't dealing with a constant on the RHS, exit early. |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3392 | auto *C = dyn_cast<Constant>(ICmp.getOperand(1)); |
| 3393 | if (!C) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3394 | return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3395 | |
| 3396 | // Compute the constant that would happen if we truncated to SrcTy then |
Sanjay Patel | c774f8c | 2016-06-04 21:20:44 +0000 | [diff] [blame] | 3397 | // re-extended to DestTy. |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3398 | Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy); |
Sanjay Patel | c774f8c | 2016-06-04 21:20:44 +0000 | [diff] [blame] | 3399 | Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3400 | |
| 3401 | // If the re-extended constant didn't change... |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3402 | if (Res2 == C) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3403 | // Deal with equality cases early. |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3404 | if (ICmp.isEquality()) |
| 3405 | return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3406 | |
| 3407 | // A signed comparison of sign extended values simplifies into a |
| 3408 | // signed comparison. |
| 3409 | if (isSignedExt && isSignedCmp) |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3410 | return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3411 | |
| 3412 | // The other three cases all fold into an unsigned comparison. |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3413 | return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3414 | } |
| 3415 | |
Sanjay Patel | 6a333c3 | 2016-06-06 16:56:57 +0000 | [diff] [blame] | 3416 | // The re-extended constant changed, partly changed (in the case of a vector), |
| 3417 | // or could not be determined to be equal (in the case of a constant |
| 3418 | // expression), so the constant cannot be represented in the shorter type. |
| 3419 | // Consequently, we cannot emit a simple comparison. |
Duncan Sands | 8fb2c38 | 2011-01-20 13:21:55 +0000 | [diff] [blame] | 3420 | // All the cases that fold to true or false will have already been handled |
| 3421 | // by SimplifyICmpInst, so only deal with the tricky case. |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3422 | |
Sanjay Patel | 6a333c3 | 2016-06-06 16:56:57 +0000 | [diff] [blame] | 3423 | if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3424 | return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3425 | |
| 3426 | // Evaluate the comparison for LT (we invert for GT below). LE and GE cases |
| 3427 | // should have been folded away previously and not enter in here. |
Duncan Sands | 8fb2c38 | 2011-01-20 13:21:55 +0000 | [diff] [blame] | 3428 | |
| 3429 | // We're performing an unsigned comp with a sign extended value. |
| 3430 | // This is true if the input is >= 0. [aka >s -1] |
| 3431 | Constant *NegOne = Constant::getAllOnesValue(SrcTy); |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3432 | Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3433 | |
| 3434 | // Finally, return the value computed. |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3435 | if (ICmp.getPredicate() == ICmpInst::ICMP_ULT) |
| 3436 | return replaceInstUsesWith(ICmp, Result); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3437 | |
Sanjay Patel | 6f8f47b | 2016-06-05 00:12:32 +0000 | [diff] [blame] | 3438 | assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!"); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3439 | return BinaryOperator::CreateNot(Result); |
| 3440 | } |
| 3441 | |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3442 | bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS, |
| 3443 | Value *RHS, Instruction &OrigI, |
| 3444 | Value *&Result, Constant *&Overflow) { |
Sanjoy Das | 827529e | 2015-08-11 21:33:55 +0000 | [diff] [blame] | 3445 | if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS)) |
| 3446 | std::swap(LHS, RHS); |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3447 | |
| 3448 | auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) { |
| 3449 | Result = OpResult; |
| 3450 | Overflow = OverflowVal; |
| 3451 | if (ReuseName) |
| 3452 | Result->takeName(&OrigI); |
| 3453 | return true; |
| 3454 | }; |
| 3455 | |
Sanjoy Das | 6f5dca7 | 2015-08-28 19:09:31 +0000 | [diff] [blame] | 3456 | // If the overflow check was an add followed by a compare, the insertion point |
| 3457 | // may be pointing to the compare. We want to insert the new instructions |
| 3458 | // before the add in case there are uses of the add between the add and the |
| 3459 | // compare. |
| 3460 | Builder->SetInsertPoint(&OrigI); |
| 3461 | |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3462 | switch (OCF) { |
| 3463 | case OCF_INVALID: |
| 3464 | llvm_unreachable("bad overflow check kind!"); |
| 3465 | |
| 3466 | case OCF_UNSIGNED_ADD: { |
| 3467 | OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI); |
| 3468 | if (OR == OverflowResult::NeverOverflows) |
| 3469 | return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(), |
| 3470 | true); |
| 3471 | |
| 3472 | if (OR == OverflowResult::AlwaysOverflows) |
| 3473 | return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 3474 | |
| 3475 | // Fall through uadd into sadd |
| 3476 | LLVM_FALLTHROUGH; |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3477 | } |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3478 | case OCF_SIGNED_ADD: { |
David Majnemer | 27e89ba | 2015-05-21 23:04:21 +0000 | [diff] [blame] | 3479 | // X + 0 -> {X, false} |
| 3480 | if (match(RHS, m_Zero())) |
| 3481 | return SetResult(LHS, Builder->getFalse(), false); |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3482 | |
| 3483 | // We can strength reduce this signed add into a regular add if we can prove |
| 3484 | // that it will never overflow. |
| 3485 | if (OCF == OCF_SIGNED_ADD) |
| 3486 | if (WillNotOverflowSignedAdd(LHS, RHS, OrigI)) |
| 3487 | return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(), |
| 3488 | true); |
Sanjoy Das | 72cb5e1 | 2015-06-05 18:04:42 +0000 | [diff] [blame] | 3489 | break; |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3490 | } |
| 3491 | |
| 3492 | case OCF_UNSIGNED_SUB: |
| 3493 | case OCF_SIGNED_SUB: { |
David Majnemer | 27e89ba | 2015-05-21 23:04:21 +0000 | [diff] [blame] | 3494 | // X - 0 -> {X, false} |
| 3495 | if (match(RHS, m_Zero())) |
| 3496 | return SetResult(LHS, Builder->getFalse(), false); |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3497 | |
| 3498 | if (OCF == OCF_SIGNED_SUB) { |
| 3499 | if (WillNotOverflowSignedSub(LHS, RHS, OrigI)) |
| 3500 | return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(), |
| 3501 | true); |
| 3502 | } else { |
| 3503 | if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI)) |
| 3504 | return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(), |
| 3505 | true); |
| 3506 | } |
| 3507 | break; |
| 3508 | } |
| 3509 | |
| 3510 | case OCF_UNSIGNED_MUL: { |
| 3511 | OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI); |
| 3512 | if (OR == OverflowResult::NeverOverflows) |
| 3513 | return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(), |
| 3514 | true); |
| 3515 | if (OR == OverflowResult::AlwaysOverflows) |
| 3516 | return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 3517 | LLVM_FALLTHROUGH; |
| 3518 | } |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3519 | case OCF_SIGNED_MUL: |
| 3520 | // X * undef -> undef |
| 3521 | if (isa<UndefValue>(RHS)) |
David Majnemer | 27e89ba | 2015-05-21 23:04:21 +0000 | [diff] [blame] | 3522 | return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false); |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3523 | |
David Majnemer | 27e89ba | 2015-05-21 23:04:21 +0000 | [diff] [blame] | 3524 | // X * 0 -> {0, false} |
| 3525 | if (match(RHS, m_Zero())) |
| 3526 | return SetResult(RHS, Builder->getFalse(), false); |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3527 | |
David Majnemer | 27e89ba | 2015-05-21 23:04:21 +0000 | [diff] [blame] | 3528 | // X * 1 -> {X, false} |
| 3529 | if (match(RHS, m_One())) |
| 3530 | return SetResult(LHS, Builder->getFalse(), false); |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3531 | |
| 3532 | if (OCF == OCF_SIGNED_MUL) |
| 3533 | if (WillNotOverflowSignedMul(LHS, RHS, OrigI)) |
| 3534 | return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(), |
| 3535 | true); |
Sanjoy Das | c80dad6 | 2015-06-05 18:04:46 +0000 | [diff] [blame] | 3536 | break; |
Sanjoy Das | b098447 | 2015-04-08 04:27:22 +0000 | [diff] [blame] | 3537 | } |
| 3538 | |
| 3539 | return false; |
| 3540 | } |
| 3541 | |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3542 | /// \brief Recognize and process idiom involving test for multiplication |
| 3543 | /// overflow. |
| 3544 | /// |
| 3545 | /// The caller has matched a pattern of the form: |
| 3546 | /// I = cmp u (mul(zext A, zext B), V |
| 3547 | /// The function checks if this is a test for overflow and if so replaces |
| 3548 | /// multiplication with call to 'mul.with.overflow' intrinsic. |
| 3549 | /// |
| 3550 | /// \param I Compare instruction. |
| 3551 | /// \param MulVal Result of 'mult' instruction. It is one of the arguments of |
| 3552 | /// the compare instruction. Must be of integer type. |
| 3553 | /// \param OtherVal The other argument of compare instruction. |
| 3554 | /// \returns Instruction which must replace the compare instruction, NULL if no |
| 3555 | /// replacement required. |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 3556 | static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal, |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3557 | Value *OtherVal, InstCombiner &IC) { |
Benjamin Kramer | c96a7f8 | 2014-06-24 10:47:52 +0000 | [diff] [blame] | 3558 | // Don't bother doing this transformation for pointers, don't do it for |
| 3559 | // vectors. |
| 3560 | if (!isa<IntegerType>(MulVal->getType())) |
| 3561 | return nullptr; |
| 3562 | |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3563 | assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal); |
| 3564 | assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal); |
David Majnemer | daa24b9 | 2015-09-05 20:44:56 +0000 | [diff] [blame] | 3565 | auto *MulInstr = dyn_cast<Instruction>(MulVal); |
| 3566 | if (!MulInstr) |
| 3567 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3568 | assert(MulInstr->getOpcode() == Instruction::Mul); |
| 3569 | |
David Majnemer | 634ca23 | 2014-11-01 23:46:05 +0000 | [diff] [blame] | 3570 | auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)), |
| 3571 | *RHS = cast<ZExtOperator>(MulInstr->getOperand(1)); |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3572 | assert(LHS->getOpcode() == Instruction::ZExt); |
| 3573 | assert(RHS->getOpcode() == Instruction::ZExt); |
| 3574 | Value *A = LHS->getOperand(0), *B = RHS->getOperand(0); |
| 3575 | |
| 3576 | // Calculate type and width of the result produced by mul.with.overflow. |
| 3577 | Type *TyA = A->getType(), *TyB = B->getType(); |
| 3578 | unsigned WidthA = TyA->getPrimitiveSizeInBits(), |
| 3579 | WidthB = TyB->getPrimitiveSizeInBits(); |
| 3580 | unsigned MulWidth; |
| 3581 | Type *MulType; |
| 3582 | if (WidthB > WidthA) { |
| 3583 | MulWidth = WidthB; |
| 3584 | MulType = TyB; |
| 3585 | } else { |
| 3586 | MulWidth = WidthA; |
| 3587 | MulType = TyA; |
| 3588 | } |
| 3589 | |
| 3590 | // In order to replace the original mul with a narrower mul.with.overflow, |
| 3591 | // all uses must ignore upper bits of the product. The number of used low |
| 3592 | // bits must be not greater than the width of mul.with.overflow. |
| 3593 | if (MulVal->hasNUsesOrMore(2)) |
| 3594 | for (User *U : MulVal->users()) { |
| 3595 | if (U == &I) |
| 3596 | continue; |
| 3597 | if (TruncInst *TI = dyn_cast<TruncInst>(U)) { |
| 3598 | // Check if truncation ignores bits above MulWidth. |
| 3599 | unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits(); |
| 3600 | if (TruncWidth > MulWidth) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3601 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3602 | } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) { |
| 3603 | // Check if AND ignores bits above MulWidth. |
| 3604 | if (BO->getOpcode() != Instruction::And) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3605 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3606 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) { |
| 3607 | const APInt &CVal = CI->getValue(); |
| 3608 | if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3609 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3610 | } |
| 3611 | } else { |
| 3612 | // Other uses prohibit this transformation. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3613 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3614 | } |
| 3615 | } |
| 3616 | |
| 3617 | // Recognize patterns |
| 3618 | switch (I.getPredicate()) { |
| 3619 | case ICmpInst::ICMP_EQ: |
| 3620 | case ICmpInst::ICMP_NE: |
| 3621 | // Recognize pattern: |
| 3622 | // mulval = mul(zext A, zext B) |
| 3623 | // cmp eq/neq mulval, zext trunc mulval |
| 3624 | if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal)) |
| 3625 | if (Zext->hasOneUse()) { |
| 3626 | Value *ZextArg = Zext->getOperand(0); |
| 3627 | if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg)) |
| 3628 | if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth) |
| 3629 | break; //Recognized |
| 3630 | } |
| 3631 | |
| 3632 | // Recognize pattern: |
| 3633 | // mulval = mul(zext A, zext B) |
| 3634 | // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits. |
| 3635 | ConstantInt *CI; |
| 3636 | Value *ValToMask; |
| 3637 | if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) { |
| 3638 | if (ValToMask != MulVal) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3639 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3640 | const APInt &CVal = CI->getValue() + 1; |
| 3641 | if (CVal.isPowerOf2()) { |
| 3642 | unsigned MaskWidth = CVal.logBase2(); |
| 3643 | if (MaskWidth == MulWidth) |
| 3644 | break; // Recognized |
| 3645 | } |
| 3646 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3647 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3648 | |
| 3649 | case ICmpInst::ICMP_UGT: |
| 3650 | // Recognize pattern: |
| 3651 | // mulval = mul(zext A, zext B) |
| 3652 | // cmp ugt mulval, max |
| 3653 | if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { |
| 3654 | APInt MaxVal = APInt::getMaxValue(MulWidth); |
| 3655 | MaxVal = MaxVal.zext(CI->getBitWidth()); |
| 3656 | if (MaxVal.eq(CI->getValue())) |
| 3657 | break; // Recognized |
| 3658 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3659 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3660 | |
| 3661 | case ICmpInst::ICMP_UGE: |
| 3662 | // Recognize pattern: |
| 3663 | // mulval = mul(zext A, zext B) |
| 3664 | // cmp uge mulval, max+1 |
| 3665 | if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { |
| 3666 | APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); |
| 3667 | if (MaxVal.eq(CI->getValue())) |
| 3668 | break; // Recognized |
| 3669 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3670 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3671 | |
| 3672 | case ICmpInst::ICMP_ULE: |
| 3673 | // Recognize pattern: |
| 3674 | // mulval = mul(zext A, zext B) |
| 3675 | // cmp ule mulval, max |
| 3676 | if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { |
| 3677 | APInt MaxVal = APInt::getMaxValue(MulWidth); |
| 3678 | MaxVal = MaxVal.zext(CI->getBitWidth()); |
| 3679 | if (MaxVal.eq(CI->getValue())) |
| 3680 | break; // Recognized |
| 3681 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3682 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3683 | |
| 3684 | case ICmpInst::ICMP_ULT: |
| 3685 | // Recognize pattern: |
| 3686 | // mulval = mul(zext A, zext B) |
| 3687 | // cmp ule mulval, max + 1 |
| 3688 | if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { |
Serge Pavlov | b5f3ddc | 2014-04-14 02:20:19 +0000 | [diff] [blame] | 3689 | APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3690 | if (MaxVal.eq(CI->getValue())) |
| 3691 | break; // Recognized |
| 3692 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3693 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3694 | |
| 3695 | default: |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 3696 | return nullptr; |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3697 | } |
| 3698 | |
| 3699 | InstCombiner::BuilderTy *Builder = IC.Builder; |
| 3700 | Builder->SetInsertPoint(MulInstr); |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3701 | |
| 3702 | // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B) |
| 3703 | Value *MulA = A, *MulB = B; |
| 3704 | if (WidthA < MulWidth) |
| 3705 | MulA = Builder->CreateZExt(A, MulType); |
| 3706 | if (WidthB < MulWidth) |
| 3707 | MulB = Builder->CreateZExt(B, MulType); |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 3708 | Value *F = Intrinsic::getDeclaration(I.getModule(), |
| 3709 | Intrinsic::umul_with_overflow, MulType); |
David Blaikie | ff6409d | 2015-05-18 22:13:54 +0000 | [diff] [blame] | 3710 | CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul"); |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3711 | IC.Worklist.Add(MulInstr); |
| 3712 | |
| 3713 | // If there are uses of mul result other than the comparison, we know that |
| 3714 | // they are truncation or binary AND. Change them to use result of |
Serge Pavlov | b5f3ddc | 2014-04-14 02:20:19 +0000 | [diff] [blame] | 3715 | // mul.with.overflow and adjust properly mask/size. |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3716 | if (MulVal->hasNUsesOrMore(2)) { |
| 3717 | Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value"); |
| 3718 | for (User *U : MulVal->users()) { |
| 3719 | if (U == &I || U == OtherVal) |
| 3720 | continue; |
| 3721 | if (TruncInst *TI = dyn_cast<TruncInst>(U)) { |
| 3722 | if (TI->getType()->getPrimitiveSizeInBits() == MulWidth) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 3723 | IC.replaceInstUsesWith(*TI, Mul); |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3724 | else |
| 3725 | TI->setOperand(0, Mul); |
| 3726 | } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) { |
| 3727 | assert(BO->getOpcode() == Instruction::And); |
| 3728 | // Replace (mul & mask) --> zext (mul.with.overflow & short_mask) |
| 3729 | ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1)); |
| 3730 | APInt ShortMask = CI->getValue().trunc(MulWidth); |
| 3731 | Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask); |
| 3732 | Instruction *Zext = |
| 3733 | cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType())); |
| 3734 | IC.Worklist.Add(Zext); |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 3735 | IC.replaceInstUsesWith(*BO, Zext); |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 3736 | } else { |
| 3737 | llvm_unreachable("Unexpected Binary operation"); |
| 3738 | } |
| 3739 | IC.Worklist.Add(cast<Instruction>(U)); |
| 3740 | } |
| 3741 | } |
| 3742 | if (isa<Instruction>(OtherVal)) |
| 3743 | IC.Worklist.Add(cast<Instruction>(OtherVal)); |
| 3744 | |
| 3745 | // The original icmp gets replaced with the overflow value, maybe inverted |
| 3746 | // depending on predicate. |
| 3747 | bool Inverse = false; |
| 3748 | switch (I.getPredicate()) { |
| 3749 | case ICmpInst::ICMP_NE: |
| 3750 | break; |
| 3751 | case ICmpInst::ICMP_EQ: |
| 3752 | Inverse = true; |
| 3753 | break; |
| 3754 | case ICmpInst::ICMP_UGT: |
| 3755 | case ICmpInst::ICMP_UGE: |
| 3756 | if (I.getOperand(0) == MulVal) |
| 3757 | break; |
| 3758 | Inverse = true; |
| 3759 | break; |
| 3760 | case ICmpInst::ICMP_ULT: |
| 3761 | case ICmpInst::ICMP_ULE: |
| 3762 | if (I.getOperand(1) == MulVal) |
| 3763 | break; |
| 3764 | Inverse = true; |
| 3765 | break; |
| 3766 | default: |
| 3767 | llvm_unreachable("Unexpected predicate"); |
| 3768 | } |
| 3769 | if (Inverse) { |
| 3770 | Value *Res = Builder->CreateExtractValue(Call, 1); |
| 3771 | return BinaryOperator::CreateNot(Res); |
| 3772 | } |
| 3773 | |
| 3774 | return ExtractValueInst::Create(Call, 1); |
| 3775 | } |
| 3776 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 3777 | /// When performing a comparison against a constant, it is possible that not all |
| 3778 | /// the bits in the LHS are demanded. This helper method computes the mask that |
| 3779 | /// IS demanded. |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 3780 | static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth, |
| 3781 | bool isSignCheck) { |
Owen Anderson | d490c2d | 2011-01-11 00:36:45 +0000 | [diff] [blame] | 3782 | if (isSignCheck) |
| 3783 | return APInt::getSignBit(BitWidth); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 3784 | |
Owen Anderson | d490c2d | 2011-01-11 00:36:45 +0000 | [diff] [blame] | 3785 | ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1)); |
| 3786 | if (!CI) return APInt::getAllOnesValue(BitWidth); |
Owen Anderson | 0022a4b | 2011-01-11 18:26:37 +0000 | [diff] [blame] | 3787 | const APInt &RHS = CI->getValue(); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 3788 | |
Owen Anderson | d490c2d | 2011-01-11 00:36:45 +0000 | [diff] [blame] | 3789 | switch (I.getPredicate()) { |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 3790 | // For a UGT comparison, we don't care about any bits that |
Owen Anderson | d490c2d | 2011-01-11 00:36:45 +0000 | [diff] [blame] | 3791 | // correspond to the trailing ones of the comparand. The value of these |
| 3792 | // bits doesn't impact the outcome of the comparison, because any value |
| 3793 | // greater than the RHS must differ in a bit higher than these due to carry. |
| 3794 | case ICmpInst::ICMP_UGT: { |
| 3795 | unsigned trailingOnes = RHS.countTrailingOnes(); |
| 3796 | APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes); |
| 3797 | return ~lowBitsSet; |
| 3798 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 3799 | |
Owen Anderson | d490c2d | 2011-01-11 00:36:45 +0000 | [diff] [blame] | 3800 | // Similarly, for a ULT comparison, we don't care about the trailing zeros. |
| 3801 | // Any value less than the RHS must differ in a higher bit because of carries. |
| 3802 | case ICmpInst::ICMP_ULT: { |
| 3803 | unsigned trailingZeros = RHS.countTrailingZeros(); |
| 3804 | APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros); |
| 3805 | return ~lowBitsSet; |
| 3806 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 3807 | |
Owen Anderson | d490c2d | 2011-01-11 00:36:45 +0000 | [diff] [blame] | 3808 | default: |
| 3809 | return APInt::getAllOnesValue(BitWidth); |
| 3810 | } |
Owen Anderson | d490c2d | 2011-01-11 00:36:45 +0000 | [diff] [blame] | 3811 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 3812 | |
Quentin Colombet | 5ab5555 | 2013-09-09 20:56:48 +0000 | [diff] [blame] | 3813 | /// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst |
| 3814 | /// should be swapped. |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 3815 | /// The decision is based on how many times these two operands are reused |
Quentin Colombet | 5ab5555 | 2013-09-09 20:56:48 +0000 | [diff] [blame] | 3816 | /// as subtract operands and their positions in those instructions. |
| 3817 | /// The rational is that several architectures use the same instruction for |
| 3818 | /// both subtract and cmp, thus it is better if the order of those operands |
| 3819 | /// match. |
| 3820 | /// \return true if Op0 and Op1 should be swapped. |
| 3821 | static bool swapMayExposeCSEOpportunities(const Value * Op0, |
| 3822 | const Value * Op1) { |
| 3823 | // Filter out pointer value as those cannot appears directly in subtract. |
| 3824 | // FIXME: we may want to go through inttoptrs or bitcasts. |
| 3825 | if (Op0->getType()->isPointerTy()) |
| 3826 | return false; |
| 3827 | // Count every uses of both Op0 and Op1 in a subtract. |
| 3828 | // Each time Op0 is the first operand, count -1: swapping is bad, the |
| 3829 | // subtract has already the same layout as the compare. |
| 3830 | // Each time Op0 is the second operand, count +1: swapping is good, the |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 3831 | // subtract has a different layout as the compare. |
Quentin Colombet | 5ab5555 | 2013-09-09 20:56:48 +0000 | [diff] [blame] | 3832 | // At the end, if the benefit is greater than 0, Op0 should come second to |
| 3833 | // expose more CSE opportunities. |
| 3834 | int GlobalSwapBenefits = 0; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3835 | for (const User *U : Op0->users()) { |
| 3836 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U); |
Quentin Colombet | 5ab5555 | 2013-09-09 20:56:48 +0000 | [diff] [blame] | 3837 | if (!BinOp || BinOp->getOpcode() != Instruction::Sub) |
| 3838 | continue; |
| 3839 | // If Op0 is the first argument, this is not beneficial to swap the |
| 3840 | // arguments. |
| 3841 | int LocalSwapBenefits = -1; |
| 3842 | unsigned Op1Idx = 1; |
| 3843 | if (BinOp->getOperand(Op1Idx) == Op0) { |
| 3844 | Op1Idx = 0; |
| 3845 | LocalSwapBenefits = 1; |
| 3846 | } |
| 3847 | if (BinOp->getOperand(Op1Idx) != Op1) |
| 3848 | continue; |
| 3849 | GlobalSwapBenefits += LocalSwapBenefits; |
| 3850 | } |
| 3851 | return GlobalSwapBenefits > 0; |
| 3852 | } |
| 3853 | |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3854 | /// \brief Check that one use is in the same block as the definition and all |
Sanjay Patel | 5352331 | 2016-09-12 14:25:46 +0000 | [diff] [blame] | 3855 | /// other uses are in blocks dominated by a given block. |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3856 | /// |
| 3857 | /// \param DI Definition |
| 3858 | /// \param UI Use |
| 3859 | /// \param DB Block that must dominate all uses of \p DI outside |
| 3860 | /// the parent block |
| 3861 | /// \return true when \p UI is the only use of \p DI in the parent block |
| 3862 | /// and all other uses of \p DI are in blocks dominated by \p DB. |
| 3863 | /// |
| 3864 | bool InstCombiner::dominatesAllUses(const Instruction *DI, |
| 3865 | const Instruction *UI, |
| 3866 | const BasicBlock *DB) const { |
| 3867 | assert(DI && UI && "Instruction not defined\n"); |
Sanjay Patel | 5352331 | 2016-09-12 14:25:46 +0000 | [diff] [blame] | 3868 | // Ignore incomplete definitions. |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3869 | if (!DI->getParent()) |
| 3870 | return false; |
Sanjay Patel | 5352331 | 2016-09-12 14:25:46 +0000 | [diff] [blame] | 3871 | // DI and UI must be in the same block. |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3872 | if (DI->getParent() != UI->getParent()) |
| 3873 | return false; |
Sanjay Patel | 5352331 | 2016-09-12 14:25:46 +0000 | [diff] [blame] | 3874 | // Protect from self-referencing blocks. |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3875 | if (DI->getParent() == DB) |
| 3876 | return false; |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3877 | for (const User *U : DI->users()) { |
| 3878 | auto *Usr = cast<Instruction>(U); |
Justin Bogner | 9979840 | 2016-08-05 01:06:44 +0000 | [diff] [blame] | 3879 | if (Usr != UI && !DT.dominates(DB, Usr->getParent())) |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3880 | return false; |
| 3881 | } |
| 3882 | return true; |
| 3883 | } |
| 3884 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 3885 | /// Return true when the instruction sequence within a block is select-cmp-br. |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3886 | static bool isChainSelectCmpBranch(const SelectInst *SI) { |
| 3887 | const BasicBlock *BB = SI->getParent(); |
| 3888 | if (!BB) |
| 3889 | return false; |
| 3890 | auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator()); |
| 3891 | if (!BI || BI->getNumSuccessors() != 2) |
| 3892 | return false; |
| 3893 | auto *IC = dyn_cast<ICmpInst>(BI->getCondition()); |
| 3894 | if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI)) |
| 3895 | return false; |
| 3896 | return true; |
| 3897 | } |
| 3898 | |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3899 | /// \brief True when a select result is replaced by one of its operands |
| 3900 | /// in select-icmp sequence. This will eventually result in the elimination |
| 3901 | /// of the select. |
| 3902 | /// |
| 3903 | /// \param SI Select instruction |
| 3904 | /// \param Icmp Compare instruction |
| 3905 | /// \param SIOpd Operand that replaces the select |
| 3906 | /// |
| 3907 | /// Notes: |
| 3908 | /// - The replacement is global and requires dominator information |
| 3909 | /// - The caller is responsible for the actual replacement |
| 3910 | /// |
| 3911 | /// Example: |
| 3912 | /// |
| 3913 | /// entry: |
| 3914 | /// %4 = select i1 %3, %C* %0, %C* null |
| 3915 | /// %5 = icmp eq %C* %4, null |
| 3916 | /// br i1 %5, label %9, label %7 |
| 3917 | /// ... |
| 3918 | /// ; <label>:7 ; preds = %entry |
| 3919 | /// %8 = getelementptr inbounds %C* %4, i64 0, i32 0 |
| 3920 | /// ... |
| 3921 | /// |
| 3922 | /// can be transformed to |
| 3923 | /// |
| 3924 | /// %5 = icmp eq %C* %0, null |
| 3925 | /// %6 = select i1 %3, i1 %5, i1 true |
| 3926 | /// br i1 %6, label %9, label %7 |
| 3927 | /// ... |
| 3928 | /// ; <label>:7 ; preds = %entry |
| 3929 | /// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0! |
| 3930 | /// |
| 3931 | /// Similar when the first operand of the select is a constant or/and |
| 3932 | /// the compare is for not equal rather than equal. |
| 3933 | /// |
| 3934 | /// NOTE: The function is only called when the select and compare constants |
| 3935 | /// are equal, the optimization can work only for EQ predicates. This is not a |
| 3936 | /// major restriction since a NE compare should be 'normalized' to an equal |
| 3937 | /// compare, which usually happens in the combiner and test case |
Sanjay Patel | 5352331 | 2016-09-12 14:25:46 +0000 | [diff] [blame] | 3938 | /// select-cmp-br.ll checks for it. |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3939 | bool InstCombiner::replacedSelectWithOperand(SelectInst *SI, |
| 3940 | const ICmpInst *Icmp, |
| 3941 | const unsigned SIOpd) { |
David Majnemer | 83484fd | 2014-11-22 06:09:28 +0000 | [diff] [blame] | 3942 | assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!"); |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3943 | if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) { |
| 3944 | BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1); |
| 3945 | // The check for the unique predecessor is not the best that can be |
Sanjay Patel | 5352331 | 2016-09-12 14:25:46 +0000 | [diff] [blame] | 3946 | // done. But it protects efficiently against cases like when SI's |
Gerolf Hoflehner | ec6217c | 2014-11-21 23:36:44 +0000 | [diff] [blame] | 3947 | // home block has two successors, Succ and Succ1, and Succ1 predecessor |
| 3948 | // of Succ. Then SI can't be replaced by SIOpd because the use that gets |
| 3949 | // replaced can be reached on either path. So the uniqueness check |
| 3950 | // guarantees that the path all uses of SI (outside SI's parent) are on |
| 3951 | // is disjoint from all other paths out of SI. But that information |
| 3952 | // is more expensive to compute, and the trade-off here is in favor |
| 3953 | // of compile-time. |
| 3954 | if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) { |
| 3955 | NumSel++; |
| 3956 | SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent()); |
| 3957 | return true; |
| 3958 | } |
| 3959 | } |
| 3960 | return false; |
| 3961 | } |
| 3962 | |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 3963 | /// Try to fold the comparison based on range information we can get by checking |
| 3964 | /// whether bits are known to be zero or one in the inputs. |
| 3965 | Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) { |
| 3966 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 3967 | Type *Ty = Op0->getType(); |
Sanjay Patel | 0531f0a | 2016-09-12 15:52:28 +0000 | [diff] [blame] | 3968 | ICmpInst::Predicate Pred = I.getPredicate(); |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 3969 | |
| 3970 | // Get scalar or pointer size. |
| 3971 | unsigned BitWidth = Ty->isIntOrIntVectorTy() |
| 3972 | ? Ty->getScalarSizeInBits() |
| 3973 | : DL.getTypeSizeInBits(Ty->getScalarType()); |
| 3974 | |
| 3975 | if (!BitWidth) |
| 3976 | return nullptr; |
| 3977 | |
| 3978 | // If this is a normal comparison, it demands all bits. If it is a sign bit |
| 3979 | // comparison, it only demands the sign bit. |
| 3980 | bool IsSignBit = false; |
Sanjay Patel | f5887f1 | 2016-09-12 16:25:41 +0000 | [diff] [blame] | 3981 | const APInt *CmpC; |
| 3982 | if (match(Op1, m_APInt(CmpC))) { |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 3983 | bool UnusedBit; |
Sanjay Patel | f5887f1 | 2016-09-12 16:25:41 +0000 | [diff] [blame] | 3984 | IsSignBit = isSignBitCheck(Pred, *CmpC, UnusedBit); |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 3985 | } |
| 3986 | |
| 3987 | APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0); |
| 3988 | APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0); |
| 3989 | |
| 3990 | if (SimplifyDemandedBits(I.getOperandUse(0), |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 3991 | getDemandedBitsLHSMask(I, BitWidth, IsSignBit), |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 3992 | Op0KnownZero, Op0KnownOne, 0)) |
| 3993 | return &I; |
| 3994 | |
| 3995 | if (SimplifyDemandedBits(I.getOperandUse(1), APInt::getAllOnesValue(BitWidth), |
| 3996 | Op1KnownZero, Op1KnownOne, 0)) |
| 3997 | return &I; |
| 3998 | |
| 3999 | // Given the known and unknown bits, compute a range that the LHS could be |
| 4000 | // in. Compute the Min, Max and RHS values based on the known bits. For the |
| 4001 | // EQ and NE we use unsigned values. |
| 4002 | APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0); |
| 4003 | APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0); |
| 4004 | if (I.isSigned()) { |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 4005 | computeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min, |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4006 | Op0Max); |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 4007 | computeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min, |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4008 | Op1Max); |
| 4009 | } else { |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 4010 | computeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min, |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4011 | Op0Max); |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 4012 | computeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min, |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4013 | Op1Max); |
| 4014 | } |
| 4015 | |
| 4016 | // If Min and Max are known to be the same, then SimplifyDemandedBits |
Sanjay Patel | 0531f0a | 2016-09-12 15:52:28 +0000 | [diff] [blame] | 4017 | // figured out that the LHS is a constant. Constant fold this now, so that |
| 4018 | // code below can assume that Min != Max. |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4019 | if (!isa<Constant>(Op0) && Op0Min == Op0Max) |
Sanjay Patel | 0531f0a | 2016-09-12 15:52:28 +0000 | [diff] [blame] | 4020 | return new ICmpInst(Pred, ConstantInt::get(Op0->getType(), Op0Min), Op1); |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4021 | if (!isa<Constant>(Op1) && Op1Min == Op1Max) |
Sanjay Patel | 0531f0a | 2016-09-12 15:52:28 +0000 | [diff] [blame] | 4022 | return new ICmpInst(Pred, Op0, ConstantInt::get(Op1->getType(), Op1Min)); |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4023 | |
| 4024 | // Based on the range information we know about the LHS, see if we can |
| 4025 | // simplify this comparison. For example, (x&4) < 8 is always true. |
Sanjay Patel | 0531f0a | 2016-09-12 15:52:28 +0000 | [diff] [blame] | 4026 | switch (Pred) { |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4027 | default: |
| 4028 | llvm_unreachable("Unknown icmp opcode!"); |
Sanjay Patel | 9efb1bd | 2016-09-14 23:38:56 +0000 | [diff] [blame] | 4029 | case ICmpInst::ICMP_EQ: |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4030 | case ICmpInst::ICMP_NE: { |
Sanjay Patel | 9efb1bd | 2016-09-14 23:38:56 +0000 | [diff] [blame] | 4031 | if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) { |
| 4032 | return Pred == CmpInst::ICMP_EQ |
| 4033 | ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())) |
| 4034 | : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); |
| 4035 | } |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4036 | |
Sanjay Patel | 0531f0a | 2016-09-12 15:52:28 +0000 | [diff] [blame] | 4037 | // If all bits are known zero except for one, then we know at most one bit |
| 4038 | // is set. If the comparison is against zero, then this is a check to see if |
| 4039 | // *that* bit is set. |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4040 | APInt Op0KnownZeroInverted = ~Op0KnownZero; |
| 4041 | if (~Op1KnownZero == 0) { |
| 4042 | // If the LHS is an AND with the same constant, look through it. |
| 4043 | Value *LHS = nullptr; |
Sanjay Patel | 7577a3d | 2016-09-15 14:15:47 +0000 | [diff] [blame] | 4044 | const APInt *LHSC; |
| 4045 | if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) || |
| 4046 | *LHSC != Op0KnownZeroInverted) |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4047 | LHS = Op0; |
| 4048 | |
Sanjay Patel | 9efb1bd | 2016-09-14 23:38:56 +0000 | [diff] [blame] | 4049 | Value *X; |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4050 | if (match(LHS, m_Shl(m_One(), m_Value(X)))) { |
| 4051 | APInt ValToCheck = Op0KnownZeroInverted; |
Sanjay Patel | 9efb1bd | 2016-09-14 23:38:56 +0000 | [diff] [blame] | 4052 | Type *XTy = X->getType(); |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4053 | if (ValToCheck.isPowerOf2()) { |
Sanjay Patel | 9efb1bd | 2016-09-14 23:38:56 +0000 | [diff] [blame] | 4054 | // ((1 << X) & 8) == 0 -> X != 3 |
| 4055 | // ((1 << X) & 8) != 0 -> X == 3 |
| 4056 | auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros()); |
| 4057 | auto NewPred = ICmpInst::getInversePredicate(Pred); |
| 4058 | return new ICmpInst(NewPred, X, CmpC); |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4059 | } else if ((++ValToCheck).isPowerOf2()) { |
Sanjay Patel | 9efb1bd | 2016-09-14 23:38:56 +0000 | [diff] [blame] | 4060 | // ((1 << X) & 7) == 0 -> X >= 3 |
| 4061 | // ((1 << X) & 7) != 0 -> X < 3 |
| 4062 | auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros()); |
| 4063 | auto NewPred = |
| 4064 | Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT; |
| 4065 | return new ICmpInst(NewPred, X, CmpC); |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4066 | } |
| 4067 | } |
| 4068 | |
Sanjay Patel | 9efb1bd | 2016-09-14 23:38:56 +0000 | [diff] [blame] | 4069 | // Check if the LHS is 8 >>u x and the result is a power of 2 like 1. |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4070 | const APInt *CI; |
| 4071 | if (Op0KnownZeroInverted == 1 && |
Sanjay Patel | 9efb1bd | 2016-09-14 23:38:56 +0000 | [diff] [blame] | 4072 | match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) { |
| 4073 | // ((8 >>u X) & 1) == 0 -> X != 3 |
| 4074 | // ((8 >>u X) & 1) != 0 -> X == 3 |
| 4075 | unsigned CmpVal = CI->countTrailingZeros(); |
| 4076 | auto NewPred = ICmpInst::getInversePredicate(Pred); |
| 4077 | return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal)); |
| 4078 | } |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4079 | } |
| 4080 | break; |
| 4081 | } |
| 4082 | case ICmpInst::ICMP_ULT: { |
| 4083 | if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B) |
| 4084 | return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); |
| 4085 | if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B) |
| 4086 | return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); |
| 4087 | if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B) |
| 4088 | return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); |
| 4089 | |
| 4090 | const APInt *CmpC; |
| 4091 | if (match(Op1, m_APInt(CmpC))) { |
| 4092 | // A <u C -> A == C-1 if min(A)+1 == C |
| 4093 | if (Op1Max == Op0Min + 1) { |
| 4094 | Constant *CMinus1 = ConstantInt::get(Op0->getType(), *CmpC - 1); |
| 4095 | return new ICmpInst(ICmpInst::ICMP_EQ, Op0, CMinus1); |
| 4096 | } |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4097 | } |
| 4098 | break; |
| 4099 | } |
| 4100 | case ICmpInst::ICMP_UGT: { |
| 4101 | if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B) |
| 4102 | return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); |
| 4103 | |
| 4104 | if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B) |
| 4105 | return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); |
| 4106 | |
| 4107 | if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B) |
| 4108 | return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); |
| 4109 | |
| 4110 | const APInt *CmpC; |
| 4111 | if (match(Op1, m_APInt(CmpC))) { |
| 4112 | // A >u C -> A == C+1 if max(a)-1 == C |
| 4113 | if (*CmpC == Op0Max - 1) |
| 4114 | return new ICmpInst(ICmpInst::ICMP_EQ, Op0, |
| 4115 | ConstantInt::get(Op1->getType(), *CmpC + 1)); |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4116 | } |
| 4117 | break; |
| 4118 | } |
| 4119 | case ICmpInst::ICMP_SLT: |
| 4120 | if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C) |
| 4121 | return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); |
| 4122 | if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C) |
| 4123 | return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); |
| 4124 | if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B) |
| 4125 | return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); |
| 4126 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { |
| 4127 | if (Op1Max == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C |
| 4128 | return new ICmpInst(ICmpInst::ICMP_EQ, Op0, |
| 4129 | Builder->getInt(CI->getValue() - 1)); |
| 4130 | } |
| 4131 | break; |
| 4132 | case ICmpInst::ICMP_SGT: |
| 4133 | if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B) |
| 4134 | return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); |
| 4135 | if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B) |
| 4136 | return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); |
| 4137 | |
| 4138 | if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B) |
| 4139 | return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); |
| 4140 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { |
| 4141 | if (Op1Min == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C |
| 4142 | return new ICmpInst(ICmpInst::ICMP_EQ, Op0, |
| 4143 | Builder->getInt(CI->getValue() + 1)); |
| 4144 | } |
| 4145 | break; |
| 4146 | case ICmpInst::ICMP_SGE: |
| 4147 | assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!"); |
| 4148 | if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B) |
| 4149 | return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); |
| 4150 | if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B) |
| 4151 | return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); |
| 4152 | break; |
| 4153 | case ICmpInst::ICMP_SLE: |
| 4154 | assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!"); |
| 4155 | if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B) |
| 4156 | return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); |
| 4157 | if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B) |
| 4158 | return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); |
| 4159 | break; |
| 4160 | case ICmpInst::ICMP_UGE: |
| 4161 | assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!"); |
| 4162 | if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B) |
| 4163 | return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); |
| 4164 | if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B) |
| 4165 | return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); |
| 4166 | break; |
| 4167 | case ICmpInst::ICMP_ULE: |
| 4168 | assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!"); |
| 4169 | if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B) |
| 4170 | return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); |
| 4171 | if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B) |
| 4172 | return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); |
| 4173 | break; |
| 4174 | } |
| 4175 | |
| 4176 | // Turn a signed comparison into an unsigned one if both operands are known to |
| 4177 | // have the same sign. |
| 4178 | if (I.isSigned() && |
| 4179 | ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) || |
| 4180 | (Op0KnownOne.isNegative() && Op1KnownOne.isNegative()))) |
| 4181 | return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1); |
| 4182 | |
| 4183 | return nullptr; |
| 4184 | } |
| 4185 | |
Sanjay Patel | d5b0e54 | 2016-04-29 16:22:25 +0000 | [diff] [blame] | 4186 | /// If we have an icmp le or icmp ge instruction with a constant operand, turn |
| 4187 | /// it into the appropriate icmp lt or icmp gt instruction. This transform |
| 4188 | /// allows them to be folded in visitICmpInst. |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4189 | static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) { |
| 4190 | ICmpInst::Predicate Pred = I.getPredicate(); |
| 4191 | if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE && |
| 4192 | Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE) |
| 4193 | return nullptr; |
| 4194 | |
Sanjay Patel | d5b0e54 | 2016-04-29 16:22:25 +0000 | [diff] [blame] | 4195 | Value *Op0 = I.getOperand(0); |
| 4196 | Value *Op1 = I.getOperand(1); |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4197 | auto *Op1C = dyn_cast<Constant>(Op1); |
| 4198 | if (!Op1C) |
| 4199 | return nullptr; |
Sanjay Patel | d5b0e54 | 2016-04-29 16:22:25 +0000 | [diff] [blame] | 4200 | |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4201 | // Check if the constant operand can be safely incremented/decremented without |
| 4202 | // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled |
| 4203 | // the edge cases for us, so we just assert on them. For vectors, we must |
| 4204 | // handle the edge cases. |
| 4205 | Type *Op1Type = Op1->getType(); |
| 4206 | bool IsSigned = I.isSigned(); |
| 4207 | bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE); |
Sanjay Patel | 1825493 | 2016-05-17 01:12:31 +0000 | [diff] [blame] | 4208 | auto *CI = dyn_cast<ConstantInt>(Op1C); |
| 4209 | if (CI) { |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4210 | // A <= MAX -> TRUE ; A >= MIN -> TRUE |
| 4211 | assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned)); |
| 4212 | } else if (Op1Type->isVectorTy()) { |
Sanjay Patel | b79ab27 | 2016-05-13 15:10:46 +0000 | [diff] [blame] | 4213 | // TODO? If the edge cases for vectors were guaranteed to be handled as they |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4214 | // are for scalar, we could remove the min/max checks. However, to do that, |
| 4215 | // we would have to use insertelement/shufflevector to replace edge values. |
| 4216 | unsigned NumElts = Op1Type->getVectorNumElements(); |
| 4217 | for (unsigned i = 0; i != NumElts; ++i) { |
| 4218 | Constant *Elt = Op1C->getAggregateElement(i); |
Benjamin Kramer | ca9a0fe | 2016-05-17 12:08:55 +0000 | [diff] [blame] | 4219 | if (!Elt) |
| 4220 | return nullptr; |
| 4221 | |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4222 | if (isa<UndefValue>(Elt)) |
| 4223 | continue; |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 4224 | |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4225 | // Bail out if we can't determine if this constant is min/max or if we |
| 4226 | // know that this constant is min/max. |
| 4227 | auto *CI = dyn_cast<ConstantInt>(Elt); |
| 4228 | if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned))) |
| 4229 | return nullptr; |
Sanjay Patel | b79ab27 | 2016-05-13 15:10:46 +0000 | [diff] [blame] | 4230 | } |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4231 | } else { |
| 4232 | // ConstantExpr? |
| 4233 | return nullptr; |
Sanjay Patel | b79ab27 | 2016-05-13 15:10:46 +0000 | [diff] [blame] | 4234 | } |
Sanjay Patel | d5b0e54 | 2016-04-29 16:22:25 +0000 | [diff] [blame] | 4235 | |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4236 | // Increment or decrement the constant and set the new comparison predicate: |
| 4237 | // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT |
Sanjay Patel | 22b01fe | 2016-05-17 20:20:40 +0000 | [diff] [blame] | 4238 | Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true); |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4239 | CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT; |
| 4240 | NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred; |
| 4241 | return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne)); |
Sanjay Patel | d5b0e54 | 2016-04-29 16:22:25 +0000 | [diff] [blame] | 4242 | } |
| 4243 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4244 | Instruction *InstCombiner::visitICmpInst(ICmpInst &I) { |
| 4245 | bool Changed = false; |
Chris Lattner | 9306ffa | 2010-02-01 19:54:45 +0000 | [diff] [blame] | 4246 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
Quentin Colombet | 5ab5555 | 2013-09-09 20:56:48 +0000 | [diff] [blame] | 4247 | unsigned Op0Cplxity = getComplexity(Op0); |
| 4248 | unsigned Op1Cplxity = getComplexity(Op1); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4249 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4250 | /// Orders the operands of the compare so that they are listed from most |
| 4251 | /// complex to least complex. This puts constants before unary operators, |
| 4252 | /// before binary operators. |
Quentin Colombet | 5ab5555 | 2013-09-09 20:56:48 +0000 | [diff] [blame] | 4253 | if (Op0Cplxity < Op1Cplxity || |
Sanjay Patel | 4c20423 | 2016-06-04 20:39:22 +0000 | [diff] [blame] | 4254 | (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4255 | I.swapOperands(); |
Chris Lattner | 9306ffa | 2010-02-01 19:54:45 +0000 | [diff] [blame] | 4256 | std::swap(Op0, Op1); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4257 | Changed = true; |
| 4258 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4259 | |
Jingyue Wu | 5e34ce3 | 2015-06-25 20:14:47 +0000 | [diff] [blame] | 4260 | if (Value *V = |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 4261 | SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &AC, &I)) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4262 | return replaceInstUsesWith(I, V); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4263 | |
Pete Cooper | bc5c524 | 2011-12-01 03:58:40 +0000 | [diff] [blame] | 4264 | // comparing -val or val with non-zero is the same as just comparing val |
Pete Cooper | fdddc27 | 2011-12-01 19:13:26 +0000 | [diff] [blame] | 4265 | // ie, abs(val) != 0 -> val != 0 |
Sanjay Patel | 4c20423 | 2016-06-04 20:39:22 +0000 | [diff] [blame] | 4266 | if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) { |
Pete Cooper | fdddc27 | 2011-12-01 19:13:26 +0000 | [diff] [blame] | 4267 | Value *Cond, *SelectTrue, *SelectFalse; |
| 4268 | if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue), |
Pete Cooper | bc5c524 | 2011-12-01 03:58:40 +0000 | [diff] [blame] | 4269 | m_Value(SelectFalse)))) { |
Pete Cooper | fdddc27 | 2011-12-01 19:13:26 +0000 | [diff] [blame] | 4270 | if (Value *V = dyn_castNegVal(SelectTrue)) { |
| 4271 | if (V == SelectFalse) |
| 4272 | return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); |
| 4273 | } |
| 4274 | else if (Value *V = dyn_castNegVal(SelectFalse)) { |
| 4275 | if (V == SelectTrue) |
| 4276 | return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); |
Pete Cooper | bc5c524 | 2011-12-01 03:58:40 +0000 | [diff] [blame] | 4277 | } |
| 4278 | } |
| 4279 | } |
| 4280 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 4281 | Type *Ty = Op0->getType(); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4282 | |
| 4283 | // icmp's with boolean values can always be turned into bitwise operations |
Sanjay Patel | a6fbc82 | 2016-06-05 17:49:45 +0000 | [diff] [blame] | 4284 | if (Ty->getScalarType()->isIntegerTy(1)) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4285 | switch (I.getPredicate()) { |
| 4286 | default: llvm_unreachable("Invalid icmp instruction!"); |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 4287 | case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B) |
| 4288 | Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp"); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4289 | return BinaryOperator::CreateNot(Xor); |
| 4290 | } |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 4291 | case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4292 | return BinaryOperator::CreateXor(Op0, Op1); |
| 4293 | |
| 4294 | case ICmpInst::ICMP_UGT: |
| 4295 | std::swap(Op0, Op1); // Change icmp ugt -> icmp ult |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 4296 | LLVM_FALLTHROUGH; |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 4297 | case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B |
| 4298 | Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp"); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4299 | return BinaryOperator::CreateAnd(Not, Op1); |
| 4300 | } |
| 4301 | case ICmpInst::ICMP_SGT: |
| 4302 | std::swap(Op0, Op1); // Change icmp sgt -> icmp slt |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 4303 | LLVM_FALLTHROUGH; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4304 | case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 4305 | Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp"); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4306 | return BinaryOperator::CreateAnd(Not, Op0); |
| 4307 | } |
| 4308 | case ICmpInst::ICMP_UGE: |
| 4309 | std::swap(Op0, Op1); // Change icmp uge -> icmp ule |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 4310 | LLVM_FALLTHROUGH; |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 4311 | case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B |
| 4312 | Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp"); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4313 | return BinaryOperator::CreateOr(Not, Op1); |
| 4314 | } |
| 4315 | case ICmpInst::ICMP_SGE: |
| 4316 | std::swap(Op0, Op1); // Change icmp sge -> icmp sle |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 4317 | LLVM_FALLTHROUGH; |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 4318 | case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B |
| 4319 | Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp"); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4320 | return BinaryOperator::CreateOr(Not, Op0); |
| 4321 | } |
| 4322 | } |
| 4323 | } |
| 4324 | |
Sanjay Patel | e9b2c32 | 2016-05-17 00:57:57 +0000 | [diff] [blame] | 4325 | if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I)) |
Sanjay Patel | d5b0e54 | 2016-04-29 16:22:25 +0000 | [diff] [blame] | 4326 | return NewICmp; |
| 4327 | |
Sanjay Patel | 06b127a | 2016-09-15 14:37:50 +0000 | [diff] [blame] | 4328 | if (Instruction *Res = foldICmpWithConstant(I)) |
| 4329 | return Res; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4330 | |
Sanjay Patel | 3151dec | 2016-09-12 15:24:31 +0000 | [diff] [blame] | 4331 | if (Instruction *Res = foldICmpUsingKnownBits(I)) |
| 4332 | return Res; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4333 | |
| 4334 | // Test if the ICmpInst instruction is used exclusively by a select as |
| 4335 | // part of a minimum or maximum operation. If so, refrain from doing |
| 4336 | // any other folding. This helps out other analyses which understand |
| 4337 | // non-obfuscated minimum and maximum idioms, such as ScalarEvolution |
| 4338 | // and CodeGen. And in this case, at least one of the comparison |
| 4339 | // operands has at least one user besides the compare (the select), |
| 4340 | // which would often largely negate the benefit of folding anyway. |
| 4341 | if (I.hasOneUse()) |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4342 | if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin())) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4343 | if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) || |
| 4344 | (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4345 | return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4346 | |
Sanjay Patel | febcb9c | 2017-01-27 23:26:27 +0000 | [diff] [blame] | 4347 | // FIXME: We only do this after checking for min/max to prevent infinite |
| 4348 | // looping caused by a reverse canonicalization of these patterns for min/max. |
| 4349 | // FIXME: The organization of folds is a mess. These would naturally go into |
| 4350 | // canonicalizeCmpWithConstant(), but we can't move all of the above folds |
| 4351 | // down here after the min/max restriction. |
| 4352 | ICmpInst::Predicate Pred = I.getPredicate(); |
| 4353 | const APInt *C; |
| 4354 | if (match(Op1, m_APInt(C))) { |
| 4355 | // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set |
| 4356 | if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) { |
| 4357 | Constant *Zero = Constant::getNullValue(Op0->getType()); |
| 4358 | return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero); |
| 4359 | } |
| 4360 | |
| 4361 | // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear |
| 4362 | if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) { |
| 4363 | Constant *AllOnes = Constant::getAllOnesValue(Op0->getType()); |
| 4364 | return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes); |
| 4365 | } |
| 4366 | } |
| 4367 | |
Sanjay Patel | f58f68c | 2016-09-10 15:03:44 +0000 | [diff] [blame] | 4368 | if (Instruction *Res = foldICmpInstWithConstant(I)) |
Sanjay Patel | 1271bf9 | 2016-07-23 13:06:49 +0000 | [diff] [blame] | 4369 | return Res; |
| 4370 | |
Sanjay Patel | 10494b2 | 2016-09-16 16:10:22 +0000 | [diff] [blame] | 4371 | if (Instruction *Res = foldICmpInstWithConstantNotInt(I)) |
| 4372 | return Res; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4373 | |
| 4374 | // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now. |
| 4375 | if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0)) |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 4376 | if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I)) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4377 | return NI; |
| 4378 | if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1)) |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 4379 | if (Instruction *NI = foldGEPICmp(GEP, Op0, |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4380 | ICmpInst::getSwappedPredicate(I.getPredicate()), I)) |
| 4381 | return NI; |
| 4382 | |
Hans Wennborg | f1f3651 | 2015-10-07 00:20:07 +0000 | [diff] [blame] | 4383 | // Try to optimize equality comparisons against alloca-based pointers. |
| 4384 | if (Op0->getType()->isPointerTy() && I.isEquality()) { |
| 4385 | assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?"); |
| 4386 | if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL))) |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 4387 | if (Instruction *New = foldAllocaCmp(I, Alloca, Op1)) |
Hans Wennborg | f1f3651 | 2015-10-07 00:20:07 +0000 | [diff] [blame] | 4388 | return New; |
| 4389 | if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL))) |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 4390 | if (Instruction *New = foldAllocaCmp(I, Alloca, Op0)) |
Hans Wennborg | f1f3651 | 2015-10-07 00:20:07 +0000 | [diff] [blame] | 4391 | return New; |
| 4392 | } |
| 4393 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4394 | // Test to see if the operands of the icmp are casted versions of other |
| 4395 | // values. If the ptr->ptr cast can be stripped off both arguments, we do so |
| 4396 | // now. |
| 4397 | if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) { |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4398 | if (Op0->getType()->isPointerTy() && |
| 4399 | (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4400 | // We keep moving the cast from the left operand over to the right |
| 4401 | // operand, where it can often be eliminated completely. |
| 4402 | Op0 = CI->getOperand(0); |
| 4403 | |
| 4404 | // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast |
| 4405 | // so eliminate it as well. |
| 4406 | if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1)) |
| 4407 | Op1 = CI2->getOperand(0); |
| 4408 | |
| 4409 | // If Op1 is a constant, we can fold the cast into the constant. |
| 4410 | if (Op0->getType() != Op1->getType()) { |
| 4411 | if (Constant *Op1C = dyn_cast<Constant>(Op1)) { |
| 4412 | Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType()); |
| 4413 | } else { |
| 4414 | // Otherwise, cast the RHS right before the icmp |
| 4415 | Op1 = Builder->CreateBitCast(Op1, Op0->getType()); |
| 4416 | } |
| 4417 | } |
| 4418 | return new ICmpInst(I.getPredicate(), Op0, Op1); |
| 4419 | } |
| 4420 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4421 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4422 | if (isa<CastInst>(Op0)) { |
| 4423 | // Handle the special case of: icmp (cast bool to X), <cst> |
| 4424 | // This comes up when you have code like |
| 4425 | // int X = A < B; |
| 4426 | // if (X) ... |
| 4427 | // For generality, we handle any zero-extension of any operand comparison |
| 4428 | // with a constant or another cast from the same type. |
| 4429 | if (isa<Constant>(Op1) || isa<CastInst>(Op1)) |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 4430 | if (Instruction *R = foldICmpWithCastAndCast(I)) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4431 | return R; |
| 4432 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4433 | |
Sanjay Patel | 10494b2 | 2016-09-16 16:10:22 +0000 | [diff] [blame] | 4434 | if (Instruction *Res = foldICmpBinOp(I)) |
| 4435 | return Res; |
Duncan Sands | e522001 | 2011-02-17 07:46:37 +0000 | [diff] [blame] | 4436 | |
Sanjay Patel | dd46b52 | 2016-12-19 17:32:37 +0000 | [diff] [blame] | 4437 | if (Instruction *Res = foldICmpWithMinMax(I)) |
Sanjay Patel | d640641 | 2016-12-15 19:13:37 +0000 | [diff] [blame] | 4438 | return Res; |
| 4439 | |
Sanjay Patel | 10494b2 | 2016-09-16 16:10:22 +0000 | [diff] [blame] | 4440 | { |
| 4441 | Value *A, *B; |
David Majnemer | 1a08acc | 2013-04-12 17:25:07 +0000 | [diff] [blame] | 4442 | // Transform (A & ~B) == 0 --> (A & B) != 0 |
| 4443 | // and (A & ~B) != 0 --> (A & B) == 0 |
| 4444 | // if A is a power of 2. |
| 4445 | if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) && |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 4446 | match(Op1, m_Zero()) && |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 4447 | isKnownToBeAPowerOfTwo(A, DL, false, 0, &AC, &I, &DT) && I.isEquality()) |
David Majnemer | 1a08acc | 2013-04-12 17:25:07 +0000 | [diff] [blame] | 4448 | return new ICmpInst(I.getInversePredicate(), |
| 4449 | Builder->CreateAnd(A, B), |
| 4450 | Op1); |
| 4451 | |
Chris Lattner | f3c4eef | 2011-01-15 05:41:33 +0000 | [diff] [blame] | 4452 | // ~x < ~y --> y < x |
| 4453 | // ~x < cst --> ~cst < x |
| 4454 | if (match(Op0, m_Not(m_Value(A)))) { |
| 4455 | if (match(Op1, m_Not(m_Value(B)))) |
| 4456 | return new ICmpInst(I.getPredicate(), B, A); |
Chris Lattner | 497459d | 2011-01-15 05:42:47 +0000 | [diff] [blame] | 4457 | if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) |
Chris Lattner | f3c4eef | 2011-01-15 05:41:33 +0000 | [diff] [blame] | 4458 | return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A); |
| 4459 | } |
Chris Lattner | 5e0c0c7 | 2010-12-19 19:37:52 +0000 | [diff] [blame] | 4460 | |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 4461 | Instruction *AddI = nullptr; |
| 4462 | if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B), |
| 4463 | m_Instruction(AddI))) && |
| 4464 | isa<IntegerType>(A->getType())) { |
| 4465 | Value *Result; |
| 4466 | Constant *Overflow; |
| 4467 | if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result, |
| 4468 | Overflow)) { |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4469 | replaceInstUsesWith(*AddI, Result); |
| 4470 | return replaceInstUsesWith(I, Overflow); |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 4471 | } |
| 4472 | } |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 4473 | |
| 4474 | // (zext a) * (zext b) --> llvm.umul.with.overflow. |
| 4475 | if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) { |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 4476 | if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this)) |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 4477 | return R; |
| 4478 | } |
| 4479 | if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) { |
Sanjay Patel | d93c4c0 | 2016-09-15 18:22:25 +0000 | [diff] [blame] | 4480 | if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this)) |
Serge Pavlov | 4bb54d5 | 2014-04-13 18:23:41 +0000 | [diff] [blame] | 4481 | return R; |
| 4482 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4483 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4484 | |
Sanjay Patel | 10494b2 | 2016-09-16 16:10:22 +0000 | [diff] [blame] | 4485 | if (Instruction *Res = foldICmpEquality(I)) |
| 4486 | return Res; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4487 | |
David Majnemer | c1eca5a | 2014-11-06 23:23:30 +0000 | [diff] [blame] | 4488 | // The 'cmpxchg' instruction returns an aggregate containing the old value and |
| 4489 | // an i1 which indicates whether or not we successfully did the swap. |
| 4490 | // |
| 4491 | // Replace comparisons between the old value and the expected value with the |
| 4492 | // indicator that 'cmpxchg' returns. |
| 4493 | // |
| 4494 | // N.B. This transform is only valid when the 'cmpxchg' is not permitted to |
| 4495 | // spuriously fail. In those cases, the old value may equal the expected |
| 4496 | // value but it is possible for the swap to not occur. |
| 4497 | if (I.getPredicate() == ICmpInst::ICMP_EQ) |
| 4498 | if (auto *EVI = dyn_cast<ExtractValueInst>(Op0)) |
| 4499 | if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand())) |
| 4500 | if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 && |
| 4501 | !ACXI->isWeak()) |
| 4502 | return ExtractValueInst::Create(ACXI, 1); |
| 4503 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4504 | { |
| 4505 | Value *X; ConstantInt *Cst; |
| 4506 | // icmp X+Cst, X |
| 4507 | if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X) |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 4508 | return foldICmpAddOpConst(I, X, Cst, I.getPredicate()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4509 | |
| 4510 | // icmp X, X+Cst |
| 4511 | if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X) |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 4512 | return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4513 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4514 | return Changed ? &I : nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4515 | } |
| 4516 | |
Sanjay Patel | 5f0217f | 2016-06-05 16:46:18 +0000 | [diff] [blame] | 4517 | /// Fold fcmp ([us]itofp x, cst) if possible. |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 4518 | Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI, |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4519 | Constant *RHSC) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4520 | if (!isa<ConstantFP>(RHSC)) return nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4521 | const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF(); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4522 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4523 | // Get the width of the mantissa. We don't want to hack on conversions that |
| 4524 | // might lose information from the integer, e.g. "i64 -> float" |
| 4525 | int MantissaWidth = LHSI->getType()->getFPMantissaWidth(); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4526 | if (MantissaWidth == -1) return nullptr; // Unknown. |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4527 | |
Matt Arsenault | 55e7312 | 2015-01-06 15:50:59 +0000 | [diff] [blame] | 4528 | IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType()); |
| 4529 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4530 | bool LHSUnsigned = isa<UIToFPInst>(LHSI); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4531 | |
Matt Arsenault | 55e7312 | 2015-01-06 15:50:59 +0000 | [diff] [blame] | 4532 | if (I.isEquality()) { |
| 4533 | FCmpInst::Predicate P = I.getPredicate(); |
| 4534 | bool IsExact = false; |
| 4535 | APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned); |
| 4536 | RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact); |
| 4537 | |
| 4538 | // If the floating point constant isn't an integer value, we know if we will |
| 4539 | // ever compare equal / not equal to it. |
| 4540 | if (!IsExact) { |
| 4541 | // TODO: Can never be -0.0 and other non-representable values |
| 4542 | APFloat RHSRoundInt(RHS); |
| 4543 | RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven); |
| 4544 | if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) { |
| 4545 | if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4546 | return replaceInstUsesWith(I, Builder->getFalse()); |
Matt Arsenault | 55e7312 | 2015-01-06 15:50:59 +0000 | [diff] [blame] | 4547 | |
| 4548 | assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE); |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4549 | return replaceInstUsesWith(I, Builder->getTrue()); |
Matt Arsenault | 55e7312 | 2015-01-06 15:50:59 +0000 | [diff] [blame] | 4550 | } |
| 4551 | } |
| 4552 | |
| 4553 | // TODO: If the constant is exactly representable, is it always OK to do |
| 4554 | // equality compares as integer? |
| 4555 | } |
| 4556 | |
Arch D. Robison | 8ed0854 | 2015-09-15 17:51:59 +0000 | [diff] [blame] | 4557 | // Check to see that the input is converted from an integer type that is small |
| 4558 | // enough that preserves all bits. TODO: check here for "known" sign bits. |
| 4559 | // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e. |
| 4560 | unsigned InputSize = IntTy->getScalarSizeInBits(); |
Matt Arsenault | 55e7312 | 2015-01-06 15:50:59 +0000 | [diff] [blame] | 4561 | |
Justin Bogner | c7e4fbe | 2016-08-05 01:09:48 +0000 | [diff] [blame] | 4562 | // Following test does NOT adjust InputSize downwards for signed inputs, |
| 4563 | // because the most negative value still requires all the mantissa bits |
Arch D. Robison | 8ed0854 | 2015-09-15 17:51:59 +0000 | [diff] [blame] | 4564 | // to distinguish it from one less than that value. |
| 4565 | if ((int)InputSize > MantissaWidth) { |
| 4566 | // Conversion would lose accuracy. Check if loss can impact comparison. |
| 4567 | int Exp = ilogb(RHS); |
| 4568 | if (Exp == APFloat::IEK_Inf) { |
| 4569 | int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics())); |
Justin Bogner | c7e4fbe | 2016-08-05 01:09:48 +0000 | [diff] [blame] | 4570 | if (MaxExponent < (int)InputSize - !LHSUnsigned) |
Arch D. Robison | 8ed0854 | 2015-09-15 17:51:59 +0000 | [diff] [blame] | 4571 | // Conversion could create infinity. |
| 4572 | return nullptr; |
| 4573 | } else { |
Justin Bogner | c7e4fbe | 2016-08-05 01:09:48 +0000 | [diff] [blame] | 4574 | // Note that if RHS is zero or NaN, then Exp is negative |
Arch D. Robison | 8ed0854 | 2015-09-15 17:51:59 +0000 | [diff] [blame] | 4575 | // and first condition is trivially false. |
Justin Bogner | c7e4fbe | 2016-08-05 01:09:48 +0000 | [diff] [blame] | 4576 | if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned) |
Arch D. Robison | 8ed0854 | 2015-09-15 17:51:59 +0000 | [diff] [blame] | 4577 | // Conversion could affect comparison. |
| 4578 | return nullptr; |
| 4579 | } |
| 4580 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4581 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4582 | // Otherwise, we can potentially simplify the comparison. We know that it |
| 4583 | // will always come through as an integer value and we know the constant is |
| 4584 | // not a NAN (it would have been previously simplified). |
| 4585 | assert(!RHS.isNaN() && "NaN comparison not already folded!"); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4586 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4587 | ICmpInst::Predicate Pred; |
| 4588 | switch (I.getPredicate()) { |
| 4589 | default: llvm_unreachable("Unexpected predicate!"); |
| 4590 | case FCmpInst::FCMP_UEQ: |
| 4591 | case FCmpInst::FCMP_OEQ: |
| 4592 | Pred = ICmpInst::ICMP_EQ; |
| 4593 | break; |
| 4594 | case FCmpInst::FCMP_UGT: |
| 4595 | case FCmpInst::FCMP_OGT: |
| 4596 | Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT; |
| 4597 | break; |
| 4598 | case FCmpInst::FCMP_UGE: |
| 4599 | case FCmpInst::FCMP_OGE: |
| 4600 | Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE; |
| 4601 | break; |
| 4602 | case FCmpInst::FCMP_ULT: |
| 4603 | case FCmpInst::FCMP_OLT: |
| 4604 | Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT; |
| 4605 | break; |
| 4606 | case FCmpInst::FCMP_ULE: |
| 4607 | case FCmpInst::FCMP_OLE: |
| 4608 | Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE; |
| 4609 | break; |
| 4610 | case FCmpInst::FCMP_UNE: |
| 4611 | case FCmpInst::FCMP_ONE: |
| 4612 | Pred = ICmpInst::ICMP_NE; |
| 4613 | break; |
| 4614 | case FCmpInst::FCMP_ORD: |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4615 | return replaceInstUsesWith(I, Builder->getTrue()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4616 | case FCmpInst::FCMP_UNO: |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4617 | return replaceInstUsesWith(I, Builder->getFalse()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4618 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4619 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4620 | // Now we know that the APFloat is a normal number, zero or inf. |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4621 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4622 | // See if the FP constant is too large for the integer. For example, |
| 4623 | // comparing an i8 to 300.0. |
| 4624 | unsigned IntWidth = IntTy->getScalarSizeInBits(); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4625 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4626 | if (!LHSUnsigned) { |
| 4627 | // If the RHS value is > SignedMax, fold the comparison. This handles +INF |
| 4628 | // and large values. |
Michael Gottesman | 79b0967 | 2013-06-27 21:58:19 +0000 | [diff] [blame] | 4629 | APFloat SMax(RHS.getSemantics()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4630 | SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true, |
| 4631 | APFloat::rmNearestTiesToEven); |
| 4632 | if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0 |
| 4633 | if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT || |
| 4634 | Pred == ICmpInst::ICMP_SLE) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4635 | return replaceInstUsesWith(I, Builder->getTrue()); |
| 4636 | return replaceInstUsesWith(I, Builder->getFalse()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4637 | } |
| 4638 | } else { |
| 4639 | // If the RHS value is > UnsignedMax, fold the comparison. This handles |
| 4640 | // +INF and large values. |
Michael Gottesman | 79b0967 | 2013-06-27 21:58:19 +0000 | [diff] [blame] | 4641 | APFloat UMax(RHS.getSemantics()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4642 | UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false, |
| 4643 | APFloat::rmNearestTiesToEven); |
| 4644 | if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0 |
| 4645 | if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT || |
| 4646 | Pred == ICmpInst::ICMP_ULE) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4647 | return replaceInstUsesWith(I, Builder->getTrue()); |
| 4648 | return replaceInstUsesWith(I, Builder->getFalse()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4649 | } |
| 4650 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4651 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4652 | if (!LHSUnsigned) { |
| 4653 | // See if the RHS value is < SignedMin. |
Michael Gottesman | 79b0967 | 2013-06-27 21:58:19 +0000 | [diff] [blame] | 4654 | APFloat SMin(RHS.getSemantics()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4655 | SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true, |
| 4656 | APFloat::rmNearestTiesToEven); |
| 4657 | if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0 |
| 4658 | if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT || |
| 4659 | Pred == ICmpInst::ICMP_SGE) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4660 | return replaceInstUsesWith(I, Builder->getTrue()); |
| 4661 | return replaceInstUsesWith(I, Builder->getFalse()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4662 | } |
Devang Patel | 698452b | 2012-02-13 23:05:18 +0000 | [diff] [blame] | 4663 | } else { |
| 4664 | // See if the RHS value is < UnsignedMin. |
Michael Gottesman | 79b0967 | 2013-06-27 21:58:19 +0000 | [diff] [blame] | 4665 | APFloat SMin(RHS.getSemantics()); |
Devang Patel | 698452b | 2012-02-13 23:05:18 +0000 | [diff] [blame] | 4666 | SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true, |
| 4667 | APFloat::rmNearestTiesToEven); |
| 4668 | if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0 |
| 4669 | if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT || |
| 4670 | Pred == ICmpInst::ICMP_UGE) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4671 | return replaceInstUsesWith(I, Builder->getTrue()); |
| 4672 | return replaceInstUsesWith(I, Builder->getFalse()); |
Devang Patel | 698452b | 2012-02-13 23:05:18 +0000 | [diff] [blame] | 4673 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4674 | } |
| 4675 | |
| 4676 | // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or |
| 4677 | // [0, UMAX], but it may still be fractional. See if it is fractional by |
| 4678 | // casting the FP value to the integer value and back, checking for equality. |
| 4679 | // Don't do this for zero, because -0.0 is not fractional. |
| 4680 | Constant *RHSInt = LHSUnsigned |
| 4681 | ? ConstantExpr::getFPToUI(RHSC, IntTy) |
| 4682 | : ConstantExpr::getFPToSI(RHSC, IntTy); |
| 4683 | if (!RHS.isZero()) { |
| 4684 | bool Equal = LHSUnsigned |
| 4685 | ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC |
| 4686 | : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC; |
| 4687 | if (!Equal) { |
| 4688 | // If we had a comparison against a fractional value, we have to adjust |
| 4689 | // the compare predicate and sometimes the value. RHSC is rounded towards |
| 4690 | // zero at this point. |
| 4691 | switch (Pred) { |
| 4692 | default: llvm_unreachable("Unexpected integer comparison!"); |
| 4693 | case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4694 | return replaceInstUsesWith(I, Builder->getTrue()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4695 | case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4696 | return replaceInstUsesWith(I, Builder->getFalse()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4697 | case ICmpInst::ICMP_ULE: |
| 4698 | // (float)int <= 4.4 --> int <= 4 |
| 4699 | // (float)int <= -4.4 --> false |
| 4700 | if (RHS.isNegative()) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4701 | return replaceInstUsesWith(I, Builder->getFalse()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4702 | break; |
| 4703 | case ICmpInst::ICMP_SLE: |
| 4704 | // (float)int <= 4.4 --> int <= 4 |
| 4705 | // (float)int <= -4.4 --> int < -4 |
| 4706 | if (RHS.isNegative()) |
| 4707 | Pred = ICmpInst::ICMP_SLT; |
| 4708 | break; |
| 4709 | case ICmpInst::ICMP_ULT: |
| 4710 | // (float)int < -4.4 --> false |
| 4711 | // (float)int < 4.4 --> int <= 4 |
| 4712 | if (RHS.isNegative()) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4713 | return replaceInstUsesWith(I, Builder->getFalse()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4714 | Pred = ICmpInst::ICMP_ULE; |
| 4715 | break; |
| 4716 | case ICmpInst::ICMP_SLT: |
| 4717 | // (float)int < -4.4 --> int < -4 |
| 4718 | // (float)int < 4.4 --> int <= 4 |
| 4719 | if (!RHS.isNegative()) |
| 4720 | Pred = ICmpInst::ICMP_SLE; |
| 4721 | break; |
| 4722 | case ICmpInst::ICMP_UGT: |
| 4723 | // (float)int > 4.4 --> int > 4 |
| 4724 | // (float)int > -4.4 --> true |
| 4725 | if (RHS.isNegative()) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4726 | return replaceInstUsesWith(I, Builder->getTrue()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4727 | break; |
| 4728 | case ICmpInst::ICMP_SGT: |
| 4729 | // (float)int > 4.4 --> int > 4 |
| 4730 | // (float)int > -4.4 --> int >= -4 |
| 4731 | if (RHS.isNegative()) |
| 4732 | Pred = ICmpInst::ICMP_SGE; |
| 4733 | break; |
| 4734 | case ICmpInst::ICMP_UGE: |
| 4735 | // (float)int >= -4.4 --> true |
| 4736 | // (float)int >= 4.4 --> int > 4 |
Bob Wilson | 61f3ad5 | 2012-08-07 22:35:16 +0000 | [diff] [blame] | 4737 | if (RHS.isNegative()) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4738 | return replaceInstUsesWith(I, Builder->getTrue()); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4739 | Pred = ICmpInst::ICMP_UGT; |
| 4740 | break; |
| 4741 | case ICmpInst::ICMP_SGE: |
| 4742 | // (float)int >= -4.4 --> int >= -4 |
| 4743 | // (float)int >= 4.4 --> int > 4 |
| 4744 | if (!RHS.isNegative()) |
| 4745 | Pred = ICmpInst::ICMP_SGT; |
| 4746 | break; |
| 4747 | } |
| 4748 | } |
| 4749 | } |
| 4750 | |
| 4751 | // Lower this FP comparison into an appropriate integer version of the |
| 4752 | // comparison. |
| 4753 | return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); |
| 4754 | } |
| 4755 | |
| 4756 | Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) { |
| 4757 | bool Changed = false; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4758 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4759 | /// Orders the operands of the compare so that they are listed from most |
| 4760 | /// complex to least complex. This puts constants before unary operators, |
| 4761 | /// before binary operators. |
| 4762 | if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) { |
| 4763 | I.swapOperands(); |
| 4764 | Changed = true; |
| 4765 | } |
| 4766 | |
| 4767 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4768 | |
Benjamin Kramer | f4ebfa3 | 2015-07-10 14:02:02 +0000 | [diff] [blame] | 4769 | if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 4770 | I.getFastMathFlags(), DL, &TLI, &DT, &AC, &I)) |
Sanjay Patel | 4b19880 | 2016-02-01 22:23:39 +0000 | [diff] [blame] | 4771 | return replaceInstUsesWith(I, V); |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4772 | |
| 4773 | // Simplify 'fcmp pred X, X' |
| 4774 | if (Op0 == Op1) { |
| 4775 | switch (I.getPredicate()) { |
| 4776 | default: llvm_unreachable("Unknown predicate!"); |
| 4777 | case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y) |
| 4778 | case FCmpInst::FCMP_ULT: // True if unordered or less than |
| 4779 | case FCmpInst::FCMP_UGT: // True if unordered or greater than |
| 4780 | case FCmpInst::FCMP_UNE: // True if unordered or not equal |
| 4781 | // Canonicalize these to be 'fcmp uno %X, 0.0'. |
| 4782 | I.setPredicate(FCmpInst::FCMP_UNO); |
| 4783 | I.setOperand(1, Constant::getNullValue(Op0->getType())); |
| 4784 | return &I; |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4785 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4786 | case FCmpInst::FCMP_ORD: // True if ordered (no nans) |
| 4787 | case FCmpInst::FCMP_OEQ: // True if ordered and equal |
| 4788 | case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal |
| 4789 | case FCmpInst::FCMP_OLE: // True if ordered and less than or equal |
| 4790 | // Canonicalize these to be 'fcmp ord %X, 0.0'. |
| 4791 | I.setPredicate(FCmpInst::FCMP_ORD); |
| 4792 | I.setOperand(1, Constant::getNullValue(Op0->getType())); |
| 4793 | return &I; |
| 4794 | } |
| 4795 | } |
Jim Grosbach | 129c52a | 2011-09-30 18:09:53 +0000 | [diff] [blame] | 4796 | |
James Molloy | 2b21a7c | 2015-05-20 18:41:25 +0000 | [diff] [blame] | 4797 | // Test if the FCmpInst instruction is used exclusively by a select as |
| 4798 | // part of a minimum or maximum operation. If so, refrain from doing |
| 4799 | // any other folding. This helps out other analyses which understand |
| 4800 | // non-obfuscated minimum and maximum idioms, such as ScalarEvolution |
| 4801 | // and CodeGen. And in this case, at least one of the comparison |
| 4802 | // operands has at least one user besides the compare (the select), |
| 4803 | // which would often largely negate the benefit of folding anyway. |
| 4804 | if (I.hasOneUse()) |
| 4805 | if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin())) |
| 4806 | if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) || |
| 4807 | (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1)) |
| 4808 | return nullptr; |
| 4809 | |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4810 | // Handle fcmp with constant RHS |
| 4811 | if (Constant *RHSC = dyn_cast<Constant>(Op1)) { |
| 4812 | if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) |
| 4813 | switch (LHSI->getOpcode()) { |
Benjamin Kramer | cbb18e9 | 2011-03-31 10:12:07 +0000 | [diff] [blame] | 4814 | case Instruction::FPExt: { |
| 4815 | // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless |
| 4816 | FPExtInst *LHSExt = cast<FPExtInst>(LHSI); |
| 4817 | ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC); |
| 4818 | if (!RHSF) |
| 4819 | break; |
| 4820 | |
| 4821 | const fltSemantics *Sem; |
| 4822 | // FIXME: This shouldn't be here. |
Dan Gohman | 518cda4 | 2011-12-17 00:04:22 +0000 | [diff] [blame] | 4823 | if (LHSExt->getSrcTy()->isHalfTy()) |
Stephan Bergmann | 17c7f70 | 2016-12-14 11:57:17 +0000 | [diff] [blame] | 4824 | Sem = &APFloat::IEEEhalf(); |
Dan Gohman | 518cda4 | 2011-12-17 00:04:22 +0000 | [diff] [blame] | 4825 | else if (LHSExt->getSrcTy()->isFloatTy()) |
Stephan Bergmann | 17c7f70 | 2016-12-14 11:57:17 +0000 | [diff] [blame] | 4826 | Sem = &APFloat::IEEEsingle(); |
Benjamin Kramer | cbb18e9 | 2011-03-31 10:12:07 +0000 | [diff] [blame] | 4827 | else if (LHSExt->getSrcTy()->isDoubleTy()) |
Stephan Bergmann | 17c7f70 | 2016-12-14 11:57:17 +0000 | [diff] [blame] | 4828 | Sem = &APFloat::IEEEdouble(); |
Benjamin Kramer | cbb18e9 | 2011-03-31 10:12:07 +0000 | [diff] [blame] | 4829 | else if (LHSExt->getSrcTy()->isFP128Ty()) |
Stephan Bergmann | 17c7f70 | 2016-12-14 11:57:17 +0000 | [diff] [blame] | 4830 | Sem = &APFloat::IEEEquad(); |
Benjamin Kramer | cbb18e9 | 2011-03-31 10:12:07 +0000 | [diff] [blame] | 4831 | else if (LHSExt->getSrcTy()->isX86_FP80Ty()) |
Stephan Bergmann | 17c7f70 | 2016-12-14 11:57:17 +0000 | [diff] [blame] | 4832 | Sem = &APFloat::x87DoubleExtended(); |
Ulrich Weigand | 6a9bb51 | 2012-10-30 12:33:18 +0000 | [diff] [blame] | 4833 | else if (LHSExt->getSrcTy()->isPPC_FP128Ty()) |
Stephan Bergmann | 17c7f70 | 2016-12-14 11:57:17 +0000 | [diff] [blame] | 4834 | Sem = &APFloat::PPCDoubleDouble(); |
Benjamin Kramer | cbb18e9 | 2011-03-31 10:12:07 +0000 | [diff] [blame] | 4835 | else |
| 4836 | break; |
| 4837 | |
| 4838 | bool Lossy; |
| 4839 | APFloat F = RHSF->getValueAPF(); |
| 4840 | F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy); |
| 4841 | |
Jim Grosbach | 24ff834 | 2011-09-30 18:45:50 +0000 | [diff] [blame] | 4842 | // Avoid lossy conversions and denormals. Zero is a special case |
| 4843 | // that's OK to convert. |
Jim Grosbach | 011dafb | 2011-09-30 19:58:46 +0000 | [diff] [blame] | 4844 | APFloat Fabs = F; |
| 4845 | Fabs.clearSign(); |
Benjamin Kramer | cbb18e9 | 2011-03-31 10:12:07 +0000 | [diff] [blame] | 4846 | if (!Lossy && |
Jim Grosbach | 011dafb | 2011-09-30 19:58:46 +0000 | [diff] [blame] | 4847 | ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) != |
| 4848 | APFloat::cmpLessThan) || Fabs.isZero())) |
Jim Grosbach | 24ff834 | 2011-09-30 18:45:50 +0000 | [diff] [blame] | 4849 | |
Benjamin Kramer | cbb18e9 | 2011-03-31 10:12:07 +0000 | [diff] [blame] | 4850 | return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0), |
| 4851 | ConstantFP::get(RHSC->getContext(), F)); |
| 4852 | break; |
| 4853 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4854 | case Instruction::PHI: |
| 4855 | // Only fold fcmp into the PHI if the phi and fcmp are in the same |
| 4856 | // block. If in the same block, we're encouraging jump threading. If |
| 4857 | // not, we are just pessimizing the code by making an i1 phi. |
| 4858 | if (LHSI->getParent() == I.getParent()) |
Chris Lattner | ea7131a | 2011-01-16 05:14:26 +0000 | [diff] [blame] | 4859 | if (Instruction *NV = FoldOpIntoPhi(I)) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4860 | return NV; |
| 4861 | break; |
| 4862 | case Instruction::SIToFP: |
| 4863 | case Instruction::UIToFP: |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 4864 | if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC)) |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4865 | return NV; |
| 4866 | break; |
Benjamin Kramer | a8c5d08 | 2011-03-31 10:12:15 +0000 | [diff] [blame] | 4867 | case Instruction::FSub: { |
| 4868 | // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C |
| 4869 | Value *Op; |
| 4870 | if (match(LHSI, m_FNeg(m_Value(Op)))) |
| 4871 | return new FCmpInst(I.getSwappedPredicate(), Op, |
| 4872 | ConstantExpr::getFNeg(RHSC)); |
| 4873 | break; |
| 4874 | } |
Dan Gohman | 9473202 | 2010-02-24 06:46:09 +0000 | [diff] [blame] | 4875 | case Instruction::Load: |
| 4876 | if (GetElementPtrInst *GEP = |
| 4877 | dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { |
| 4878 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) |
| 4879 | if (GV->isConstant() && GV->hasDefinitiveInitializer() && |
| 4880 | !cast<LoadInst>(LHSI)->isVolatile()) |
Sanjay Patel | 4339506 | 2016-07-21 18:07:40 +0000 | [diff] [blame] | 4881 | if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I)) |
Dan Gohman | 9473202 | 2010-02-24 06:46:09 +0000 | [diff] [blame] | 4882 | return Res; |
| 4883 | } |
| 4884 | break; |
Benjamin Kramer | 8c2a733 | 2012-08-18 20:06:47 +0000 | [diff] [blame] | 4885 | case Instruction::Call: { |
Matt Arsenault | b935d9d | 2015-01-08 20:09:34 +0000 | [diff] [blame] | 4886 | if (!RHSC->isNullValue()) |
| 4887 | break; |
| 4888 | |
Benjamin Kramer | 8c2a733 | 2012-08-18 20:06:47 +0000 | [diff] [blame] | 4889 | CallInst *CI = cast<CallInst>(LHSI); |
Justin Bogner | 9979840 | 2016-08-05 01:06:44 +0000 | [diff] [blame] | 4890 | Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI); |
David Majnemer | 2e02ba7 | 2016-04-15 17:21:03 +0000 | [diff] [blame] | 4891 | if (IID != Intrinsic::fabs) |
Matt Arsenault | b935d9d | 2015-01-08 20:09:34 +0000 | [diff] [blame] | 4892 | break; |
| 4893 | |
Benjamin Kramer | 8c2a733 | 2012-08-18 20:06:47 +0000 | [diff] [blame] | 4894 | // Various optimization for fabs compared with zero. |
David Majnemer | 2e02ba7 | 2016-04-15 17:21:03 +0000 | [diff] [blame] | 4895 | switch (I.getPredicate()) { |
| 4896 | default: |
| 4897 | break; |
| 4898 | // fabs(x) < 0 --> false |
| 4899 | case FCmpInst::FCMP_OLT: |
| 4900 | llvm_unreachable("handled by SimplifyFCmpInst"); |
| 4901 | // fabs(x) > 0 --> x != 0 |
| 4902 | case FCmpInst::FCMP_OGT: |
| 4903 | return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC); |
| 4904 | // fabs(x) <= 0 --> x == 0 |
| 4905 | case FCmpInst::FCMP_OLE: |
| 4906 | return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC); |
| 4907 | // fabs(x) >= 0 --> !isnan(x) |
| 4908 | case FCmpInst::FCMP_OGE: |
| 4909 | return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC); |
| 4910 | // fabs(x) == 0 --> x == 0 |
| 4911 | // fabs(x) != 0 --> x != 0 |
| 4912 | case FCmpInst::FCMP_OEQ: |
| 4913 | case FCmpInst::FCMP_UEQ: |
| 4914 | case FCmpInst::FCMP_ONE: |
| 4915 | case FCmpInst::FCMP_UNE: |
| 4916 | return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC); |
Benjamin Kramer | 8c2a733 | 2012-08-18 20:06:47 +0000 | [diff] [blame] | 4917 | } |
| 4918 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4919 | } |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4920 | } |
| 4921 | |
Benjamin Kramer | be209ab | 2011-03-31 10:46:03 +0000 | [diff] [blame] | 4922 | // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y |
Benjamin Kramer | d159d94 | 2011-03-31 10:12:22 +0000 | [diff] [blame] | 4923 | Value *X, *Y; |
| 4924 | if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) |
Benjamin Kramer | be209ab | 2011-03-31 10:46:03 +0000 | [diff] [blame] | 4925 | return new FCmpInst(I.getSwappedPredicate(), X, Y); |
Benjamin Kramer | d159d94 | 2011-03-31 10:12:22 +0000 | [diff] [blame] | 4926 | |
Benjamin Kramer | 2ccfbc8 | 2011-03-31 10:11:58 +0000 | [diff] [blame] | 4927 | // fcmp (fpext x), (fpext y) -> fcmp x, y |
| 4928 | if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0)) |
| 4929 | if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1)) |
| 4930 | if (LHSExt->getSrcTy() == RHSExt->getSrcTy()) |
| 4931 | return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0), |
| 4932 | RHSExt->getOperand(0)); |
| 4933 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 4934 | return Changed ? &I : nullptr; |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 4935 | } |