blob: 844b9b6ae28fef571af8f7d0ac5b93a33b1ee007 [file] [log] [blame]
Chris Lattner2188e402010-01-04 07:37:31 +00001//===- 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 Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Matt Arsenault55e73122015-01-06 15:50:59 +000015#include "llvm/ADT/APSInt.h"
Silviu Barangaf29dfd32016-01-15 15:52:05 +000016#include "llvm/ADT/SetVector.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000017#include "llvm/ADT/Statistic.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000018#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000019#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/MemoryBuiltins.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000025#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000027#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000028#include "llvm/Support/Debug.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000029
Chris Lattner2188e402010-01-04 07:37:31 +000030using namespace llvm;
31using namespace PatternMatch;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "instcombine"
34
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000035// How many times is a select replaced by one of its operands?
36STATISTIC(NumSel, "Number of select opts");
37
Chris Lattner98457102011-02-10 05:23:05 +000038
Sanjay Pateld93c4c02016-09-15 18:22:25 +000039static ConstantInt *extractElement(Constant *V, Constant *Idx) {
Chris Lattner2188e402010-01-04 07:37:31 +000040 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
41}
42
Sanjay Pateld93c4c02016-09-15 18:22:25 +000043static bool hasAddOverflow(ConstantInt *Result,
Chris Lattner2188e402010-01-04 07:37:31 +000044 ConstantInt *In1, ConstantInt *In2,
45 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000046 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000047 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000048
49 if (In2->isNegative())
50 return Result->getValue().sgt(In1->getValue());
51 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000052}
53
Sanjay Patel5f0217f2016-06-05 16:46:18 +000054/// Compute Result = In1+In2, returning true if the result overflowed for this
55/// type.
Sanjay Pateld93c4c02016-09-15 18:22:25 +000056static bool addWithOverflow(Constant *&Result, Constant *In1,
Chris Lattner2188e402010-01-04 07:37:31 +000057 Constant *In2, bool IsSigned = false) {
58 Result = ConstantExpr::getAdd(In1, In2);
59
Chris Lattner229907c2011-07-18 04:54:35 +000060 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000061 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
62 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
Sanjay Pateld93c4c02016-09-15 18:22:25 +000063 if (hasAddOverflow(extractElement(Result, Idx),
64 extractElement(In1, Idx),
65 extractElement(In2, Idx),
Chris Lattner2188e402010-01-04 07:37:31 +000066 IsSigned))
67 return true;
68 }
69 return false;
70 }
71
Sanjay Pateld93c4c02016-09-15 18:22:25 +000072 return hasAddOverflow(cast<ConstantInt>(Result),
Chris Lattner2188e402010-01-04 07:37:31 +000073 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
74 IsSigned);
75}
76
Sanjay Pateld93c4c02016-09-15 18:22:25 +000077static bool hasSubOverflow(ConstantInt *Result,
Chris Lattner2188e402010-01-04 07:37:31 +000078 ConstantInt *In1, ConstantInt *In2,
79 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000080 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000081 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000082
Chris Lattnerb1a15122011-07-15 06:08:15 +000083 if (In2->isNegative())
84 return Result->getValue().slt(In1->getValue());
85
86 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000087}
88
Sanjay Patel5f0217f2016-06-05 16:46:18 +000089/// Compute Result = In1-In2, returning true if the result overflowed for this
90/// type.
Sanjay Pateld93c4c02016-09-15 18:22:25 +000091static bool subWithOverflow(Constant *&Result, Constant *In1,
Chris Lattner2188e402010-01-04 07:37:31 +000092 Constant *In2, bool IsSigned = false) {
93 Result = ConstantExpr::getSub(In1, In2);
94
Chris Lattner229907c2011-07-18 04:54:35 +000095 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000096 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
97 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
Sanjay Pateld93c4c02016-09-15 18:22:25 +000098 if (hasSubOverflow(extractElement(Result, Idx),
99 extractElement(In1, Idx),
100 extractElement(In2, Idx),
Chris Lattner2188e402010-01-04 07:37:31 +0000101 IsSigned))
102 return true;
103 }
104 return false;
105 }
106
Sanjay Pateld93c4c02016-09-15 18:22:25 +0000107 return hasSubOverflow(cast<ConstantInt>(Result),
Chris Lattner2188e402010-01-04 07:37:31 +0000108 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
109 IsSigned);
110}
111
Balaram Makam569eaec2016-05-04 21:32:14 +0000112/// Given an icmp instruction, return true if any use of this comparison is a
113/// branch on sign bit comparison.
114static 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 Patel5f0217f2016-06-05 16:46:18 +0000121/// 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 Patel79263662016-08-21 15:07:45 +0000124static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000125 bool &TrueIfSigned) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000126 switch (Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000127 case ICmpInst::ICMP_SLT: // True if LHS s< 0
128 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000129 return RHS == 0;
Chris Lattner2188e402010-01-04 07:37:31 +0000130 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
131 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000132 return RHS.isAllOnesValue();
Chris Lattner2188e402010-01-04 07:37:31 +0000133 case ICmpInst::ICMP_SGT: // True if LHS s> -1
134 TrueIfSigned = false;
Sanjay Patel79263662016-08-21 15:07:45 +0000135 return RHS.isAllOnesValue();
Chris Lattner2188e402010-01-04 07:37:31 +0000136 case ICmpInst::ICMP_UGT:
137 // True if LHS u> RHS and RHS == high-bit-mask - 1
138 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000139 return RHS.isMaxSignedValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000140 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000141 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
142 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000143 return RHS.isSignBit();
Chris Lattner2188e402010-01-04 07:37:31 +0000144 default:
145 return false;
146 }
147}
148
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000149/// 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 Patel5b112842016-08-18 14:59:14 +0000152/// TODO: Refactor with decomposeBitTestICmp()?
153static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000154 if (!ICmpInst::isSigned(Pred))
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000155 return false;
156
Sanjay Patel5b112842016-08-18 14:59:14 +0000157 if (C == 0)
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000158 return ICmpInst::isRelational(Pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000159
Sanjay Patel5b112842016-08-18 14:59:14 +0000160 if (C == 1) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000161 if (Pred == ICmpInst::ICMP_SLT) {
162 Pred = ICmpInst::ICMP_SLE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000163 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000164 }
Sanjay Patel5b112842016-08-18 14:59:14 +0000165 } else if (C.isAllOnesValue()) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000166 if (Pred == ICmpInst::ICMP_SGT) {
167 Pred = ICmpInst::ICMP_SGE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000168 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000169 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000170 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000171
172 return false;
173}
174
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000175/// 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 Pateld93c4c02016-09-15 18:22:25 +0000178static void computeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000179 const APInt &KnownOne,
180 APInt &Min, APInt &Max) {
Chris Lattner2188e402010-01-04 07:37:31 +0000181 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 Grosbach129c52a2011-09-30 18:09:53 +0000191
Chris Lattner2188e402010-01-04 07:37:31 +0000192 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000193 Min.setBit(Min.getBitWidth()-1);
194 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000195 }
196}
197
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000198/// 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 Pateld93c4c02016-09-15 18:22:25 +0000201static void computeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattner2188e402010-01-04 07:37:31 +0000202 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 Grosbach129c52a2011-09-30 18:09:53 +0000209
Chris Lattner2188e402010-01-04 07:37:31 +0000210 // 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 Patel5f0217f2016-06-05 16:46:18 +0000216/// This is called when we see this pattern:
Chris Lattner2188e402010-01-04 07:37:31 +0000217/// cmp pred (load (gep GV, ...)), cmpcst
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000218/// 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 Lattner2188e402010-01-04 07:37:31 +0000220/// 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 Patel5f0217f2016-06-05 16:46:18 +0000223/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Sanjay Patel43395062016-07-21 18:07:40 +0000224Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
225 GlobalVariable *GV,
226 CmpInst &ICI,
227 ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000228 Constant *Init = GV->getInitializer();
229 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000230 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000231
Chris Lattnerfe741762012-01-31 02:55:06 +0000232 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000233 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000234
Chris Lattner2188e402010-01-04 07:37:31 +0000235 // There are many forms of this optimization we can handle, for now, just do
236 // the simple index into a single-dimensional array.
237 //
238 // Require: GEP GV, 0, i {{, constant indices}}
239 if (GEP->getNumOperands() < 3 ||
240 !isa<ConstantInt>(GEP->getOperand(1)) ||
241 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
242 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000243 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000244
245 // Check that indices after the variable are constants and in-range for the
246 // type they index. Collect the indices. This is typically for arrays of
247 // structs.
248 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000249
Chris Lattnerfe741762012-01-31 02:55:06 +0000250 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000251 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
252 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000253 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000254
Chris Lattner2188e402010-01-04 07:37:31 +0000255 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000256 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000257
Chris Lattner229907c2011-07-18 04:54:35 +0000258 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000259 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000260 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000261 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000262 EltTy = ATy->getElementType();
263 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000264 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000265 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000266
Chris Lattner2188e402010-01-04 07:37:31 +0000267 LaterIndices.push_back(IdxVal);
268 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000269
Chris Lattner2188e402010-01-04 07:37:31 +0000270 enum { Overdefined = -3, Undefined = -2 };
271
272 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000273
Chris Lattner2188e402010-01-04 07:37:31 +0000274 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
275 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
276 // and 87 is the second (and last) index. FirstTrueElement is -2 when
277 // undefined, otherwise set to the first true element. SecondTrueElement is
278 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
279 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
280
281 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
282 // form "i != 47 & i != 87". Same state transitions as for true elements.
283 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000284
Chris Lattner2188e402010-01-04 07:37:31 +0000285 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
286 /// define a state machine that triggers for ranges of values that the index
287 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
288 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
289 /// index in the range (inclusive). We use -2 for undefined here because we
290 /// use relative comparisons and don't want 0-1 to match -1.
291 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000292
Chris Lattner2188e402010-01-04 07:37:31 +0000293 // MagicBitvector - This is a magic bitvector where we set a bit if the
294 // comparison is true for element 'i'. If there are 64 elements or less in
295 // the array, this will fully represent all the comparison results.
296 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000297
Chris Lattner2188e402010-01-04 07:37:31 +0000298 // Scan the array and see if one of our patterns matches.
299 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000300 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
301 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000302 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000303
Chris Lattner2188e402010-01-04 07:37:31 +0000304 // If this is indexing an array of structures, get the structure element.
305 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000306 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000307
Chris Lattner2188e402010-01-04 07:37:31 +0000308 // If the element is masked, handle it.
309 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000310
Chris Lattner2188e402010-01-04 07:37:31 +0000311 // Find out if the comparison would be true or false for the i'th element.
312 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Justin Bogner99798402016-08-05 01:06:44 +0000313 CompareRHS, DL, &TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000314 // If the result is undef for this element, ignore it.
315 if (isa<UndefValue>(C)) {
316 // Extend range state machines to cover this element in case there is an
317 // undef in the middle of the range.
318 if (TrueRangeEnd == (int)i-1)
319 TrueRangeEnd = i;
320 if (FalseRangeEnd == (int)i-1)
321 FalseRangeEnd = i;
322 continue;
323 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000324
Chris Lattner2188e402010-01-04 07:37:31 +0000325 // If we can't compute the result for any of the elements, we have to give
326 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000327 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000328
Chris Lattner2188e402010-01-04 07:37:31 +0000329 // Otherwise, we know if the comparison is true or false for this element,
330 // update our state machines.
331 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000332
Chris Lattner2188e402010-01-04 07:37:31 +0000333 // State machine for single/double/range index comparison.
334 if (IsTrueForElt) {
335 // Update the TrueElement state machine.
336 if (FirstTrueElement == Undefined)
337 FirstTrueElement = TrueRangeEnd = i; // First true element.
338 else {
339 // Update double-compare state machine.
340 if (SecondTrueElement == Undefined)
341 SecondTrueElement = i;
342 else
343 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000344
Chris Lattner2188e402010-01-04 07:37:31 +0000345 // Update range state machine.
346 if (TrueRangeEnd == (int)i-1)
347 TrueRangeEnd = i;
348 else
349 TrueRangeEnd = Overdefined;
350 }
351 } else {
352 // Update the FalseElement state machine.
353 if (FirstFalseElement == Undefined)
354 FirstFalseElement = FalseRangeEnd = i; // First false element.
355 else {
356 // Update double-compare state machine.
357 if (SecondFalseElement == Undefined)
358 SecondFalseElement = i;
359 else
360 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000361
Chris Lattner2188e402010-01-04 07:37:31 +0000362 // Update range state machine.
363 if (FalseRangeEnd == (int)i-1)
364 FalseRangeEnd = i;
365 else
366 FalseRangeEnd = Overdefined;
367 }
368 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000369
Chris Lattner2188e402010-01-04 07:37:31 +0000370 // If this element is in range, update our magic bitvector.
371 if (i < 64 && IsTrueForElt)
372 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000373
Chris Lattner2188e402010-01-04 07:37:31 +0000374 // If all of our states become overdefined, bail out early. Since the
375 // predicate is expensive, only check it every 8 elements. This is only
376 // really useful for really huge arrays.
377 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
378 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
379 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000380 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000381 }
382
383 // Now that we've scanned the entire array, emit our new comparison(s). We
384 // order the state machines in complexity of the generated code.
385 Value *Idx = GEP->getOperand(2);
386
Matt Arsenault5aeae182013-08-19 21:40:31 +0000387 // If the index is larger than the pointer size of the target, truncate the
388 // index down like the GEP would do implicitly. We don't have to do this for
389 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000390 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000391 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000392 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
393 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
394 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
395 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000396
Chris Lattner2188e402010-01-04 07:37:31 +0000397 // If the comparison is only true for one or two elements, emit direct
398 // comparisons.
399 if (SecondTrueElement != Overdefined) {
400 // None true -> false.
401 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000402 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000403
Chris Lattner2188e402010-01-04 07:37:31 +0000404 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000405
Chris Lattner2188e402010-01-04 07:37:31 +0000406 // True for one element -> 'i == 47'.
407 if (SecondTrueElement == Undefined)
408 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000409
Chris Lattner2188e402010-01-04 07:37:31 +0000410 // True for two elements -> 'i == 47 | i == 72'.
411 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
412 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
413 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
414 return BinaryOperator::CreateOr(C1, C2);
415 }
416
417 // If the comparison is only false for one or two elements, emit direct
418 // comparisons.
419 if (SecondFalseElement != Overdefined) {
420 // None false -> true.
421 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000422 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000423
Chris Lattner2188e402010-01-04 07:37:31 +0000424 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
425
426 // False for one element -> 'i != 47'.
427 if (SecondFalseElement == Undefined)
428 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000429
Chris Lattner2188e402010-01-04 07:37:31 +0000430 // False for two elements -> 'i != 47 & i != 72'.
431 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
432 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
433 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
434 return BinaryOperator::CreateAnd(C1, C2);
435 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000436
Chris Lattner2188e402010-01-04 07:37:31 +0000437 // If the comparison can be replaced with a range comparison for the elements
438 // where it is true, emit the range check.
439 if (TrueRangeEnd != Overdefined) {
440 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000441
Chris Lattner2188e402010-01-04 07:37:31 +0000442 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
443 if (FirstTrueElement) {
444 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
445 Idx = Builder->CreateAdd(Idx, Offs);
446 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000447
Chris Lattner2188e402010-01-04 07:37:31 +0000448 Value *End = ConstantInt::get(Idx->getType(),
449 TrueRangeEnd-FirstTrueElement+1);
450 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
451 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000452
Chris Lattner2188e402010-01-04 07:37:31 +0000453 // False range check.
454 if (FalseRangeEnd != Overdefined) {
455 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
456 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
457 if (FirstFalseElement) {
458 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
459 Idx = Builder->CreateAdd(Idx, Offs);
460 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000461
Chris Lattner2188e402010-01-04 07:37:31 +0000462 Value *End = ConstantInt::get(Idx->getType(),
463 FalseRangeEnd-FirstFalseElement);
464 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
465 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000466
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000467 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000468 // of this load, replace it with computation that does:
469 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000470 {
Craig Topperf40110f2014-04-25 05:29:35 +0000471 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000472
473 // Look for an appropriate type:
474 // - The type of Idx if the magic fits
475 // - The smallest fitting legal type if we have a DataLayout
476 // - Default to i32
477 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
478 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000479 else
480 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000481
Craig Topperf40110f2014-04-25 05:29:35 +0000482 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000483 Value *V = Builder->CreateIntCast(Idx, Ty, false);
484 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
485 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
486 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
487 }
Chris Lattner2188e402010-01-04 07:37:31 +0000488 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000489
Craig Topperf40110f2014-04-25 05:29:35 +0000490 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000491}
492
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000493/// Return a value that can be used to compare the *offset* implied by a GEP to
494/// zero. For example, if we have &A[i], we want to return 'i' for
495/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
496/// are involved. The above expression would also be legal to codegen as
497/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
498/// This latter form is less amenable to optimization though, and we are allowed
Chris Lattner2188e402010-01-04 07:37:31 +0000499/// to generate the first by knowing that pointer arithmetic doesn't overflow.
500///
501/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000502///
Sanjay Pateld93c4c02016-09-15 18:22:25 +0000503static Value *evaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000504 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000505 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000506
Chris Lattner2188e402010-01-04 07:37:31 +0000507 // Check to see if this gep only has a single variable index. If so, and if
508 // any constant indices are a multiple of its scale, then we can compute this
509 // in terms of the scale of the variable index. For example, if the GEP
510 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
511 // because the expression will cross zero at the same point.
512 unsigned i, e = GEP->getNumOperands();
513 int64_t Offset = 0;
514 for (i = 1; i != e; ++i, ++GTI) {
515 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
516 // Compute the aggregate offset of constant indices.
517 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000518
Chris Lattner2188e402010-01-04 07:37:31 +0000519 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000520 if (StructType *STy = GTI.getStructTypeOrNull()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000521 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000522 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000523 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000524 Offset += Size*CI->getSExtValue();
525 }
526 } else {
527 // Found our variable index.
528 break;
529 }
530 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000531
Chris Lattner2188e402010-01-04 07:37:31 +0000532 // If there are no variable indices, we must have a constant offset, just
533 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000534 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000535
Chris Lattner2188e402010-01-04 07:37:31 +0000536 Value *VariableIdx = GEP->getOperand(i);
537 // Determine the scale factor of the variable element. For example, this is
538 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000539 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000540
Chris Lattner2188e402010-01-04 07:37:31 +0000541 // Verify that there are no other variable indices. If so, emit the hard way.
542 for (++i, ++GTI; i != e; ++i, ++GTI) {
543 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000544 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000545
Chris Lattner2188e402010-01-04 07:37:31 +0000546 // Compute the aggregate offset of constant indices.
547 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000548
Chris Lattner2188e402010-01-04 07:37:31 +0000549 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000550 if (StructType *STy = GTI.getStructTypeOrNull()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000551 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000552 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000553 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000554 Offset += Size*CI->getSExtValue();
555 }
556 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000557
Chris Lattner2188e402010-01-04 07:37:31 +0000558 // Okay, we know we have a single variable index, which must be a
559 // pointer/array/vector index. If there is no offset, life is simple, return
560 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000561 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000562 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000563 if (Offset == 0) {
564 // Cast to intptrty in case a truncation occurs. If an extension is needed,
565 // we don't need to bother extending: the extension won't affect where the
566 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000567 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000568 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
569 }
Chris Lattner2188e402010-01-04 07:37:31 +0000570 return VariableIdx;
571 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000572
Chris Lattner2188e402010-01-04 07:37:31 +0000573 // Otherwise, there is an index. The computation we will do will be modulo
574 // the pointer size, so get it.
575 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000576
Chris Lattner2188e402010-01-04 07:37:31 +0000577 Offset &= PtrSizeMask;
578 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000579
Chris Lattner2188e402010-01-04 07:37:31 +0000580 // To do this transformation, any constant index must be a multiple of the
581 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
582 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
583 // multiple of the variable scale.
584 int64_t NewOffs = Offset / (int64_t)VariableScale;
585 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000586 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000587
Chris Lattner2188e402010-01-04 07:37:31 +0000588 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000589 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000590 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
591 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000592 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000593 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000594}
595
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000596/// Returns true if we can rewrite Start as a GEP with pointer Base
597/// and some integer offset. The nodes that need to be re-written
598/// for this transformation will be added to Explored.
599static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
600 const DataLayout &DL,
601 SetVector<Value *> &Explored) {
602 SmallVector<Value *, 16> WorkList(1, Start);
603 Explored.insert(Base);
604
605 // The following traversal gives us an order which can be used
606 // when doing the final transformation. Since in the final
607 // transformation we create the PHI replacement instructions first,
608 // we don't have to get them in any particular order.
609 //
610 // However, for other instructions we will have to traverse the
611 // operands of an instruction first, which means that we have to
612 // do a post-order traversal.
613 while (!WorkList.empty()) {
614 SetVector<PHINode *> PHIs;
615
616 while (!WorkList.empty()) {
617 if (Explored.size() >= 100)
618 return false;
619
620 Value *V = WorkList.back();
621
622 if (Explored.count(V) != 0) {
623 WorkList.pop_back();
624 continue;
625 }
626
627 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
David Majnemer8b16da82016-09-15 20:10:09 +0000628 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000629 // We've found some value that we can't explore which is different from
630 // the base. Therefore we can't do this transformation.
631 return false;
632
633 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
634 auto *CI = dyn_cast<CastInst>(V);
635 if (!CI->isNoopCast(DL))
636 return false;
637
638 if (Explored.count(CI->getOperand(0)) == 0)
639 WorkList.push_back(CI->getOperand(0));
640 }
641
642 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
643 // We're limiting the GEP to having one index. This will preserve
644 // the original pointer type. We could handle more cases in the
645 // future.
646 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
647 GEP->getType() != Start->getType())
648 return false;
649
650 if (Explored.count(GEP->getOperand(0)) == 0)
651 WorkList.push_back(GEP->getOperand(0));
652 }
653
654 if (WorkList.back() == V) {
655 WorkList.pop_back();
656 // We've finished visiting this node, mark it as such.
657 Explored.insert(V);
658 }
659
660 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000661 // We cannot transform PHIs on unsplittable basic blocks.
662 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
663 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000664 Explored.insert(PN);
665 PHIs.insert(PN);
666 }
667 }
668
669 // Explore the PHI nodes further.
670 for (auto *PN : PHIs)
671 for (Value *Op : PN->incoming_values())
672 if (Explored.count(Op) == 0)
673 WorkList.push_back(Op);
674 }
675
676 // Make sure that we can do this. Since we can't insert GEPs in a basic
677 // block before a PHI node, we can't easily do this transformation if
678 // we have PHI node users of transformed instructions.
679 for (Value *Val : Explored) {
680 for (Value *Use : Val->uses()) {
681
682 auto *PHI = dyn_cast<PHINode>(Use);
683 auto *Inst = dyn_cast<Instruction>(Val);
684
685 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
686 Explored.count(PHI) == 0)
687 continue;
688
689 if (PHI->getParent() == Inst->getParent())
690 return false;
691 }
692 }
693 return true;
694}
695
696// Sets the appropriate insert point on Builder where we can add
697// a replacement Instruction for V (if that is possible).
698static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
699 bool Before = true) {
700 if (auto *PHI = dyn_cast<PHINode>(V)) {
701 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
702 return;
703 }
704 if (auto *I = dyn_cast<Instruction>(V)) {
705 if (!Before)
706 I = &*std::next(I->getIterator());
707 Builder.SetInsertPoint(I);
708 return;
709 }
710 if (auto *A = dyn_cast<Argument>(V)) {
711 // Set the insertion point in the entry block.
712 BasicBlock &Entry = A->getParent()->getEntryBlock();
713 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
714 return;
715 }
716 // Otherwise, this is a constant and we don't need to set a new
717 // insertion point.
718 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
719}
720
721/// Returns a re-written value of Start as an indexed GEP using Base as a
722/// pointer.
723static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
724 const DataLayout &DL,
725 SetVector<Value *> &Explored) {
726 // Perform all the substitutions. This is a bit tricky because we can
727 // have cycles in our use-def chains.
728 // 1. Create the PHI nodes without any incoming values.
729 // 2. Create all the other values.
730 // 3. Add the edges for the PHI nodes.
731 // 4. Emit GEPs to get the original pointers.
732 // 5. Remove the original instructions.
733 Type *IndexType = IntegerType::get(
734 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
735
736 DenseMap<Value *, Value *> NewInsts;
737 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
738
739 // Create the new PHI nodes, without adding any incoming values.
740 for (Value *Val : Explored) {
741 if (Val == Base)
742 continue;
743 // Create empty phi nodes. This avoids cyclic dependencies when creating
744 // the remaining instructions.
745 if (auto *PHI = dyn_cast<PHINode>(Val))
746 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
747 PHI->getName() + ".idx", PHI);
748 }
749 IRBuilder<> Builder(Base->getContext());
750
751 // Create all the other instructions.
752 for (Value *Val : Explored) {
753
754 if (NewInsts.find(Val) != NewInsts.end())
755 continue;
756
757 if (auto *CI = dyn_cast<CastInst>(Val)) {
758 NewInsts[CI] = NewInsts[CI->getOperand(0)];
759 continue;
760 }
761 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
762 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
763 : GEP->getOperand(1);
764 setInsertionPoint(Builder, GEP);
765 // Indices might need to be sign extended. GEPs will magically do
766 // this, but we need to do it ourselves here.
767 if (Index->getType()->getScalarSizeInBits() !=
768 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
769 Index = Builder.CreateSExtOrTrunc(
770 Index, NewInsts[GEP->getOperand(0)]->getType(),
771 GEP->getOperand(0)->getName() + ".sext");
772 }
773
774 auto *Op = NewInsts[GEP->getOperand(0)];
775 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
776 NewInsts[GEP] = Index;
777 else
778 NewInsts[GEP] = Builder.CreateNSWAdd(
779 Op, Index, GEP->getOperand(0)->getName() + ".add");
780 continue;
781 }
782 if (isa<PHINode>(Val))
783 continue;
784
785 llvm_unreachable("Unexpected instruction type");
786 }
787
788 // Add the incoming values to the PHI nodes.
789 for (Value *Val : Explored) {
790 if (Val == Base)
791 continue;
792 // All the instructions have been created, we can now add edges to the
793 // phi nodes.
794 if (auto *PHI = dyn_cast<PHINode>(Val)) {
795 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
796 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
797 Value *NewIncoming = PHI->getIncomingValue(I);
798
799 if (NewInsts.find(NewIncoming) != NewInsts.end())
800 NewIncoming = NewInsts[NewIncoming];
801
802 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
803 }
804 }
805 }
806
807 for (Value *Val : Explored) {
808 if (Val == Base)
809 continue;
810
811 // Depending on the type, for external users we have to emit
812 // a GEP or a GEP + ptrtoint.
813 setInsertionPoint(Builder, Val, false);
814
815 // If required, create an inttoptr instruction for Base.
816 Value *NewBase = Base;
817 if (!Base->getType()->isPointerTy())
818 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
819 Start->getName() + "to.ptr");
820
821 Value *GEP = Builder.CreateInBoundsGEP(
822 Start->getType()->getPointerElementType(), NewBase,
823 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
824
825 if (!Val->getType()->isPointerTy()) {
826 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
827 Val->getName() + ".conv");
828 GEP = Cast;
829 }
830 Val->replaceAllUsesWith(GEP);
831 }
832
833 return NewInsts[Start];
834}
835
836/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
837/// the input Value as a constant indexed GEP. Returns a pair containing
838/// the GEPs Pointer and Index.
839static std::pair<Value *, Value *>
840getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
841 Type *IndexType = IntegerType::get(V->getContext(),
842 DL.getPointerTypeSizeInBits(V->getType()));
843
844 Constant *Index = ConstantInt::getNullValue(IndexType);
845 while (true) {
846 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
847 // We accept only inbouds GEPs here to exclude the possibility of
848 // overflow.
849 if (!GEP->isInBounds())
850 break;
851 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
852 GEP->getType() == V->getType()) {
853 V = GEP->getOperand(0);
854 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
855 Index = ConstantExpr::getAdd(
856 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
857 continue;
858 }
859 break;
860 }
861 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
862 if (!CI->isNoopCast(DL))
863 break;
864 V = CI->getOperand(0);
865 continue;
866 }
867 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
868 if (!CI->isNoopCast(DL))
869 break;
870 V = CI->getOperand(0);
871 continue;
872 }
873 break;
874 }
875 return {V, Index};
876}
877
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000878/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
879/// We can look through PHIs, GEPs and casts in order to determine a common base
880/// between GEPLHS and RHS.
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000881static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
882 ICmpInst::Predicate Cond,
883 const DataLayout &DL) {
884 if (!GEPLHS->hasAllConstantIndices())
885 return nullptr;
886
887 Value *PtrBase, *Index;
888 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
889
890 // The set of nodes that will take part in this transformation.
891 SetVector<Value *> Nodes;
892
893 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
894 return nullptr;
895
896 // We know we can re-write this as
897 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
898 // Since we've only looked through inbouds GEPs we know that we
899 // can't have overflow on either side. We can therefore re-write
900 // this as:
901 // OFFSET1 cmp OFFSET2
902 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
903
904 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
905 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
906 // offset. Since Index is the offset of LHS to the base pointer, we will now
907 // compare the offsets instead of comparing the pointers.
908 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
909}
910
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000911/// Fold comparisons between a GEP instruction and something else. At this point
912/// we know that the GEP is on the LHS of the comparison.
Sanjay Patel43395062016-07-21 18:07:40 +0000913Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000914 ICmpInst::Predicate Cond,
915 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000916 // Don't transform signed compares of GEPs into index compares. Even if the
917 // GEP is inbounds, the final add of the base pointer can have signed overflow
918 // and would change the result of the icmp.
919 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000920 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000921 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000922 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000923
Matt Arsenault44f60d02014-06-09 19:20:29 +0000924 // Look through bitcasts and addrspacecasts. We do not however want to remove
925 // 0 GEPs.
926 if (!isa<GetElementPtrInst>(RHS))
927 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000928
929 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000930 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000931 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
932 // This transformation (ignoring the base and scales) is valid because we
933 // know pointers can't overflow since the gep is inbounds. See if we can
934 // output an optimized form.
Sanjay Pateld93c4c02016-09-15 18:22:25 +0000935 Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000936
Chris Lattner2188e402010-01-04 07:37:31 +0000937 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000938 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000939 Offset = EmitGEPOffset(GEPLHS);
940 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
941 Constant::getNullValue(Offset->getType()));
942 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
943 // If the base pointers are different, but the indices are the same, just
944 // compare the base pointer.
945 if (PtrBase != GEPRHS->getOperand(0)) {
946 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
947 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
948 GEPRHS->getOperand(0)->getType();
949 if (IndicesTheSame)
950 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
951 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
952 IndicesTheSame = false;
953 break;
954 }
955
956 // If all indices are the same, just compare the base pointers.
957 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000958 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000959
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000960 // If we're comparing GEPs with two base pointers that only differ in type
961 // and both GEPs have only constant indices or just one use, then fold
962 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000963 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000964 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
965 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
966 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000968 Value *LOffset = EmitGEPOffset(GEPLHS);
969 Value *ROffset = EmitGEPOffset(GEPRHS);
970
971 // If we looked through an addrspacecast between different sized address
972 // spaces, the LHS and RHS pointers are different sized
973 // integers. Truncate to the smaller one.
974 Type *LHSIndexTy = LOffset->getType();
975 Type *RHSIndexTy = ROffset->getType();
976 if (LHSIndexTy != RHSIndexTy) {
977 if (LHSIndexTy->getPrimitiveSizeInBits() <
978 RHSIndexTy->getPrimitiveSizeInBits()) {
979 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
980 } else
981 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
982 }
983
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000984 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000985 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000986 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000987 }
988
Chris Lattner2188e402010-01-04 07:37:31 +0000989 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000990 // different. Try convert this to an indexed compare by looking through
991 // PHIs/casts.
992 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +0000993 }
994
995 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000996 if (GEPLHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +0000997 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +0000998 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +0000999
1000 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001001 if (GEPRHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001002 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner2188e402010-01-04 07:37:31 +00001003
Stuart Hastings66a82b92011-05-14 05:55:10 +00001004 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001005 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1006 // If the GEPs only differ by one index, compare it.
1007 unsigned NumDifferences = 0; // Keep track of # differences.
1008 unsigned DiffOperand = 0; // The operand that differs.
1009 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1010 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1011 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1012 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1013 // Irreconcilable differences.
1014 NumDifferences = 2;
1015 break;
1016 } else {
1017 if (NumDifferences++) break;
1018 DiffOperand = i;
1019 }
1020 }
1021
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001022 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001023 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001024 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001025
Stuart Hastings66a82b92011-05-14 05:55:10 +00001026 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001027 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1028 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1029 // Make sure we do a signed comparison here.
1030 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1031 }
1032 }
1033
1034 // Only lower this if the icmp is the only user of the GEP or if we expect
1035 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001036 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001037 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1038 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1039 Value *L = EmitGEPOffset(GEPLHS);
1040 Value *R = EmitGEPOffset(GEPRHS);
1041 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1042 }
1043 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001044
1045 // Try convert this to an indexed compare by looking through PHIs/casts as a
1046 // last resort.
1047 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001048}
1049
Pete Cooper980a9352016-08-12 17:13:28 +00001050Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI,
1051 const AllocaInst *Alloca,
1052 const Value *Other) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001053 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1054
1055 // It would be tempting to fold away comparisons between allocas and any
1056 // pointer not based on that alloca (e.g. an argument). However, even
1057 // though such pointers cannot alias, they can still compare equal.
1058 //
1059 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1060 // doesn't escape we can argue that it's impossible to guess its value, and we
1061 // can therefore act as if any such guesses are wrong.
1062 //
1063 // The code below checks that the alloca doesn't escape, and that it's only
1064 // used in a comparison once (the current instruction). The
1065 // single-comparison-use condition ensures that we're trivially folding all
1066 // comparisons against the alloca consistently, and avoids the risk of
1067 // erroneously folding a comparison of the pointer with itself.
1068
1069 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1070
Pete Cooper980a9352016-08-12 17:13:28 +00001071 SmallVector<const Use *, 32> Worklist;
1072 for (const Use &U : Alloca->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001073 if (Worklist.size() >= MaxIter)
1074 return nullptr;
1075 Worklist.push_back(&U);
1076 }
1077
1078 unsigned NumCmps = 0;
1079 while (!Worklist.empty()) {
1080 assert(Worklist.size() <= MaxIter);
Pete Cooper980a9352016-08-12 17:13:28 +00001081 const Use *U = Worklist.pop_back_val();
1082 const Value *V = U->getUser();
Hans Wennborgf1f36512015-10-07 00:20:07 +00001083 --MaxIter;
1084
1085 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1086 isa<SelectInst>(V)) {
1087 // Track the uses.
1088 } else if (isa<LoadInst>(V)) {
1089 // Loading from the pointer doesn't escape it.
1090 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001091 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001092 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1093 if (SI->getValueOperand() == U->get())
1094 return nullptr;
1095 continue;
1096 } else if (isa<ICmpInst>(V)) {
1097 if (NumCmps++)
1098 return nullptr; // Found more than one cmp.
1099 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001100 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001101 switch (Intrin->getIntrinsicID()) {
1102 // These intrinsics don't escape or compare the pointer. Memset is safe
1103 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1104 // we don't allow stores, so src cannot point to V.
1105 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1106 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1107 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1108 continue;
1109 default:
1110 return nullptr;
1111 }
1112 } else {
1113 return nullptr;
1114 }
Pete Cooper980a9352016-08-12 17:13:28 +00001115 for (const Use &U : V->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001116 if (Worklist.size() >= MaxIter)
1117 return nullptr;
1118 Worklist.push_back(&U);
1119 }
1120 }
1121
1122 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001123 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001124 ICI,
1125 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1126}
1127
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001128/// Fold "icmp pred (X+CI), X".
Sanjay Patel43395062016-07-21 18:07:40 +00001129Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI,
1130 Value *X, ConstantInt *CI,
1131 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001132 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001133 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001134 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001135
Chris Lattner8c92b572010-01-08 17:48:19 +00001136 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001137 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1138 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1139 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001140 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001141 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001142 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1143 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001144
Chris Lattner2188e402010-01-04 07:37:31 +00001145 // (X+1) >u X --> X <u (0-1) --> X != 255
1146 // (X+2) >u X --> X <u (0-2) --> X <u 254
1147 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001148 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001149 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001150
Chris Lattner2188e402010-01-04 07:37:31 +00001151 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1152 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1153 APInt::getSignedMaxValue(BitWidth));
1154
1155 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1156 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1157 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1158 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1159 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1160 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001161 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001162 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001163
Chris Lattner2188e402010-01-04 07:37:31 +00001164 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1165 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1166 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1167 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1168 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1169 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001170
Chris Lattner2188e402010-01-04 07:37:31 +00001171 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001172 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001173 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1174}
1175
Sanjay Patel8da42cc2016-09-15 22:26:31 +00001176/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
1177/// (icmp eq/ne A, Log2(AP2/AP1)) ->
1178/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
1179Instruction *InstCombiner::foldICmpShrConstConst(ICmpInst &I, Value *A,
1180 const APInt &AP1,
1181 const APInt &AP2) {
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001182 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1183
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001184 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1185 if (I.getPredicate() == I.ICMP_NE)
1186 Pred = CmpInst::getInversePredicate(Pred);
1187 return new ICmpInst(Pred, LHS, RHS);
1188 };
1189
David Majnemer2abb8182014-10-25 07:13:13 +00001190 // Don't bother doing any work for cases which InstSimplify handles.
1191 if (AP2 == 0)
1192 return nullptr;
Sanjay Patel8da42cc2016-09-15 22:26:31 +00001193
1194 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
David Majnemer2abb8182014-10-25 07:13:13 +00001195 if (IsAShr) {
1196 if (AP2.isAllOnesValue())
1197 return nullptr;
1198 if (AP2.isNegative() != AP1.isNegative())
1199 return nullptr;
1200 if (AP2.sgt(AP1))
1201 return nullptr;
1202 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001203
David Majnemerd2056022014-10-21 19:51:55 +00001204 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001205 // 'A' must be large enough to shift out the highest set bit.
1206 return getICmp(I.ICMP_UGT, A,
1207 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001208
David Majnemerd2056022014-10-21 19:51:55 +00001209 if (AP1 == AP2)
1210 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001211
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001212 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001213 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001214 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001215 else
David Majnemere5977eb2015-09-19 00:48:26 +00001216 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001217
David Majnemerd2056022014-10-21 19:51:55 +00001218 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001219 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1220 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001221 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001222 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1223 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001224 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001225 } else if (AP1 == AP2.lshr(Shift)) {
1226 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1227 }
David Majnemerd2056022014-10-21 19:51:55 +00001228 }
Sanjay Patel524fcdf2016-09-15 19:04:55 +00001229
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001230 // Shifting const2 will never be equal to const1.
Sanjay Patel524fcdf2016-09-15 19:04:55 +00001231 // FIXME: This should always be handled by InstSimplify?
1232 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1233 return replaceInstUsesWith(I, TorF);
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001234}
Chris Lattner2188e402010-01-04 07:37:31 +00001235
Sanjay Patel8da42cc2016-09-15 22:26:31 +00001236/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1237/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1238Instruction *InstCombiner::foldICmpShlConstConst(ICmpInst &I, Value *A,
1239 const APInt &AP1,
1240 const APInt &AP2) {
David Majnemer59939ac2014-10-19 08:23:08 +00001241 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1242
David Majnemer59939ac2014-10-19 08:23:08 +00001243 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1244 if (I.getPredicate() == I.ICMP_NE)
1245 Pred = CmpInst::getInversePredicate(Pred);
1246 return new ICmpInst(Pred, LHS, RHS);
1247 };
1248
David Majnemer2abb8182014-10-25 07:13:13 +00001249 // Don't bother doing any work for cases which InstSimplify handles.
1250 if (AP2 == 0)
1251 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001252
1253 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1254
1255 if (!AP1 && AP2TrailingZeros != 0)
Sanjay Patelaf91d1f2016-09-15 21:35:30 +00001256 return getICmp(
1257 I.ICMP_UGE, A,
1258 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
David Majnemer59939ac2014-10-19 08:23:08 +00001259
1260 if (AP1 == AP2)
1261 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1262
1263 // Get the distance between the lowest bits that are set.
1264 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1265
1266 if (Shift > 0 && AP2.shl(Shift) == AP1)
1267 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1268
1269 // Shifting const2 will never be equal to const1.
Sanjay Patel524fcdf2016-09-15 19:04:55 +00001270 // FIXME: This should always be handled by InstSimplify?
1271 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1272 return replaceInstUsesWith(I, TorF);
David Majnemer59939ac2014-10-19 08:23:08 +00001273}
1274
Sanjay Patel06b127a2016-09-15 14:37:50 +00001275/// The caller has matched a pattern of the form:
1276/// I = icmp ugt (add (add A, B), CI2), CI1
1277/// If this is of the form:
1278/// sum = a + b
1279/// if (sum+128 >u 255)
1280/// Then replace it with llvm.sadd.with.overflow.i8.
1281///
Sanjay Pateld93c4c02016-09-15 18:22:25 +00001282static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
Sanjay Patel06b127a2016-09-15 14:37:50 +00001283 ConstantInt *CI2, ConstantInt *CI1,
1284 InstCombiner &IC) {
1285 // The transformation we're trying to do here is to transform this into an
1286 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1287 // with a narrower add, and discard the add-with-constant that is part of the
1288 // range check (if we can't eliminate it, this isn't profitable).
1289
1290 // In order to eliminate the add-with-constant, the compare can be its only
1291 // use.
1292 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1293 if (!AddWithCst->hasOneUse())
1294 return nullptr;
1295
1296 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1297 if (!CI2->getValue().isPowerOf2())
1298 return nullptr;
1299 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1300 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1301 return nullptr;
1302
1303 // The width of the new add formed is 1 more than the bias.
1304 ++NewWidth;
1305
1306 // Check to see that CI1 is an all-ones value with NewWidth bits.
1307 if (CI1->getBitWidth() == NewWidth ||
1308 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1309 return nullptr;
1310
1311 // This is only really a signed overflow check if the inputs have been
1312 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1313 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1314 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1315 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
1316 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
1317 return nullptr;
1318
1319 // In order to replace the original add with a narrower
1320 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1321 // and truncates that discard the high bits of the add. Verify that this is
1322 // the case.
1323 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1324 for (User *U : OrigAdd->users()) {
1325 if (U == AddWithCst)
1326 continue;
1327
1328 // Only accept truncates for now. We would really like a nice recursive
1329 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1330 // chain to see which bits of a value are actually demanded. If the
1331 // original add had another add which was then immediately truncated, we
1332 // could still do the transformation.
1333 TruncInst *TI = dyn_cast<TruncInst>(U);
1334 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1335 return nullptr;
1336 }
1337
1338 // If the pattern matches, truncate the inputs to the narrower type and
1339 // use the sadd_with_overflow intrinsic to efficiently compute both the
1340 // result and the overflow bit.
1341 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1342 Value *F = Intrinsic::getDeclaration(I.getModule(),
1343 Intrinsic::sadd_with_overflow, NewType);
1344
1345 InstCombiner::BuilderTy *Builder = IC.Builder;
1346
1347 // Put the new code above the original add, in case there are any uses of the
1348 // add between the add and the compare.
1349 Builder->SetInsertPoint(OrigAdd);
1350
1351 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName() + ".trunc");
1352 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName() + ".trunc");
1353 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
1354 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1355 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1356
1357 // The inner add was the result of the narrow add, zero extended to the
1358 // wider type. Replace it with the result computed by the intrinsic.
1359 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1360
1361 // The original icmp gets replaced with the overflow value.
1362 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1363}
1364
1365// Fold icmp Pred X, C.
Sanjay Patel97459832016-09-15 15:11:12 +00001366Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &Cmp) {
1367 CmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001368 Value *X = Cmp.getOperand(0);
Sanjay Patel06b127a2016-09-15 14:37:50 +00001369
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001370 const APInt *C;
1371 if (!match(Cmp.getOperand(1), m_APInt(C)))
Sanjay Patel97459832016-09-15 15:11:12 +00001372 return nullptr;
Sanjay Patel06b127a2016-09-15 14:37:50 +00001373
Sanjay Patel97459832016-09-15 15:11:12 +00001374 Value *A = nullptr, *B = nullptr;
Sanjay Patel06b127a2016-09-15 14:37:50 +00001375
Sanjay Patel97459832016-09-15 15:11:12 +00001376 // Match the following pattern, which is a common idiom when writing
1377 // overflow-safe integer arithmetic functions. The source performs an addition
1378 // in wider type and explicitly checks for overflow using comparisons against
1379 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1380 //
1381 // TODO: This could probably be generalized to handle other overflow-safe
1382 // operations if we worked out the formulas to compute the appropriate magic
1383 // constants.
1384 //
1385 // sum = a + b
1386 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1387 {
1388 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1389 if (Pred == ICmpInst::ICMP_UGT &&
1390 match(X, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Sanjay Pateld93c4c02016-09-15 18:22:25 +00001391 if (Instruction *Res = processUGT_ADDCST_ADD(
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001392 Cmp, A, B, CI2, cast<ConstantInt>(Cmp.getOperand(1)), *this))
Sanjay Patel97459832016-09-15 15:11:12 +00001393 return Res;
1394 }
Sanjay Patel06b127a2016-09-15 14:37:50 +00001395
Sanjay Patel97459832016-09-15 15:11:12 +00001396 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001397 if (*C == 0 && Pred == ICmpInst::ICMP_SGT) {
1398 SelectPatternResult SPR = matchSelectPattern(X, A, B);
1399 if (SPR.Flavor == SPF_SMIN) {
1400 if (isKnownPositive(A, DL))
1401 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1402 if (isKnownPositive(B, DL))
1403 return new ICmpInst(Pred, A, Cmp.getOperand(1));
Sanjay Patel06b127a2016-09-15 14:37:50 +00001404 }
Sanjay Patel40c53ea2016-09-15 16:23:20 +00001405 }
1406
1407 // FIXME: Use m_APInt to allow folds for splat constants.
1408 ConstantInt *CI = dyn_cast<ConstantInt>(Cmp.getOperand(1));
1409 if (!CI)
1410 return nullptr;
Sanjay Patel06b127a2016-09-15 14:37:50 +00001411
Sanjay Patel97459832016-09-15 15:11:12 +00001412 // Canonicalize icmp instructions based on dominating conditions.
1413 BasicBlock *Parent = Cmp.getParent();
1414 BasicBlock *Dom = Parent->getSinglePredecessor();
1415 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
1416 ICmpInst::Predicate Pred2;
1417 BasicBlock *TrueBB, *FalseBB;
1418 ConstantInt *CI2;
1419 if (BI && match(BI, m_Br(m_ICmp(Pred2, m_Specific(X), m_ConstantInt(CI2)),
1420 TrueBB, FalseBB)) &&
1421 TrueBB != FalseBB) {
1422 ConstantRange CR =
1423 ConstantRange::makeAllowedICmpRegion(Pred, CI->getValue());
1424 ConstantRange DominatingCR =
1425 (Parent == TrueBB)
1426 ? ConstantRange::makeExactICmpRegion(Pred2, CI2->getValue())
1427 : ConstantRange::makeExactICmpRegion(
1428 CmpInst::getInversePredicate(Pred2), CI2->getValue());
1429 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1430 ConstantRange Difference = DominatingCR.difference(CR);
1431 if (Intersection.isEmptySet())
1432 return replaceInstUsesWith(Cmp, Builder->getFalse());
1433 if (Difference.isEmptySet())
1434 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel06b127a2016-09-15 14:37:50 +00001435
Sanjay Patel97459832016-09-15 15:11:12 +00001436 // If this is a normal comparison, it demands all bits. If it is a sign
1437 // bit comparison, it only demands the sign bit.
1438 bool UnusedBit;
1439 bool IsSignBit = isSignBitCheck(Pred, CI->getValue(), UnusedBit);
1440
1441 // Canonicalizing a sign bit comparison that gets used in a branch,
1442 // pessimizes codegen by generating branch on zero instruction instead
1443 // of a test and branch. So we avoid canonicalizing in such situations
1444 // because test and branch instruction has better branch displacement
1445 // than compare and branch instruction.
1446 if (!isBranchOnSignBitCheck(Cmp, IsSignBit) && !Cmp.isEquality()) {
1447 if (auto *AI = Intersection.getSingleElement())
1448 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder->getInt(*AI));
1449 if (auto *AD = Difference.getSingleElement())
1450 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder->getInt(*AD));
Sanjay Patel06b127a2016-09-15 14:37:50 +00001451 }
1452 }
1453
1454 return nullptr;
1455}
1456
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001457/// Fold icmp (trunc X, Y), C.
1458Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp,
1459 Instruction *Trunc,
1460 const APInt *C) {
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001461 ICmpInst::Predicate Pred = Cmp.getPredicate();
1462 Value *X = Trunc->getOperand(0);
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001463 if (*C == 1 && C->getBitWidth() > 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001464 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1465 Value *V = nullptr;
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001466 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001467 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1468 ConstantInt::get(V->getType(), 1));
1469 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001470
1471 if (Cmp.isEquality() && Trunc->hasOneUse()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001472 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1473 // of the high bits truncated out of x are known.
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001474 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1475 SrcBits = X->getType()->getScalarSizeInBits();
Sanjay Patela3f4f082016-08-16 17:54:36 +00001476 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001477 computeKnownBits(X, KnownZero, KnownOne, 0, &Cmp);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001478
1479 // If all the high bits are known, we can do this xform.
1480 if ((KnownZero | KnownOne).countLeadingOnes() >= SrcBits - DstBits) {
1481 // Pull in the high bits from known-ones set.
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001482 APInt NewRHS = C->zext(SrcBits);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001483 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001484 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001485 }
1486 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001487
Sanjay Patela3f4f082016-08-16 17:54:36 +00001488 return nullptr;
1489}
1490
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001491/// Fold icmp (xor X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001492Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp,
1493 BinaryOperator *Xor,
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001494 const APInt *C) {
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001495 Value *X = Xor->getOperand(0);
1496 Value *Y = Xor->getOperand(1);
Sanjay Pateldaffec912016-08-17 19:45:18 +00001497 const APInt *XorC;
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001498 if (!match(Y, m_APInt(XorC)))
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001499 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001500
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001501 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1502 // fold the xor.
1503 ICmpInst::Predicate Pred = Cmp.getPredicate();
1504 if ((Pred == ICmpInst::ICMP_SLT && *C == 0) ||
1505 (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001506
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001507 // If the sign bit of the XorCst is not set, there is no change to
1508 // the operation, just stop using the Xor.
Sanjay Pateldaffec912016-08-17 19:45:18 +00001509 if (!XorC->isNegative()) {
1510 Cmp.setOperand(0, X);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001511 Worklist.Add(Xor);
1512 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001513 }
1514
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001515 // Was the old condition true if the operand is positive?
1516 bool isTrueIfPositive = Pred == ICmpInst::ICMP_SGT;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001517
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001518 // If so, the new one isn't.
1519 isTrueIfPositive ^= true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001520
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001521 Constant *CmpConstant = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001522 if (isTrueIfPositive)
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001523 return new ICmpInst(ICmpInst::ICMP_SGT, X, SubOne(CmpConstant));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001524 else
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001525 return new ICmpInst(ICmpInst::ICMP_SLT, X, AddOne(CmpConstant));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001526 }
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001527
1528 if (Xor->hasOneUse()) {
Sanjay Pateldaffec912016-08-17 19:45:18 +00001529 // (icmp u/s (xor X SignBit), C) -> (icmp s/u X, (xor C SignBit))
1530 if (!Cmp.isEquality() && XorC->isSignBit()) {
1531 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1532 : Cmp.getSignedPredicate();
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001533 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001534 }
1535
Sanjay Pateldaffec912016-08-17 19:45:18 +00001536 // (icmp u/s (xor X ~SignBit), C) -> (icmp s/u X, (xor C ~SignBit))
1537 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1538 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1539 : Cmp.getSignedPredicate();
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001540 Pred = Cmp.getSwappedPredicate(Pred);
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001541 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001542 }
1543 }
1544
1545 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1546 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001547 if (Pred == ICmpInst::ICMP_UGT && *XorC == ~(*C) && (*C + 1).isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001548 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001549
1550 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1551 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001552 if (Pred == ICmpInst::ICMP_ULT && *XorC == -(*C) && C->isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001553 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001554
Sanjay Patela3f4f082016-08-16 17:54:36 +00001555 return nullptr;
1556}
1557
Sanjay Patel14e0e182016-08-26 18:28:46 +00001558/// Fold icmp (and (sh X, Y), C2), C1.
1559Instruction *InstCombiner::foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
Sanjay Patel9b40f982016-09-07 22:33:03 +00001560 const APInt *C1, const APInt *C2) {
1561 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1562 if (!Shift || !Shift->isShift())
Sanjay Patelda9c5622016-08-26 17:15:22 +00001563 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001564
Sanjay Patelda9c5622016-08-26 17:15:22 +00001565 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1566 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1567 // code produced by the clang front-end, for bitfield access.
Sanjay Patelda9c5622016-08-26 17:15:22 +00001568 // This seemingly simple opportunity to fold away a shift turns out to be
1569 // rather complicated. See PR17827 for details.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001570 unsigned ShiftOpcode = Shift->getOpcode();
1571 bool IsShl = ShiftOpcode == Instruction::Shl;
1572 const APInt *C3;
1573 if (match(Shift->getOperand(1), m_APInt(C3))) {
Sanjay Patelda9c5622016-08-26 17:15:22 +00001574 bool CanFold = false;
Sanjay Patelda9c5622016-08-26 17:15:22 +00001575 if (ShiftOpcode == Instruction::AShr) {
1576 // There may be some constraints that make this possible, but nothing
1577 // simple has been discovered yet.
1578 CanFold = false;
1579 } else if (ShiftOpcode == Instruction::Shl) {
1580 // For a left shift, we can fold if the comparison is not signed. We can
1581 // also fold a signed comparison if the mask value and comparison value
1582 // are not negative. These constraints may not be obvious, but we can
1583 // prove that they are correct using an SMT solver.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001584 if (!Cmp.isSigned() || (!C2->isNegative() && !C1->isNegative()))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001585 CanFold = true;
1586 } else if (ShiftOpcode == Instruction::LShr) {
1587 // For a logical right shift, we can fold if the comparison is not signed.
1588 // We can also fold a signed comparison if the shifted mask value and the
1589 // shifted comparison value are not negative. These constraints may not be
1590 // obvious, but we can prove that they are correct using an SMT solver.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001591 if (!Cmp.isSigned() ||
1592 (!C2->shl(*C3).isNegative() && !C1->shl(*C3).isNegative()))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001593 CanFold = true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001594 }
1595
Sanjay Patelda9c5622016-08-26 17:15:22 +00001596 if (CanFold) {
Sanjay Patel9b40f982016-09-07 22:33:03 +00001597 APInt NewCst = IsShl ? C1->lshr(*C3) : C1->shl(*C3);
1598 APInt SameAsC1 = IsShl ? NewCst.shl(*C3) : NewCst.lshr(*C3);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001599 // Check to see if we are shifting out any of the bits being compared.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001600 if (SameAsC1 != *C1) {
Sanjay Patelda9c5622016-08-26 17:15:22 +00001601 // If we shifted bits out, the fold is not going to work out. As a
1602 // special case, check to see if this means that the result is always
1603 // true or false now.
1604 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
Sanjay Patel1c608f42016-09-08 16:54:02 +00001605 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
Sanjay Patelda9c5622016-08-26 17:15:22 +00001606 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
Sanjay Patel1c608f42016-09-08 16:54:02 +00001607 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001608 } else {
Sanjay Patel9b40f982016-09-07 22:33:03 +00001609 Cmp.setOperand(1, ConstantInt::get(And->getType(), NewCst));
1610 APInt NewAndCst = IsShl ? C2->lshr(*C3) : C2->shl(*C3);
1611 And->setOperand(1, ConstantInt::get(And->getType(), NewAndCst));
Sanjay Patelda9c5622016-08-26 17:15:22 +00001612 And->setOperand(0, Shift->getOperand(0));
1613 Worklist.Add(Shift); // Shift is dead.
1614 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001615 }
Sanjay Patelda9c5622016-08-26 17:15:22 +00001616 }
1617 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001618
Sanjay Patelda9c5622016-08-26 17:15:22 +00001619 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1620 // preferable because it allows the C2 << Y expression to be hoisted out of a
1621 // loop if Y is invariant and X is not.
Sanjay Patel14e0e182016-08-26 18:28:46 +00001622 if (Shift->hasOneUse() && *C1 == 0 && Cmp.isEquality() &&
Sanjay Patelda9c5622016-08-26 17:15:22 +00001623 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1624 // Compute C2 << Y.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001625 Value *NewShift =
1626 IsShl ? Builder->CreateLShr(And->getOperand(1), Shift->getOperand(1))
1627 : Builder->CreateShl(And->getOperand(1), Shift->getOperand(1));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001628
Sanjay Patelda9c5622016-08-26 17:15:22 +00001629 // Compute X & (C2 << Y).
Sanjay Patel9b40f982016-09-07 22:33:03 +00001630 Value *NewAnd = Builder->CreateAnd(Shift->getOperand(0), NewShift);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001631 Cmp.setOperand(0, NewAnd);
1632 return &Cmp;
1633 }
1634
Sanjay Patel14e0e182016-08-26 18:28:46 +00001635 return nullptr;
1636}
1637
1638/// Fold icmp (and X, C2), C1.
1639Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp,
1640 BinaryOperator *And,
1641 const APInt *C1) {
Sanjay Patel6b490972016-09-04 14:32:15 +00001642 const APInt *C2;
1643 if (!match(And->getOperand(1), m_APInt(C2)))
Sanjay Patel14e0e182016-08-26 18:28:46 +00001644 return nullptr;
1645
1646 if (!And->hasOneUse() || !And->getOperand(0)->hasOneUse())
1647 return nullptr;
1648
Sanjay Patel6b490972016-09-04 14:32:15 +00001649 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1650 // the input width without changing the value produced, eliminate the cast:
1651 //
1652 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1653 //
1654 // We can do this transformation if the constants do not have their sign bits
1655 // set or if it is an equality comparison. Extending a relational comparison
1656 // when we're checking the sign bit would not work.
1657 Value *W;
1658 if (match(And->getOperand(0), m_Trunc(m_Value(W))) &&
1659 (Cmp.isEquality() || (!C1->isNegative() && !C2->isNegative()))) {
1660 // TODO: Is this a good transform for vectors? Wider types may reduce
1661 // throughput. Should this transform be limited (even for scalars) by using
1662 // ShouldChangeType()?
1663 if (!Cmp.getType()->isVectorTy()) {
1664 Type *WideType = W->getType();
1665 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1666 Constant *ZextC1 = ConstantInt::get(WideType, C1->zext(WideScalarBits));
1667 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1668 Value *NewAnd = Builder->CreateAnd(W, ZextC2, And->getName());
1669 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
Sanjay Patel14e0e182016-08-26 18:28:46 +00001670 }
1671 }
1672
Sanjay Patel9b40f982016-09-07 22:33:03 +00001673 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2))
Sanjay Patel14e0e182016-08-26 18:28:46 +00001674 return I;
1675
Sanjay Patelda9c5622016-08-26 17:15:22 +00001676 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
Sanjay Patel6b490972016-09-04 14:32:15 +00001677 // (icmp pred (and A, (or (shl 1, B), 1), 0))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001678 //
1679 // iff pred isn't signed
Sanjay Pateldef931e2016-09-07 20:50:44 +00001680 if (!Cmp.isSigned() && *C1 == 0 && match(And->getOperand(1), m_One())) {
1681 Constant *One = cast<Constant>(And->getOperand(1));
1682 Value *Or = And->getOperand(0);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001683 Value *A, *B, *LShr;
Sanjay Pateldef931e2016-09-07 20:50:44 +00001684 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1685 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1686 unsigned UsesRemoved = 0;
1687 if (And->hasOneUse())
1688 ++UsesRemoved;
1689 if (Or->hasOneUse())
1690 ++UsesRemoved;
1691 if (LShr->hasOneUse())
1692 ++UsesRemoved;
1693
1694 // Compute A & ((1 << B) | 1)
1695 Value *NewOr = nullptr;
1696 if (auto *C = dyn_cast<Constant>(B)) {
1697 if (UsesRemoved >= 1)
1698 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1699 } else {
1700 if (UsesRemoved >= 3)
1701 NewOr = Builder->CreateOr(Builder->CreateShl(One, B, LShr->getName(),
Sanjay Patelda9c5622016-08-26 17:15:22 +00001702 /*HasNUW=*/true),
1703 One, Or->getName());
Sanjay Pateldef931e2016-09-07 20:50:44 +00001704 }
1705 if (NewOr) {
1706 Value *NewAnd = Builder->CreateAnd(A, NewOr, And->getName());
1707 Cmp.setOperand(0, NewAnd);
1708 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001709 }
1710 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001711 }
Sanjay Patelda9c5622016-08-26 17:15:22 +00001712
Sanjay Pateldef931e2016-09-07 20:50:44 +00001713 // (X & C2) > C1 --> (X & C2) != 0, if any bit set in (X & C2) will produce a
1714 // result greater than C1.
1715 unsigned NumTZ = C2->countTrailingZeros();
1716 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && NumTZ < C2->getBitWidth() &&
1717 APInt::getOneBitSet(C2->getBitWidth(), NumTZ).ugt(*C1)) {
1718 Constant *Zero = Constant::getNullValue(And->getType());
1719 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001720 }
1721
Sanjay Pateld3c7bb282016-08-26 16:42:33 +00001722 return nullptr;
1723}
1724
1725/// Fold icmp (and X, Y), C.
1726Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp,
1727 BinaryOperator *And,
1728 const APInt *C) {
1729 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1730 return I;
1731
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001732 // TODO: These all require that Y is constant too, so refactor with the above.
Sanjay Patela3f4f082016-08-16 17:54:36 +00001733
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001734 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1735 Value *X = And->getOperand(0);
1736 Value *Y = And->getOperand(1);
1737 if (auto *LI = dyn_cast<LoadInst>(X))
1738 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1739 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001740 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001741 !LI->isVolatile() && isa<ConstantInt>(Y)) {
1742 ConstantInt *C2 = cast<ConstantInt>(Y);
1743 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001744 return Res;
1745 }
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001746
1747 if (!Cmp.isEquality())
1748 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001749
1750 // X & -C == -C -> X > u ~C
1751 // X & -C != -C -> X <= u ~C
1752 // iff C is a power of 2
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001753 if (Cmp.getOperand(1) == Y && (-(*C)).isPowerOf2()) {
1754 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT
1755 : CmpInst::ICMP_ULE;
1756 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1757 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001758
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001759 // (X & C2) == 0 -> (trunc X) >= 0
1760 // (X & C2) != 0 -> (trunc X) < 0
1761 // iff C2 is a power of 2 and it masks the sign bit of a legal integer type.
1762 const APInt *C2;
1763 if (And->hasOneUse() && *C == 0 && match(Y, m_APInt(C2))) {
1764 int32_t ExactLogBase2 = C2->exactLogBase2();
1765 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1766 Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1);
1767 if (And->getType()->isVectorTy())
1768 NTy = VectorType::get(NTy, And->getType()->getVectorNumElements());
1769 Value *Trunc = Builder->CreateTrunc(X, NTy);
1770 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE
1771 : CmpInst::ICMP_SLT;
1772 return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001773 }
1774 }
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001775
Sanjay Patela3f4f082016-08-16 17:54:36 +00001776 return nullptr;
1777}
1778
Sanjay Patel943e92e2016-08-17 16:30:43 +00001779/// Fold icmp (or X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001780Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
Sanjay Patel943e92e2016-08-17 16:30:43 +00001781 const APInt *C) {
Sanjay Patel943e92e2016-08-17 16:30:43 +00001782 ICmpInst::Predicate Pred = Cmp.getPredicate();
1783 if (*C == 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001784 // icmp slt signum(V) 1 --> icmp slt V, 1
1785 Value *V = nullptr;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001786 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001787 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1788 ConstantInt::get(V->getType(), 1));
1789 }
1790
Sanjay Patel943e92e2016-08-17 16:30:43 +00001791 if (!Cmp.isEquality() || *C != 0 || !Or->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00001792 return nullptr;
1793
1794 Value *P, *Q;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001795 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001796 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1797 // -> and (icmp eq P, null), (icmp eq Q, null).
Reid Klecknera871d382016-08-19 16:53:18 +00001798 Value *CmpP =
1799 Builder->CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
1800 Value *CmpQ =
1801 Builder->CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
Sanjay Patel943e92e2016-08-17 16:30:43 +00001802 auto LogicOpc = Pred == ICmpInst::Predicate::ICMP_EQ ? Instruction::And
1803 : Instruction::Or;
1804 return BinaryOperator::Create(LogicOpc, CmpP, CmpQ);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001805 }
Sanjay Patel943e92e2016-08-17 16:30:43 +00001806
Sanjay Patela3f4f082016-08-16 17:54:36 +00001807 return nullptr;
1808}
1809
Sanjay Patel63478072016-08-18 15:44:44 +00001810/// Fold icmp (mul X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001811Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp,
1812 BinaryOperator *Mul,
Sanjay Patel63478072016-08-18 15:44:44 +00001813 const APInt *C) {
1814 const APInt *MulC;
1815 if (!match(Mul->getOperand(1), m_APInt(MulC)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001816 return nullptr;
1817
Sanjay Patel63478072016-08-18 15:44:44 +00001818 // If this is a test of the sign bit and the multiply is sign-preserving with
1819 // a constant operand, use the multiply LHS operand instead.
1820 ICmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patelc9196c42016-08-22 21:24:29 +00001821 if (isSignTest(Pred, *C) && Mul->hasNoSignedWrap()) {
Sanjay Patel63478072016-08-18 15:44:44 +00001822 if (MulC->isNegative())
1823 Pred = ICmpInst::getSwappedPredicate(Pred);
1824 return new ICmpInst(Pred, Mul->getOperand(0),
1825 Constant::getNullValue(Mul->getType()));
1826 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001827
1828 return nullptr;
1829}
1830
Sanjay Patel98cd99d2016-08-18 21:28:30 +00001831/// Fold icmp (shl 1, Y), C.
1832static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
1833 const APInt *C) {
1834 Value *Y;
1835 if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
1836 return nullptr;
1837
1838 Type *ShiftType = Shl->getType();
1839 uint32_t TypeBits = C->getBitWidth();
1840 bool CIsPowerOf2 = C->isPowerOf2();
1841 ICmpInst::Predicate Pred = Cmp.getPredicate();
1842 if (Cmp.isUnsigned()) {
1843 // (1 << Y) pred C -> Y pred Log2(C)
1844 if (!CIsPowerOf2) {
1845 // (1 << Y) < 30 -> Y <= 4
1846 // (1 << Y) <= 30 -> Y <= 4
1847 // (1 << Y) >= 30 -> Y > 4
1848 // (1 << Y) > 30 -> Y > 4
1849 if (Pred == ICmpInst::ICMP_ULT)
1850 Pred = ICmpInst::ICMP_ULE;
1851 else if (Pred == ICmpInst::ICMP_UGE)
1852 Pred = ICmpInst::ICMP_UGT;
1853 }
1854
1855 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31
1856 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31
1857 unsigned CLog2 = C->logBase2();
1858 if (CLog2 == TypeBits - 1) {
1859 if (Pred == ICmpInst::ICMP_UGE)
1860 Pred = ICmpInst::ICMP_EQ;
1861 else if (Pred == ICmpInst::ICMP_ULT)
1862 Pred = ICmpInst::ICMP_NE;
1863 }
1864 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
1865 } else if (Cmp.isSigned()) {
1866 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
1867 if (C->isAllOnesValue()) {
1868 // (1 << Y) <= -1 -> Y == 31
1869 if (Pred == ICmpInst::ICMP_SLE)
1870 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1871
1872 // (1 << Y) > -1 -> Y != 31
1873 if (Pred == ICmpInst::ICMP_SGT)
1874 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1875 } else if (!(*C)) {
1876 // (1 << Y) < 0 -> Y == 31
1877 // (1 << Y) <= 0 -> Y == 31
1878 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1879 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1880
1881 // (1 << Y) >= 0 -> Y != 31
1882 // (1 << Y) > 0 -> Y != 31
1883 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1884 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1885 }
1886 } else if (Cmp.isEquality() && CIsPowerOf2) {
1887 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C->logBase2()));
1888 }
1889
1890 return nullptr;
1891}
1892
Sanjay Patel38b75062016-08-19 17:20:37 +00001893/// Fold icmp (shl X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001894Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp,
1895 BinaryOperator *Shl,
Sanjay Patel38b75062016-08-19 17:20:37 +00001896 const APInt *C) {
Sanjay Patel8da42cc2016-09-15 22:26:31 +00001897 const APInt *ShiftVal;
1898 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
1899 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), *C, *ShiftVal);
1900
Sanjay Patelfa7de602016-08-19 22:33:26 +00001901 const APInt *ShiftAmt;
1902 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
Sanjay Patel38b75062016-08-19 17:20:37 +00001903 return foldICmpShlOne(Cmp, Shl, C);
Sanjay Patela867afe2016-08-19 16:12:16 +00001904
Sanjay Patel38b75062016-08-19 17:20:37 +00001905 // Check that the shift amount is in range. If not, don't perform undefined
1906 // shifts. When the shift is visited it will be simplified.
1907 unsigned TypeBits = C->getBitWidth();
Sanjay Patelfa7de602016-08-19 22:33:26 +00001908 if (ShiftAmt->uge(TypeBits))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001909 return nullptr;
1910
Sanjay Patele38e79c2016-08-19 17:34:05 +00001911 ICmpInst::Predicate Pred = Cmp.getPredicate();
1912 Value *X = Shl->getOperand(0);
Sanjay Patel38b75062016-08-19 17:20:37 +00001913 if (Cmp.isEquality()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001914 // If the shift is NUW, then it is just shifting out zeros, no need for an
1915 // AND.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001916 Constant *LShrC = ConstantInt::get(Shl->getType(), C->lshr(*ShiftAmt));
Sanjay Patelc9196c42016-08-22 21:24:29 +00001917 if (Shl->hasNoUnsignedWrap())
Sanjay Patelfa7de602016-08-19 22:33:26 +00001918 return new ICmpInst(Pred, X, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001919
1920 // If the shift is NSW and we compare to 0, then it is just shifting out
1921 // sign bits, no need for an AND either.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001922 if (Shl->hasNoSignedWrap() && *C == 0)
Sanjay Patelfa7de602016-08-19 22:33:26 +00001923 return new ICmpInst(Pred, X, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001924
Sanjay Patel38b75062016-08-19 17:20:37 +00001925 if (Shl->hasOneUse()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001926 // Otherwise strength reduce the shift into an and.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001927 Constant *Mask = ConstantInt::get(Shl->getType(),
1928 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001929
Sanjay Patele38e79c2016-08-19 17:34:05 +00001930 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask");
Sanjay Patelfa7de602016-08-19 22:33:26 +00001931 return new ICmpInst(Pred, And, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001932 }
1933 }
1934
1935 // If this is a signed comparison to 0 and the shift is sign preserving,
Sanjay Patele38e79c2016-08-19 17:34:05 +00001936 // use the shift LHS operand instead; isSignTest may change 'Pred', so only
1937 // do that if we're sure to not continue on in this function.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001938 if (Shl->hasNoSignedWrap() && isSignTest(Pred, *C))
Sanjay Patel7e09f132016-08-21 16:28:22 +00001939 return new ICmpInst(Pred, X, Constant::getNullValue(X->getType()));
1940
Sanjay Patela3f4f082016-08-16 17:54:36 +00001941 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1942 bool TrueIfSigned = false;
Sanjay Patel79263662016-08-21 15:07:45 +00001943 if (Shl->hasOneUse() && isSignBitCheck(Pred, *C, TrueIfSigned)) {
Sanjay Patel7ffcde72016-08-21 16:35:34 +00001944 // (X << 31) <s 0 --> (X & 1) != 0
Sanjay Patela3f4f082016-08-16 17:54:36 +00001945 Constant *Mask = ConstantInt::get(
Sanjay Patele38e79c2016-08-19 17:34:05 +00001946 X->getType(),
Sanjay Patelfa7de602016-08-19 22:33:26 +00001947 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
Sanjay Patele38e79c2016-08-19 17:34:05 +00001948 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask");
Sanjay Patela3f4f082016-08-16 17:54:36 +00001949 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1950 And, Constant::getNullValue(And->getType()));
1951 }
1952
Sanjay Patelc0339c72016-11-01 19:19:29 +00001953 // When the shift is nuw and pred is >u or <=u, comparison only really happens
1954 // in the pre-shifted bits. Since InstSimplify canoncalizes <=u into <u, the
1955 // <=u case can be further converted to match <u (see below).
1956 if (Shl->hasNoUnsignedWrap() &&
1957 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
1958 // Derivation for the ult case:
1959 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
1960 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
1961 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
1962 assert((Pred != ICmpInst::ICMP_ULT || C->ugt(0)) &&
1963 "Encountered `ult 0` that should have been eliminated by "
1964 "InstSimplify.");
1965 APInt ShiftedC = Pred == ICmpInst::ICMP_ULT ? (*C - 1).lshr(*ShiftAmt) + 1
1966 : C->lshr(*ShiftAmt);
1967 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), ShiftedC));
1968 }
1969
Sanjay Patel643d21a2016-08-21 17:10:07 +00001970 // Transform (icmp pred iM (shl iM %v, N), C)
1971 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
1972 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
1973 // This enables us to get rid of the shift in favor of a trunc which can be
Sanjay Patela3f4f082016-08-16 17:54:36 +00001974 // free on the target. It has the additional benefit of comparing to a
1975 // smaller constant, which will be target friendly.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001976 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
Sanjay Patelf3dda132016-10-25 20:11:47 +00001977 if (Shl->hasOneUse() && Amt != 0 && C->countTrailingZeros() >= Amt &&
1978 DL.isLegalInteger(TypeBits - Amt)) {
Sanjay Patel643d21a2016-08-21 17:10:07 +00001979 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
1980 if (X->getType()->isVectorTy())
1981 TruncTy = VectorType::get(TruncTy, X->getType()->getVectorNumElements());
1982 Constant *NewC =
1983 ConstantInt::get(TruncTy, C->ashr(*ShiftAmt).trunc(TypeBits - Amt));
1984 return new ICmpInst(Pred, Builder->CreateTrunc(X, TruncTy), NewC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001985 }
1986
1987 return nullptr;
1988}
1989
Sanjay Patela3920492016-08-22 20:45:06 +00001990/// Fold icmp ({al}shr X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001991Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp,
1992 BinaryOperator *Shr,
1993 const APInt *C) {
Sanjay Patela3920492016-08-22 20:45:06 +00001994 // An exact shr only shifts out zero bits, so:
1995 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
Sanjay Pateld64e9882016-08-23 22:05:55 +00001996 Value *X = Shr->getOperand(0);
Sanjay Patelc9196c42016-08-22 21:24:29 +00001997 CmpInst::Predicate Pred = Cmp.getPredicate();
1998 if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() && *C == 0)
Sanjay Pateld64e9882016-08-23 22:05:55 +00001999 return new ICmpInst(Pred, X, Cmp.getOperand(1));
Sanjay Patela3920492016-08-22 20:45:06 +00002000
Sanjay Patel8da42cc2016-09-15 22:26:31 +00002001 const APInt *ShiftVal;
2002 if (Cmp.isEquality() && match(Shr->getOperand(0), m_APInt(ShiftVal)))
2003 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), *C, *ShiftVal);
2004
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002005 const APInt *ShiftAmt;
2006 if (!match(Shr->getOperand(1), m_APInt(ShiftAmt)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002007 return nullptr;
2008
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002009 // Check that the shift amount is in range. If not, don't perform undefined
2010 // shifts. When the shift is visited it will be simplified.
2011 unsigned TypeBits = C->getBitWidth();
2012 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002013 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2014 return nullptr;
2015
Sanjay Pateld64e9882016-08-23 22:05:55 +00002016 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002017 if (!Cmp.isEquality()) {
2018 // If we have an unsigned comparison and an ashr, we can't simplify this.
2019 // Similarly for signed comparisons with lshr.
Sanjay Pateld64e9882016-08-23 22:05:55 +00002020 if (Cmp.isSigned() != IsAShr)
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002021 return nullptr;
2022
2023 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
2024 // by a power of 2. Since we already have logic to simplify these,
2025 // transform to div and then simplify the resultant comparison.
Sanjay Pateld64e9882016-08-23 22:05:55 +00002026 if (IsAShr && (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002027 return nullptr;
2028
2029 // Revisit the shift (to delete it).
2030 Worklist.Add(Shr);
2031
2032 Constant *DivCst = ConstantInt::get(
2033 Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
2034
Sanjay Pateld64e9882016-08-23 22:05:55 +00002035 Value *Tmp = IsAShr ? Builder->CreateSDiv(X, DivCst, "", Shr->isExact())
2036 : Builder->CreateUDiv(X, DivCst, "", Shr->isExact());
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002037
2038 Cmp.setOperand(0, Tmp);
2039
2040 // If the builder folded the binop, just return it.
2041 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
2042 if (!TheDiv)
2043 return &Cmp;
2044
2045 // Otherwise, fold this div/compare.
2046 assert(TheDiv->getOpcode() == Instruction::SDiv ||
2047 TheDiv->getOpcode() == Instruction::UDiv);
2048
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002049 Instruction *Res = foldICmpDivConstant(Cmp, TheDiv, C);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002050 assert(Res && "This div/cst should have folded!");
Sanjay Patela3920492016-08-22 20:45:06 +00002051 return Res;
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002052 }
2053
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002054 // Handle equality comparisons of shift-by-constant.
2055
Sanjay Patel8e297742016-08-24 13:55:55 +00002056 // If the comparison constant changes with the shift, the comparison cannot
2057 // succeed (bits of the comparison constant cannot match the shifted value).
2058 // This should be known by InstSimplify and already be folded to true/false.
2059 assert(((IsAShr && C->shl(ShAmtVal).ashr(ShAmtVal) == *C) ||
2060 (!IsAShr && C->shl(ShAmtVal).lshr(ShAmtVal) == *C)) &&
2061 "Expected icmp+shr simplify did not occur.");
2062
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002063 // Check if the bits shifted out are known to be zero. If so, we can compare
2064 // against the unshifted value:
2065 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002066 Constant *ShiftedCmpRHS = ConstantInt::get(Shr->getType(), *C << ShAmtVal);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002067 if (Shr->hasOneUse()) {
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002068 if (Shr->isExact())
2069 return new ICmpInst(Pred, X, ShiftedCmpRHS);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002070
Sanjay Pateld398d4a2016-08-24 22:22:06 +00002071 // Otherwise strength reduce the shift into an 'and'.
2072 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2073 Constant *Mask = ConstantInt::get(Shr->getType(), Val);
Sanjay Pateld64e9882016-08-23 22:05:55 +00002074 Value *And = Builder->CreateAnd(X, Mask, Shr->getName() + ".mask");
Sanjay Pateldcac0df2016-08-23 21:25:13 +00002075 return new ICmpInst(Pred, And, ShiftedCmpRHS);
2076 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002077
2078 return nullptr;
2079}
2080
Sanjay Patel12a41052016-08-18 17:37:26 +00002081/// Fold icmp (udiv X, Y), C.
2082Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp,
Sanjay Patelc9196c42016-08-22 21:24:29 +00002083 BinaryOperator *UDiv,
Sanjay Patel12a41052016-08-18 17:37:26 +00002084 const APInt *C) {
Sanjay Patelfa5ca2b2016-08-18 17:55:59 +00002085 const APInt *C2;
2086 if (!match(UDiv->getOperand(0), m_APInt(C2)))
2087 return nullptr;
2088
2089 assert(C2 != 0 && "udiv 0, X should have been simplified already.");
2090
2091 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2092 Value *Y = UDiv->getOperand(1);
2093 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) {
2094 assert(!C->isMaxValue() &&
2095 "icmp ugt X, UINT_MAX should have been simplified already.");
2096 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2097 ConstantInt::get(Y->getType(), C2->udiv(*C + 1)));
2098 }
2099
2100 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2101 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) {
2102 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2103 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2104 ConstantInt::get(Y->getType(), C2->udiv(*C)));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002105 }
2106
2107 return nullptr;
2108}
2109
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002110/// Fold icmp ({su}div X, Y), C.
2111Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp,
2112 BinaryOperator *Div,
2113 const APInt *C) {
Sanjay Patela7cb4772016-08-30 17:10:49 +00002114 // Fold: icmp pred ([us]div X, C2), C -> range test
Sanjay Patela3f4f082016-08-16 17:54:36 +00002115 // Fold this div into the comparison, producing a range check.
2116 // Determine, based on the divide type, what the range is being
2117 // checked. If there is an overflow on the low or high side, remember
2118 // it, otherwise compute the range [low, hi) bounding the new value.
2119 // See: InsertRangeTest above for the kinds of replacements possible.
Sanjay Patela7cb4772016-08-30 17:10:49 +00002120 const APInt *C2;
2121 if (!match(Div->getOperand(1), m_APInt(C2)))
Sanjay Patel16554142016-08-24 23:03:36 +00002122 return nullptr;
2123
Sanjay Patel16554142016-08-24 23:03:36 +00002124 // FIXME: If the operand types don't match the type of the divide
2125 // then don't attempt this transform. The code below doesn't have the
2126 // logic to deal with a signed divide and an unsigned compare (and
Sanjay Patela7cb4772016-08-30 17:10:49 +00002127 // vice versa). This is because (x /s C2) <s C produces different
2128 // results than (x /s C2) <u C or (x /u C2) <s C or even
2129 // (x /u C2) <u C. Simply casting the operands and result won't
Sanjay Patel16554142016-08-24 23:03:36 +00002130 // work. :( The if statement below tests that condition and bails
2131 // if it finds it.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002132 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2133 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
Sanjay Patel16554142016-08-24 23:03:36 +00002134 return nullptr;
Sanjay Patela7cb4772016-08-30 17:10:49 +00002135
Sanjay Pateleea2ef72016-09-05 23:38:22 +00002136 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2137 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2138 // division-by-constant cases should be present, we can not assert that they
2139 // have happened before we reach this icmp instruction.
2140 if (*C2 == 0 || *C2 == 1 || (DivIsSigned && C2->isAllOnesValue()))
2141 return nullptr;
Sanjay Patelb3714572016-08-30 17:31:34 +00002142
Sanjay Patel541aef42016-08-31 21:57:21 +00002143 // TODO: We could do all of the computations below using APInt.
2144 Constant *CmpRHS = cast<Constant>(Cmp.getOperand(1));
2145 Constant *DivRHS = cast<Constant>(Div->getOperand(1));
Sanjay Patelb3714572016-08-30 17:31:34 +00002146
Sanjay Patel541aef42016-08-31 21:57:21 +00002147 // Compute Prod = CmpRHS * DivRHS. We are essentially solving an equation of
2148 // form X / C2 = C. We solve for X by multiplying C2 (DivRHS) and C (CmpRHS).
2149 // By solving for X, we can turn this into a range check instead of computing
2150 // a divide.
2151 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Sanjay Patel16554142016-08-24 23:03:36 +00002152
Sanjay Patel541aef42016-08-31 21:57:21 +00002153 // Determine if the product overflows by seeing if the product is not equal to
2154 // the divide. Make sure we do the same kind of divide as in the LHS
2155 // instruction that we're folding.
2156 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS)
2157 : ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Sanjay Patel16554142016-08-24 23:03:36 +00002158
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002159 ICmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patel16554142016-08-24 23:03:36 +00002160
2161 // If the division is known to be exact, then there is no remainder from the
2162 // divide, so the covered range size is unit, otherwise it is the divisor.
Sanjay Patel541aef42016-08-31 21:57:21 +00002163 Constant *RangeSize =
2164 Div->isExact() ? ConstantInt::get(Div->getType(), 1) : DivRHS;
Sanjay Patel16554142016-08-24 23:03:36 +00002165
2166 // Figure out the interval that is being checked. For example, a comparison
2167 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2168 // Compute this interval based on the constants involved and the signedness of
2169 // the compare/divide. This computes a half-open interval, keeping track of
2170 // whether either value in the interval overflows. After analysis each
2171 // overflow variable is set to 0 if it's corresponding bound variable is valid
2172 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2173 int LoOverflow = 0, HiOverflow = 0;
2174 Constant *LoBound = nullptr, *HiBound = nullptr;
2175
2176 if (!DivIsSigned) { // udiv
2177 // e.g. X/5 op 3 --> [15, 20)
2178 LoBound = Prod;
2179 HiOverflow = LoOverflow = ProdOV;
2180 if (!HiOverflow) {
2181 // If this is not an exact divide, then many values in the range collapse
2182 // to the same result value.
Sanjay Pateld93c4c02016-09-15 18:22:25 +00002183 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
Sanjay Patel16554142016-08-24 23:03:36 +00002184 }
Sanjay Patel541aef42016-08-31 21:57:21 +00002185 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002186 if (*C == 0) { // (X / pos) op 0
Sanjay Patel16554142016-08-24 23:03:36 +00002187 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2188 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
2189 HiBound = RangeSize;
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002190 } else if (C->isStrictlyPositive()) { // (X / pos) op pos
Sanjay Patel16554142016-08-24 23:03:36 +00002191 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2192 HiOverflow = LoOverflow = ProdOV;
2193 if (!HiOverflow)
Sanjay Pateld93c4c02016-09-15 18:22:25 +00002194 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
Sanjay Patel16554142016-08-24 23:03:36 +00002195 } else { // (X / pos) op neg
2196 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2197 HiBound = AddOne(Prod);
2198 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2199 if (!LoOverflow) {
Sanjay Patel541aef42016-08-31 21:57:21 +00002200 Constant *DivNeg = ConstantExpr::getNeg(RangeSize);
Sanjay Pateld93c4c02016-09-15 18:22:25 +00002201 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Sanjay Patel16554142016-08-24 23:03:36 +00002202 }
2203 }
Sanjay Patel541aef42016-08-31 21:57:21 +00002204 } else if (C2->isNegative()) { // Divisor is < 0.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002205 if (Div->isExact())
Sanjay Patel541aef42016-08-31 21:57:21 +00002206 RangeSize = ConstantExpr::getNeg(RangeSize);
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002207 if (*C == 0) { // (X / neg) op 0
Sanjay Patel16554142016-08-24 23:03:36 +00002208 // e.g. X/-5 op 0 --> [-4, 5)
2209 LoBound = AddOne(RangeSize);
Sanjay Patel541aef42016-08-31 21:57:21 +00002210 HiBound = ConstantExpr::getNeg(RangeSize);
Sanjay Patel16554142016-08-24 23:03:36 +00002211 if (HiBound == DivRHS) { // -INTMIN = INTMIN
2212 HiOverflow = 1; // [INTMIN+1, overflow)
2213 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
2214 }
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002215 } else if (C->isStrictlyPositive()) { // (X / neg) op pos
Sanjay Patel16554142016-08-24 23:03:36 +00002216 // e.g. X/-5 op 3 --> [-19, -14)
2217 HiBound = AddOne(Prod);
2218 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2219 if (!LoOverflow)
Sanjay Pateld93c4c02016-09-15 18:22:25 +00002220 LoOverflow = addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Sanjay Patel16554142016-08-24 23:03:36 +00002221 } else { // (X / neg) op neg
2222 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2223 LoOverflow = HiOverflow = ProdOV;
2224 if (!HiOverflow)
Sanjay Pateld93c4c02016-09-15 18:22:25 +00002225 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
Sanjay Patel16554142016-08-24 23:03:36 +00002226 }
2227
2228 // Dividing by a negative swaps the condition. LT <-> GT
2229 Pred = ICmpInst::getSwappedPredicate(Pred);
2230 }
2231
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002232 Value *X = Div->getOperand(0);
Sanjay Patel16554142016-08-24 23:03:36 +00002233 switch (Pred) {
2234 default: llvm_unreachable("Unhandled icmp opcode!");
2235 case ICmpInst::ICMP_EQ:
2236 if (LoOverflow && HiOverflow)
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002237 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002238 if (HiOverflow)
2239 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2240 ICmpInst::ICMP_UGE, X, LoBound);
2241 if (LoOverflow)
2242 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2243 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel85d79742016-08-31 19:49:56 +00002244 return replaceInstUsesWith(
Sanjay Patel541aef42016-08-31 21:57:21 +00002245 Cmp, insertRangeTest(X, LoBound->getUniqueInteger(),
2246 HiBound->getUniqueInteger(), DivIsSigned, true));
Sanjay Patel16554142016-08-24 23:03:36 +00002247 case ICmpInst::ICMP_NE:
2248 if (LoOverflow && HiOverflow)
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002249 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002250 if (HiOverflow)
2251 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2252 ICmpInst::ICMP_ULT, X, LoBound);
2253 if (LoOverflow)
2254 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2255 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel541aef42016-08-31 21:57:21 +00002256 return replaceInstUsesWith(Cmp,
2257 insertRangeTest(X, LoBound->getUniqueInteger(),
2258 HiBound->getUniqueInteger(),
2259 DivIsSigned, false));
Sanjay Patel16554142016-08-24 23:03:36 +00002260 case ICmpInst::ICMP_ULT:
2261 case ICmpInst::ICMP_SLT:
2262 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002263 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002264 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002265 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002266 return new ICmpInst(Pred, X, LoBound);
2267 case ICmpInst::ICMP_UGT:
2268 case ICmpInst::ICMP_SGT:
2269 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002270 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002271 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002272 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002273 if (Pred == ICmpInst::ICMP_UGT)
2274 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
2275 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
2276 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002277
2278 return nullptr;
2279}
2280
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002281/// Fold icmp (sub X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002282Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp,
2283 BinaryOperator *Sub,
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002284 const APInt *C) {
Sanjay Patel886a5422016-09-15 18:05:17 +00002285 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2286 ICmpInst::Predicate Pred = Cmp.getPredicate();
2287
2288 // The following transforms are only worth it if the only user of the subtract
2289 // is the icmp.
2290 if (!Sub->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00002291 return nullptr;
2292
Sanjay Patel886a5422016-09-15 18:05:17 +00002293 if (Sub->hasNoSignedWrap()) {
2294 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2295 if (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())
2296 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
Sanjay Patela3f4f082016-08-16 17:54:36 +00002297
Sanjay Patel886a5422016-09-15 18:05:17 +00002298 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2299 if (Pred == ICmpInst::ICMP_SGT && *C == 0)
2300 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2301
2302 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2303 if (Pred == ICmpInst::ICMP_SLT && *C == 0)
2304 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2305
2306 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2307 if (Pred == ICmpInst::ICMP_SLT && *C == 1)
2308 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2309 }
2310
2311 const APInt *C2;
2312 if (!match(X, m_APInt(C2)))
2313 return nullptr;
2314
2315 // C2 - Y <u C -> (Y | (C - 1)) == C2
2316 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2317 if (Pred == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2318 (*C2 & (*C - 1)) == (*C - 1))
2319 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateOr(Y, *C - 1), X);
2320
2321 // C2 - Y >u C -> (Y | C) != C2
2322 // iff C2 & C == C and C + 1 is a power of 2
2323 if (Pred == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() && (*C2 & *C) == *C)
2324 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateOr(Y, *C), X);
Sanjay Patela3f4f082016-08-16 17:54:36 +00002325
2326 return nullptr;
2327}
2328
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002329/// Fold icmp (add X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002330Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp,
2331 BinaryOperator *Add,
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002332 const APInt *C) {
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002333 Value *Y = Add->getOperand(1);
2334 const APInt *C2;
2335 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002336 return nullptr;
2337
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002338 // Fold icmp pred (add X, C2), C.
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002339 Value *X = Add->getOperand(0);
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002340 Type *Ty = Add->getType();
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002341 auto CR =
2342 ConstantRange::makeExactICmpRegion(Cmp.getPredicate(), *C).subtract(*C2);
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002343 const APInt &Upper = CR.getUpper();
2344 const APInt &Lower = CR.getLower();
2345 if (Cmp.isSigned()) {
2346 if (Lower.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002347 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002348 if (Upper.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002349 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002350 } else {
2351 if (Lower.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002352 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002353 if (Upper.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002354 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002355 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002356
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002357 if (!Add->hasOneUse())
2358 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002359
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002360 // X+C <u C2 -> (X & -C2) == C
2361 // iff C & (C2-1) == 0
2362 // C2 is a power of 2
2363 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2364 (*C2 & (*C - 1)) == 0)
2365 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(X, -(*C)),
2366 ConstantExpr::getNeg(cast<Constant>(Y)));
2367
2368 // X+C >u C2 -> (X & ~C2) != C
2369 // iff C & C2 == 0
2370 // C2+1 is a power of 2
2371 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2372 (*C2 & *C) == 0)
2373 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(X, ~(*C)),
2374 ConstantExpr::getNeg(cast<Constant>(Y)));
2375
Sanjay Patela3f4f082016-08-16 17:54:36 +00002376 return nullptr;
2377}
2378
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002379/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
2380/// where X is some kind of instruction.
2381Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) {
Sanjay Patelc9196c42016-08-22 21:24:29 +00002382 const APInt *C;
2383 if (!match(Cmp.getOperand(1), m_APInt(C)))
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00002384 return nullptr;
2385
Sanjay Patelc9196c42016-08-22 21:24:29 +00002386 BinaryOperator *BO;
2387 if (match(Cmp.getOperand(0), m_BinOp(BO))) {
2388 switch (BO->getOpcode()) {
2389 case Instruction::Xor:
2390 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
2391 return I;
2392 break;
2393 case Instruction::And:
2394 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
2395 return I;
2396 break;
2397 case Instruction::Or:
2398 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
2399 return I;
2400 break;
2401 case Instruction::Mul:
2402 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
2403 return I;
2404 break;
2405 case Instruction::Shl:
2406 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
2407 return I;
2408 break;
2409 case Instruction::LShr:
2410 case Instruction::AShr:
2411 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
2412 return I;
2413 break;
2414 case Instruction::UDiv:
2415 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
2416 return I;
2417 LLVM_FALLTHROUGH;
2418 case Instruction::SDiv:
2419 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
2420 return I;
2421 break;
2422 case Instruction::Sub:
2423 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
2424 return I;
2425 break;
2426 case Instruction::Add:
2427 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
2428 return I;
2429 break;
2430 default:
2431 break;
2432 }
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002433 // TODO: These folds could be refactored to be part of the above calls.
2434 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
2435 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002436 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002437
Sanjay Patelc9196c42016-08-22 21:24:29 +00002438 Instruction *LHSI;
2439 if (match(Cmp.getOperand(0), m_Instruction(LHSI)) &&
2440 LHSI->getOpcode() == Instruction::Trunc)
2441 if (Instruction *I = foldICmpTruncConstant(Cmp, LHSI, C))
2442 return I;
2443
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002444 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, C))
2445 return I;
2446
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002447 return nullptr;
2448}
Jim Grosbach129c52a2011-09-30 18:09:53 +00002449
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002450/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
2451/// icmp eq/ne BO, C.
2452Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
2453 BinaryOperator *BO,
2454 const APInt *C) {
2455 // TODO: Some of these folds could work with arbitrary constants, but this
2456 // function is limited to scalar and vector splat constants.
2457 if (!Cmp.isEquality())
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002458 return nullptr;
2459
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002460 ICmpInst::Predicate Pred = Cmp.getPredicate();
2461 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
2462 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel51a767c2016-08-03 17:23:08 +00002463 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002464
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002465 switch (BO->getOpcode()) {
2466 case Instruction::SRem:
2467 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002468 if (*C == 0 && BO->hasOneUse()) {
Sanjay Patel2e9675f2016-08-03 19:48:40 +00002469 const APInt *BOC;
2470 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002471 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName());
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002472 return new ICmpInst(Pred, NewRem,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002473 Constant::getNullValue(BO->getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002474 }
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002475 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002476 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002477 case Instruction::Add: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002478 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
Sanjay Patel00a324e2016-08-03 22:08:44 +00002479 const APInt *BOC;
2480 if (match(BOp1, m_APInt(BOC))) {
2481 if (BO->hasOneUse()) {
2482 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002483 return new ICmpInst(Pred, BOp0, SubC);
Sanjay Patel00a324e2016-08-03 22:08:44 +00002484 }
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002485 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002486 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2487 // efficiently invertible, or if the add has just this one use.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002488 if (Value *NegVal = dyn_castNegVal(BOp1))
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002489 return new ICmpInst(Pred, BOp0, NegVal);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002490 if (Value *NegVal = dyn_castNegVal(BOp0))
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002491 return new ICmpInst(Pred, NegVal, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002492 if (BO->hasOneUse()) {
2493 Value *Neg = Builder->CreateNeg(BOp1);
2494 Neg->takeName(BO);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002495 return new ICmpInst(Pred, BOp0, Neg);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002496 }
2497 }
2498 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002499 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002500 case Instruction::Xor:
2501 if (BO->hasOneUse()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002502 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002503 // For the xor case, we can xor two constants together, eliminating
2504 // the explicit xor.
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002505 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
2506 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002507 // Replace ((xor A, B) != 0) with (A != B)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002508 return new ICmpInst(Pred, BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002509 }
2510 }
2511 break;
2512 case Instruction::Sub:
2513 if (BO->hasOneUse()) {
Sanjay Patel9d591d12016-08-04 15:19:25 +00002514 const APInt *BOC;
2515 if (match(BOp0, m_APInt(BOC))) {
Sanjay Patel362ff5c2016-09-15 17:01:17 +00002516 // Replace ((sub BOC, B) != C) with (B != BOC-C).
Sanjay Patel9d591d12016-08-04 15:19:25 +00002517 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002518 return new ICmpInst(Pred, BOp1, SubC);
2519 } else if (*C == 0) {
Sanjay Patel362ff5c2016-09-15 17:01:17 +00002520 // Replace ((sub A, B) != 0) with (A != B).
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002521 return new ICmpInst(Pred, BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002522 }
2523 }
2524 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002525 case Instruction::Or: {
2526 const APInt *BOC;
2527 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002528 // Comparing if all bits outside of a constant mask are set?
2529 // Replace (X | C) == -1 with (X & ~C) == ~C.
2530 // This removes the -1 constant.
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002531 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2532 Value *And = Builder->CreateAnd(BOp0, NotBOC);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002533 return new ICmpInst(Pred, And, NotBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002534 }
2535 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002536 }
Sanjay Pateld938e882016-08-04 20:05:02 +00002537 case Instruction::And: {
2538 const APInt *BOC;
2539 if (match(BOp1, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002540 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002541 if (C == BOC && C->isPowerOf2())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002542 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
Sanjay Patelab50a932016-08-02 22:38:33 +00002543 BO, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002544
2545 // Don't perform the following transforms if the AND has multiple uses
2546 if (!BO->hasOneUse())
2547 break;
2548
2549 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Sanjay Pateld938e882016-08-04 20:05:02 +00002550 if (BOC->isSignBit()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002551 Constant *Zero = Constant::getNullValue(BOp0->getType());
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002552 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
2553 return new ICmpInst(NewPred, BOp0, Zero);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002554 }
2555
2556 // ((X & ~7) == 0) --> X < 8
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002557 if (*C == 0 && (~(*BOC) + 1).isPowerOf2()) {
Sanjay Pateld938e882016-08-04 20:05:02 +00002558 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1));
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002559 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
2560 return new ICmpInst(NewPred, BOp0, NegBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002561 }
2562 }
2563 break;
Sanjay Pateld938e882016-08-04 20:05:02 +00002564 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002565 case Instruction::Mul:
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002566 if (*C == 0 && BO->hasNoSignedWrap()) {
Sanjay Patel3bade132016-08-04 22:19:27 +00002567 const APInt *BOC;
2568 if (match(BOp1, m_APInt(BOC)) && *BOC != 0) {
2569 // The trivial case (mul X, 0) is handled by InstSimplify.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002570 // General case : (mul X, C) != 0 iff X != 0
2571 // (mul X, C) == 0 iff X == 0
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002572 return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002573 }
2574 }
2575 break;
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002576 case Instruction::UDiv:
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002577 if (*C == 0) {
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002578 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002579 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
2580 return new ICmpInst(NewPred, BOp1, BOp0);
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002581 }
2582 break;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002583 default:
2584 break;
2585 }
2586 return nullptr;
2587}
2588
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002589/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
2590Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
2591 const APInt *C) {
2592 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0));
2593 if (!II || !Cmp.isEquality())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002594 return nullptr;
2595
2596 // Handle icmp {eq|ne} <intrinsic>, intcst.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002597 switch (II->getIntrinsicID()) {
2598 case Intrinsic::bswap:
2599 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002600 Cmp.setOperand(0, II->getArgOperand(0));
2601 Cmp.setOperand(1, Builder->getInt(C->byteSwap()));
2602 return &Cmp;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002603 case Intrinsic::ctlz:
2604 case Intrinsic::cttz:
Amaury Sechet6bea6742016-08-04 05:27:20 +00002605 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002606 if (*C == C->getBitWidth()) {
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002607 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002608 Cmp.setOperand(0, II->getArgOperand(0));
2609 Cmp.setOperand(1, ConstantInt::getNullValue(II->getType()));
2610 return &Cmp;
Chris Lattner2188e402010-01-04 07:37:31 +00002611 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002612 break;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002613 case Intrinsic::ctpop: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002614 // popcount(A) == 0 -> A == 0 and likewise for !=
Amaury Sechet6bea6742016-08-04 05:27:20 +00002615 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002616 bool IsZero = *C == 0;
2617 if (IsZero || *C == C->getBitWidth()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002618 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002619 Cmp.setOperand(0, II->getArgOperand(0));
2620 auto *NewOp = IsZero ? Constant::getNullValue(II->getType())
2621 : Constant::getAllOnesValue(II->getType());
2622 Cmp.setOperand(1, NewOp);
2623 return &Cmp;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002624 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002625 break;
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002626 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002627 default:
2628 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002629 }
Craig Topperf40110f2014-04-25 05:29:35 +00002630 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002631}
2632
Sanjay Patel10494b22016-09-16 16:10:22 +00002633/// Handle icmp with constant (but not simple integer constant) RHS.
2634Instruction *InstCombiner::foldICmpInstWithConstantNotInt(ICmpInst &I) {
2635 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2636 Constant *RHSC = dyn_cast<Constant>(Op1);
2637 Instruction *LHSI = dyn_cast<Instruction>(Op0);
2638 if (!RHSC || !LHSI)
2639 return nullptr;
2640
2641 switch (LHSI->getOpcode()) {
2642 case Instruction::GetElementPtr:
2643 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2644 if (RHSC->isNullValue() &&
2645 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2646 return new ICmpInst(
2647 I.getPredicate(), LHSI->getOperand(0),
2648 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2649 break;
2650 case Instruction::PHI:
2651 // Only fold icmp into the PHI if the phi and icmp are in the same
2652 // block. If in the same block, we're encouraging jump threading. If
2653 // not, we are just pessimizing the code by making an i1 phi.
2654 if (LHSI->getParent() == I.getParent())
2655 if (Instruction *NV = FoldOpIntoPhi(I))
2656 return NV;
2657 break;
2658 case Instruction::Select: {
2659 // If either operand of the select is a constant, we can fold the
2660 // comparison into the select arms, which will cause one to be
2661 // constant folded and the select turned into a bitwise or.
2662 Value *Op1 = nullptr, *Op2 = nullptr;
2663 ConstantInt *CI = nullptr;
2664 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2665 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2666 CI = dyn_cast<ConstantInt>(Op1);
2667 }
2668 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2669 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2670 CI = dyn_cast<ConstantInt>(Op2);
2671 }
2672
2673 // We only want to perform this transformation if it will not lead to
2674 // additional code. This is true if either both sides of the select
2675 // fold to a constant (in which case the icmp is replaced with a select
2676 // which will usually simplify) or this is the only user of the
2677 // select (in which case we are trading a select+icmp for a simpler
2678 // select+icmp) or all uses of the select can be replaced based on
2679 // dominance information ("Global cases").
2680 bool Transform = false;
2681 if (Op1 && Op2)
2682 Transform = true;
2683 else if (Op1 || Op2) {
2684 // Local case
2685 if (LHSI->hasOneUse())
2686 Transform = true;
2687 // Global cases
2688 else if (CI && !CI->isZero())
2689 // When Op1 is constant try replacing select with second operand.
2690 // Otherwise Op2 is constant and try replacing select with first
2691 // operand.
2692 Transform =
2693 replacedSelectWithOperand(cast<SelectInst>(LHSI), &I, Op1 ? 2 : 1);
2694 }
2695 if (Transform) {
2696 if (!Op1)
2697 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1), RHSC,
2698 I.getName());
2699 if (!Op2)
2700 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2), RHSC,
2701 I.getName());
2702 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2703 }
2704 break;
2705 }
2706 case Instruction::IntToPtr:
2707 // icmp pred inttoptr(X), null -> icmp pred X, 0
2708 if (RHSC->isNullValue() &&
2709 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
2710 return new ICmpInst(
2711 I.getPredicate(), LHSI->getOperand(0),
2712 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2713 break;
2714
2715 case Instruction::Load:
2716 // Try to optimize things like "A[i] > 4" to index computations.
2717 if (GetElementPtrInst *GEP =
2718 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2719 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2720 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2721 !cast<LoadInst>(LHSI)->isVolatile())
2722 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
2723 return Res;
2724 }
2725 break;
2726 }
2727
2728 return nullptr;
2729}
2730
2731/// Try to fold icmp (binop), X or icmp X, (binop).
2732Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) {
2733 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2734
2735 // Special logic for binary operators.
2736 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2737 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2738 if (!BO0 && !BO1)
2739 return nullptr;
2740
2741 CmpInst::Predicate Pred = I.getPredicate();
2742 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2743 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2744 NoOp0WrapProblem =
2745 ICmpInst::isEquality(Pred) ||
2746 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2747 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2748 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2749 NoOp1WrapProblem =
2750 ICmpInst::isEquality(Pred) ||
2751 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2752 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2753
2754 // Analyze the case when either Op0 or Op1 is an add instruction.
2755 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2756 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2757 if (BO0 && BO0->getOpcode() == Instruction::Add) {
2758 A = BO0->getOperand(0);
2759 B = BO0->getOperand(1);
2760 }
2761 if (BO1 && BO1->getOpcode() == Instruction::Add) {
2762 C = BO1->getOperand(0);
2763 D = BO1->getOperand(1);
2764 }
2765
2766 // icmp (X+cst) < 0 --> X < -cst
2767 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
2768 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
2769 if (!RHSC->isMinValue(/*isSigned=*/true))
2770 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
2771
2772 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2773 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2774 return new ICmpInst(Pred, A == Op1 ? B : A,
2775 Constant::getNullValue(Op1->getType()));
2776
2777 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2778 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2779 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2780 C == Op0 ? D : C);
2781
2782 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2783 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
2784 NoOp1WrapProblem &&
2785 // Try not to increase register pressure.
2786 BO0->hasOneUse() && BO1->hasOneUse()) {
2787 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2788 Value *Y, *Z;
2789 if (A == C) {
2790 // C + B == C + D -> B == D
2791 Y = B;
2792 Z = D;
2793 } else if (A == D) {
2794 // D + B == C + D -> B == C
2795 Y = B;
2796 Z = C;
2797 } else if (B == C) {
2798 // A + C == C + D -> A == D
2799 Y = A;
2800 Z = D;
2801 } else {
2802 assert(B == D);
2803 // A + D == C + D -> A == C
2804 Y = A;
2805 Z = C;
2806 }
2807 return new ICmpInst(Pred, Y, Z);
2808 }
2809
2810 // icmp slt (X + -1), Y -> icmp sle X, Y
2811 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2812 match(B, m_AllOnes()))
2813 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2814
2815 // icmp sge (X + -1), Y -> icmp sgt X, Y
2816 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2817 match(B, m_AllOnes()))
2818 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2819
2820 // icmp sle (X + 1), Y -> icmp slt X, Y
2821 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
2822 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2823
2824 // icmp sgt (X + 1), Y -> icmp sge X, Y
2825 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
2826 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2827
2828 // icmp sgt X, (Y + -1) -> icmp sge X, Y
2829 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
2830 match(D, m_AllOnes()))
2831 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
2832
2833 // icmp sle X, (Y + -1) -> icmp slt X, Y
2834 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
2835 match(D, m_AllOnes()))
2836 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
2837
2838 // icmp sge X, (Y + 1) -> icmp sgt X, Y
2839 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
2840 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
2841
2842 // icmp slt X, (Y + 1) -> icmp sle X, Y
2843 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
2844 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
2845
2846 // if C1 has greater magnitude than C2:
2847 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2848 // s.t. C3 = C1 - C2
2849 //
2850 // if C2 has greater magnitude than C1:
2851 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2852 // s.t. C3 = C2 - C1
2853 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2854 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2855 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2856 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2857 const APInt &AP1 = C1->getValue();
2858 const APInt &AP2 = C2->getValue();
2859 if (AP1.isNegative() == AP2.isNegative()) {
2860 APInt AP1Abs = C1->getValue().abs();
2861 APInt AP2Abs = C2->getValue().abs();
2862 if (AP1Abs.uge(AP2Abs)) {
2863 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2864 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2865 return new ICmpInst(Pred, NewAdd, C);
2866 } else {
2867 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2868 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2869 return new ICmpInst(Pred, A, NewAdd);
2870 }
2871 }
2872 }
2873
2874 // Analyze the case when either Op0 or Op1 is a sub instruction.
2875 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2876 A = nullptr;
2877 B = nullptr;
2878 C = nullptr;
2879 D = nullptr;
2880 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
2881 A = BO0->getOperand(0);
2882 B = BO0->getOperand(1);
2883 }
2884 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
2885 C = BO1->getOperand(0);
2886 D = BO1->getOperand(1);
2887 }
2888
2889 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2890 if (A == Op1 && NoOp0WrapProblem)
2891 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2892
2893 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2894 if (C == Op0 && NoOp1WrapProblem)
2895 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2896
2897 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2898 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2899 // Try not to increase register pressure.
2900 BO0->hasOneUse() && BO1->hasOneUse())
2901 return new ICmpInst(Pred, A, C);
2902
2903 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2904 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2905 // Try not to increase register pressure.
2906 BO0->hasOneUse() && BO1->hasOneUse())
2907 return new ICmpInst(Pred, D, B);
2908
2909 // icmp (0-X) < cst --> x > -cst
2910 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
2911 Value *X;
2912 if (match(BO0, m_Neg(m_Value(X))))
2913 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2914 if (!RHSC->isMinValue(/*isSigned=*/true))
2915 return new ICmpInst(I.getSwappedPredicate(), X,
2916 ConstantExpr::getNeg(RHSC));
2917 }
2918
2919 BinaryOperator *SRem = nullptr;
2920 // icmp (srem X, Y), Y
2921 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
2922 SRem = BO0;
2923 // icmp Y, (srem X, Y)
2924 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2925 Op0 == BO1->getOperand(1))
2926 SRem = BO1;
2927 if (SRem) {
2928 // We don't check hasOneUse to avoid increasing register pressure because
2929 // the value we use is the same value this instruction was already using.
2930 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2931 default:
2932 break;
2933 case ICmpInst::ICMP_EQ:
2934 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2935 case ICmpInst::ICMP_NE:
2936 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2937 case ICmpInst::ICMP_SGT:
2938 case ICmpInst::ICMP_SGE:
2939 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2940 Constant::getAllOnesValue(SRem->getType()));
2941 case ICmpInst::ICMP_SLT:
2942 case ICmpInst::ICMP_SLE:
2943 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2944 Constant::getNullValue(SRem->getType()));
2945 }
2946 }
2947
2948 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
2949 BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
2950 switch (BO0->getOpcode()) {
2951 default:
2952 break;
2953 case Instruction::Add:
2954 case Instruction::Sub:
2955 case Instruction::Xor:
2956 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2957 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2958 BO1->getOperand(0));
2959 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2960 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2961 if (CI->getValue().isSignBit()) {
2962 ICmpInst::Predicate Pred =
2963 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
2964 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
2965 }
2966
2967 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
2968 ICmpInst::Predicate Pred =
2969 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate();
2970 Pred = I.getSwappedPredicate(Pred);
2971 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
2972 }
2973 }
2974 break;
2975 case Instruction::Mul:
2976 if (!I.isEquality())
2977 break;
2978
2979 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2980 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2981 // Mask = -1 >> count-trailing-zeros(Cst).
2982 if (!CI->isZero() && !CI->isOne()) {
2983 const APInt &AP = CI->getValue();
2984 ConstantInt *Mask = ConstantInt::get(
2985 I.getContext(),
2986 APInt::getLowBitsSet(AP.getBitWidth(),
2987 AP.getBitWidth() - AP.countTrailingZeros()));
2988 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2989 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2990 return new ICmpInst(I.getPredicate(), And1, And2);
2991 }
2992 }
2993 break;
2994 case Instruction::UDiv:
2995 case Instruction::LShr:
2996 if (I.isSigned())
2997 break;
2998 LLVM_FALLTHROUGH;
2999 case Instruction::SDiv:
3000 case Instruction::AShr:
3001 if (!BO0->isExact() || !BO1->isExact())
3002 break;
3003 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3004 BO1->getOperand(0));
3005 case Instruction::Shl: {
3006 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3007 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3008 if (!NUW && !NSW)
3009 break;
3010 if (!NSW && I.isSigned())
3011 break;
3012 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3013 BO1->getOperand(0));
3014 }
3015 }
3016 }
3017
3018 if (BO0) {
3019 // Transform A & (L - 1) `ult` L --> L != 0
3020 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
3021 auto BitwiseAnd =
3022 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
3023
3024 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
3025 auto *Zero = Constant::getNullValue(BO0->getType());
3026 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
3027 }
3028 }
3029
3030 return nullptr;
3031}
3032
3033Instruction *InstCombiner::foldICmpEquality(ICmpInst &I) {
3034 if (!I.isEquality())
3035 return nullptr;
3036
3037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3038 Value *A, *B, *C, *D;
3039 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3040 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
3041 Value *OtherVal = A == Op1 ? B : A;
3042 return new ICmpInst(I.getPredicate(), OtherVal,
3043 Constant::getNullValue(A->getType()));
3044 }
3045
3046 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3047 // A^c1 == C^c2 --> A == C^(c1^c2)
3048 ConstantInt *C1, *C2;
3049 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
3050 Op1->hasOneUse()) {
3051 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
3052 Value *Xor = Builder->CreateXor(C, NC);
3053 return new ICmpInst(I.getPredicate(), A, Xor);
3054 }
3055
3056 // A^B == A^D -> B == D
3057 if (A == C)
3058 return new ICmpInst(I.getPredicate(), B, D);
3059 if (A == D)
3060 return new ICmpInst(I.getPredicate(), B, C);
3061 if (B == C)
3062 return new ICmpInst(I.getPredicate(), A, D);
3063 if (B == D)
3064 return new ICmpInst(I.getPredicate(), A, C);
3065 }
3066 }
3067
3068 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
3069 // A == (A^B) -> B == 0
3070 Value *OtherVal = A == Op0 ? B : A;
3071 return new ICmpInst(I.getPredicate(), OtherVal,
3072 Constant::getNullValue(A->getType()));
3073 }
3074
3075 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
3076 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
3077 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
3078 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
3079
3080 if (A == C) {
3081 X = B;
3082 Y = D;
3083 Z = A;
3084 } else if (A == D) {
3085 X = B;
3086 Y = C;
3087 Z = A;
3088 } else if (B == C) {
3089 X = A;
3090 Y = D;
3091 Z = B;
3092 } else if (B == D) {
3093 X = A;
3094 Y = C;
3095 Z = B;
3096 }
3097
3098 if (X) { // Build (X^Y) & Z
3099 Op1 = Builder->CreateXor(X, Y);
3100 Op1 = Builder->CreateAnd(Op1, Z);
3101 I.setOperand(0, Op1);
3102 I.setOperand(1, Constant::getNullValue(Op1->getType()));
3103 return &I;
3104 }
3105 }
3106
3107 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
3108 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
3109 ConstantInt *Cst1;
3110 if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) &&
3111 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3112 (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3113 match(Op1, m_ZExt(m_Value(A))))) {
3114 APInt Pow2 = Cst1->getValue() + 1;
3115 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3116 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3117 return new ICmpInst(I.getPredicate(), A,
3118 Builder->CreateTrunc(B, A->getType()));
3119 }
3120
3121 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
3122 // For lshr and ashr pairs.
3123 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3124 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
3125 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3126 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
3127 unsigned TypeBits = Cst1->getBitWidth();
3128 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3129 if (ShAmt < TypeBits && ShAmt != 0) {
3130 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
3131 ? ICmpInst::ICMP_UGE
3132 : ICmpInst::ICMP_ULT;
3133 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3134 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
3135 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
3136 }
3137 }
3138
3139 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
3140 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
3141 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
3142 unsigned TypeBits = Cst1->getBitWidth();
3143 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3144 if (ShAmt < TypeBits && ShAmt != 0) {
3145 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3146 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
3147 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
3148 I.getName() + ".mask");
3149 return new ICmpInst(I.getPredicate(), And,
3150 Constant::getNullValue(Cst1->getType()));
3151 }
3152 }
3153
3154 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
3155 // "icmp (and X, mask), cst"
3156 uint64_t ShAmt = 0;
3157 if (Op0->hasOneUse() &&
3158 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
3159 match(Op1, m_ConstantInt(Cst1)) &&
3160 // Only do this when A has multiple uses. This is most important to do
3161 // when it exposes other optimizations.
3162 !A->hasOneUse()) {
3163 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
3164
3165 if (ShAmt < ASize) {
3166 APInt MaskV =
3167 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3168 MaskV <<= ShAmt;
3169
3170 APInt CmpV = Cst1->getValue().zext(ASize);
3171 CmpV <<= ShAmt;
3172
3173 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3174 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3175 }
3176 }
3177
3178 return nullptr;
3179}
3180
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003181/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
3182/// far.
Sanjay Patel43395062016-07-21 18:07:40 +00003183Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003184 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00003185 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003186 Type *SrcTy = LHSCIOp->getType();
3187 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003188 Value *RHSCIOp;
3189
Jim Grosbach129c52a2011-09-30 18:09:53 +00003190 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00003191 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003192 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
3193 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00003194 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003195 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00003196 Value *RHSCIOp = RHSC->getOperand(0);
3197 if (RHSCIOp->getType()->getPointerAddressSpace() ==
3198 LHSCIOp->getType()->getPointerAddressSpace()) {
3199 RHSOp = RHSC->getOperand(0);
3200 // If the pointer types don't match, insert a bitcast.
3201 if (LHSCIOp->getType() != RHSOp->getType())
3202 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
3203 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003204 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003205 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003206 }
Chris Lattner2188e402010-01-04 07:37:31 +00003207
3208 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003209 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003210 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003211
Chris Lattner2188e402010-01-04 07:37:31 +00003212 // The code below only handles extension cast instructions, so far.
3213 // Enforce this.
3214 if (LHSCI->getOpcode() != Instruction::ZExt &&
3215 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00003216 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003217
3218 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003219 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00003220
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003221 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003222 // Not an extension from the same type?
3223 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003224 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00003225 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003226
Chris Lattner2188e402010-01-04 07:37:31 +00003227 // If the signedness of the two casts doesn't agree (i.e. one is a sext
3228 // and the other is a zext), then we can't handle this.
3229 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00003230 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003231
3232 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003233 if (ICmp.isEquality())
3234 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003235
3236 // A signed comparison of sign extended values simplifies into a
3237 // signed comparison.
3238 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003239 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003240
3241 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003242 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00003243 }
3244
Sanjay Patel4c204232016-06-04 20:39:22 +00003245 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003246 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
3247 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00003248 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003249
3250 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00003251 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003252 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00003253 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00003254
3255 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003256 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00003257 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003258 if (ICmp.isEquality())
3259 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00003260
3261 // A signed comparison of sign extended values simplifies into a
3262 // signed comparison.
3263 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003264 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00003265
3266 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003267 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00003268 }
3269
Sanjay Patel6a333c32016-06-06 16:56:57 +00003270 // The re-extended constant changed, partly changed (in the case of a vector),
3271 // or could not be determined to be equal (in the case of a constant
3272 // expression), so the constant cannot be represented in the shorter type.
3273 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003274 // All the cases that fold to true or false will have already been handled
3275 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00003276
Sanjay Patel6a333c32016-06-06 16:56:57 +00003277 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00003278 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003279
3280 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
3281 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003282
3283 // We're performing an unsigned comp with a sign extended value.
3284 // This is true if the input is >= 0. [aka >s -1]
3285 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003286 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00003287
3288 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003289 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
3290 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00003291
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00003292 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00003293 return BinaryOperator::CreateNot(Result);
3294}
3295
Sanjoy Dasb0984472015-04-08 04:27:22 +00003296bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
3297 Value *RHS, Instruction &OrigI,
3298 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00003299 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
3300 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003301
3302 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
3303 Result = OpResult;
3304 Overflow = OverflowVal;
3305 if (ReuseName)
3306 Result->takeName(&OrigI);
3307 return true;
3308 };
3309
Sanjoy Das6f5dca72015-08-28 19:09:31 +00003310 // If the overflow check was an add followed by a compare, the insertion point
3311 // may be pointing to the compare. We want to insert the new instructions
3312 // before the add in case there are uses of the add between the add and the
3313 // compare.
3314 Builder->SetInsertPoint(&OrigI);
3315
Sanjoy Dasb0984472015-04-08 04:27:22 +00003316 switch (OCF) {
3317 case OCF_INVALID:
3318 llvm_unreachable("bad overflow check kind!");
3319
3320 case OCF_UNSIGNED_ADD: {
3321 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
3322 if (OR == OverflowResult::NeverOverflows)
3323 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
3324 true);
3325
3326 if (OR == OverflowResult::AlwaysOverflows)
3327 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003328
3329 // Fall through uadd into sadd
3330 LLVM_FALLTHROUGH;
Sanjoy Dasb0984472015-04-08 04:27:22 +00003331 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00003332 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00003333 // X + 0 -> {X, false}
3334 if (match(RHS, m_Zero()))
3335 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003336
3337 // We can strength reduce this signed add into a regular add if we can prove
3338 // that it will never overflow.
3339 if (OCF == OCF_SIGNED_ADD)
3340 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
3341 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
3342 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00003343 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00003344 }
3345
3346 case OCF_UNSIGNED_SUB:
3347 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00003348 // X - 0 -> {X, false}
3349 if (match(RHS, m_Zero()))
3350 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003351
3352 if (OCF == OCF_SIGNED_SUB) {
3353 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
3354 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
3355 true);
3356 } else {
3357 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
3358 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
3359 true);
3360 }
3361 break;
3362 }
3363
3364 case OCF_UNSIGNED_MUL: {
3365 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
3366 if (OR == OverflowResult::NeverOverflows)
3367 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
3368 true);
3369 if (OR == OverflowResult::AlwaysOverflows)
3370 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003371 LLVM_FALLTHROUGH;
3372 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00003373 case OCF_SIGNED_MUL:
3374 // X * undef -> undef
3375 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00003376 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003377
David Majnemer27e89ba2015-05-21 23:04:21 +00003378 // X * 0 -> {0, false}
3379 if (match(RHS, m_Zero()))
3380 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003381
David Majnemer27e89ba2015-05-21 23:04:21 +00003382 // X * 1 -> {X, false}
3383 if (match(RHS, m_One()))
3384 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00003385
3386 if (OCF == OCF_SIGNED_MUL)
3387 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
3388 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
3389 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00003390 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00003391 }
3392
3393 return false;
3394}
3395
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003396/// \brief Recognize and process idiom involving test for multiplication
3397/// overflow.
3398///
3399/// The caller has matched a pattern of the form:
3400/// I = cmp u (mul(zext A, zext B), V
3401/// The function checks if this is a test for overflow and if so replaces
3402/// multiplication with call to 'mul.with.overflow' intrinsic.
3403///
3404/// \param I Compare instruction.
3405/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
3406/// the compare instruction. Must be of integer type.
3407/// \param OtherVal The other argument of compare instruction.
3408/// \returns Instruction which must replace the compare instruction, NULL if no
3409/// replacement required.
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003410static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003411 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00003412 // Don't bother doing this transformation for pointers, don't do it for
3413 // vectors.
3414 if (!isa<IntegerType>(MulVal->getType()))
3415 return nullptr;
3416
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003417 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
3418 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00003419 auto *MulInstr = dyn_cast<Instruction>(MulVal);
3420 if (!MulInstr)
3421 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003422 assert(MulInstr->getOpcode() == Instruction::Mul);
3423
David Majnemer634ca232014-11-01 23:46:05 +00003424 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
3425 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003426 assert(LHS->getOpcode() == Instruction::ZExt);
3427 assert(RHS->getOpcode() == Instruction::ZExt);
3428 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
3429
3430 // Calculate type and width of the result produced by mul.with.overflow.
3431 Type *TyA = A->getType(), *TyB = B->getType();
3432 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
3433 WidthB = TyB->getPrimitiveSizeInBits();
3434 unsigned MulWidth;
3435 Type *MulType;
3436 if (WidthB > WidthA) {
3437 MulWidth = WidthB;
3438 MulType = TyB;
3439 } else {
3440 MulWidth = WidthA;
3441 MulType = TyA;
3442 }
3443
3444 // In order to replace the original mul with a narrower mul.with.overflow,
3445 // all uses must ignore upper bits of the product. The number of used low
3446 // bits must be not greater than the width of mul.with.overflow.
3447 if (MulVal->hasNUsesOrMore(2))
3448 for (User *U : MulVal->users()) {
3449 if (U == &I)
3450 continue;
3451 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
3452 // Check if truncation ignores bits above MulWidth.
3453 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
3454 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00003455 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003456 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
3457 // Check if AND ignores bits above MulWidth.
3458 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00003459 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003460 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3461 const APInt &CVal = CI->getValue();
3462 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00003463 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003464 }
3465 } else {
3466 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00003467 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003468 }
3469 }
3470
3471 // Recognize patterns
3472 switch (I.getPredicate()) {
3473 case ICmpInst::ICMP_EQ:
3474 case ICmpInst::ICMP_NE:
3475 // Recognize pattern:
3476 // mulval = mul(zext A, zext B)
3477 // cmp eq/neq mulval, zext trunc mulval
3478 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
3479 if (Zext->hasOneUse()) {
3480 Value *ZextArg = Zext->getOperand(0);
3481 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
3482 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
3483 break; //Recognized
3484 }
3485
3486 // Recognize pattern:
3487 // mulval = mul(zext A, zext B)
3488 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
3489 ConstantInt *CI;
3490 Value *ValToMask;
3491 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
3492 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00003493 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003494 const APInt &CVal = CI->getValue() + 1;
3495 if (CVal.isPowerOf2()) {
3496 unsigned MaskWidth = CVal.logBase2();
3497 if (MaskWidth == MulWidth)
3498 break; // Recognized
3499 }
3500 }
Craig Topperf40110f2014-04-25 05:29:35 +00003501 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003502
3503 case ICmpInst::ICMP_UGT:
3504 // Recognize pattern:
3505 // mulval = mul(zext A, zext B)
3506 // cmp ugt mulval, max
3507 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3508 APInt MaxVal = APInt::getMaxValue(MulWidth);
3509 MaxVal = MaxVal.zext(CI->getBitWidth());
3510 if (MaxVal.eq(CI->getValue()))
3511 break; // Recognized
3512 }
Craig Topperf40110f2014-04-25 05:29:35 +00003513 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003514
3515 case ICmpInst::ICMP_UGE:
3516 // Recognize pattern:
3517 // mulval = mul(zext A, zext B)
3518 // cmp uge mulval, max+1
3519 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3520 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
3521 if (MaxVal.eq(CI->getValue()))
3522 break; // Recognized
3523 }
Craig Topperf40110f2014-04-25 05:29:35 +00003524 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003525
3526 case ICmpInst::ICMP_ULE:
3527 // Recognize pattern:
3528 // mulval = mul(zext A, zext B)
3529 // cmp ule mulval, max
3530 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3531 APInt MaxVal = APInt::getMaxValue(MulWidth);
3532 MaxVal = MaxVal.zext(CI->getBitWidth());
3533 if (MaxVal.eq(CI->getValue()))
3534 break; // Recognized
3535 }
Craig Topperf40110f2014-04-25 05:29:35 +00003536 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003537
3538 case ICmpInst::ICMP_ULT:
3539 // Recognize pattern:
3540 // mulval = mul(zext A, zext B)
3541 // cmp ule mulval, max + 1
3542 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00003543 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003544 if (MaxVal.eq(CI->getValue()))
3545 break; // Recognized
3546 }
Craig Topperf40110f2014-04-25 05:29:35 +00003547 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003548
3549 default:
Craig Topperf40110f2014-04-25 05:29:35 +00003550 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003551 }
3552
3553 InstCombiner::BuilderTy *Builder = IC.Builder;
3554 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003555
3556 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
3557 Value *MulA = A, *MulB = B;
3558 if (WidthA < MulWidth)
3559 MulA = Builder->CreateZExt(A, MulType);
3560 if (WidthB < MulWidth)
3561 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00003562 Value *F = Intrinsic::getDeclaration(I.getModule(),
3563 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00003564 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003565 IC.Worklist.Add(MulInstr);
3566
3567 // If there are uses of mul result other than the comparison, we know that
3568 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00003569 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003570 if (MulVal->hasNUsesOrMore(2)) {
3571 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
3572 for (User *U : MulVal->users()) {
3573 if (U == &I || U == OtherVal)
3574 continue;
3575 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
3576 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00003577 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003578 else
3579 TI->setOperand(0, Mul);
3580 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
3581 assert(BO->getOpcode() == Instruction::And);
3582 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
3583 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
3584 APInt ShortMask = CI->getValue().trunc(MulWidth);
3585 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
3586 Instruction *Zext =
3587 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
3588 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00003589 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003590 } else {
3591 llvm_unreachable("Unexpected Binary operation");
3592 }
3593 IC.Worklist.Add(cast<Instruction>(U));
3594 }
3595 }
3596 if (isa<Instruction>(OtherVal))
3597 IC.Worklist.Add(cast<Instruction>(OtherVal));
3598
3599 // The original icmp gets replaced with the overflow value, maybe inverted
3600 // depending on predicate.
3601 bool Inverse = false;
3602 switch (I.getPredicate()) {
3603 case ICmpInst::ICMP_NE:
3604 break;
3605 case ICmpInst::ICMP_EQ:
3606 Inverse = true;
3607 break;
3608 case ICmpInst::ICMP_UGT:
3609 case ICmpInst::ICMP_UGE:
3610 if (I.getOperand(0) == MulVal)
3611 break;
3612 Inverse = true;
3613 break;
3614 case ICmpInst::ICMP_ULT:
3615 case ICmpInst::ICMP_ULE:
3616 if (I.getOperand(1) == MulVal)
3617 break;
3618 Inverse = true;
3619 break;
3620 default:
3621 llvm_unreachable("Unexpected predicate");
3622 }
3623 if (Inverse) {
3624 Value *Res = Builder->CreateExtractValue(Call, 1);
3625 return BinaryOperator::CreateNot(Res);
3626 }
3627
3628 return ExtractValueInst::Create(Call, 1);
3629}
3630
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003631/// When performing a comparison against a constant, it is possible that not all
3632/// the bits in the LHS are demanded. This helper method computes the mask that
3633/// IS demanded.
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003634static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth,
3635 bool isSignCheck) {
Owen Andersond490c2d2011-01-11 00:36:45 +00003636 if (isSignCheck)
3637 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003638
Owen Andersond490c2d2011-01-11 00:36:45 +00003639 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3640 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00003641 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003642
Owen Andersond490c2d2011-01-11 00:36:45 +00003643 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003644 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00003645 // correspond to the trailing ones of the comparand. The value of these
3646 // bits doesn't impact the outcome of the comparison, because any value
3647 // greater than the RHS must differ in a bit higher than these due to carry.
3648 case ICmpInst::ICMP_UGT: {
3649 unsigned trailingOnes = RHS.countTrailingOnes();
3650 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
3651 return ~lowBitsSet;
3652 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003653
Owen Andersond490c2d2011-01-11 00:36:45 +00003654 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
3655 // Any value less than the RHS must differ in a higher bit because of carries.
3656 case ICmpInst::ICMP_ULT: {
3657 unsigned trailingZeros = RHS.countTrailingZeros();
3658 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
3659 return ~lowBitsSet;
3660 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003661
Owen Andersond490c2d2011-01-11 00:36:45 +00003662 default:
3663 return APInt::getAllOnesValue(BitWidth);
3664 }
Owen Andersond490c2d2011-01-11 00:36:45 +00003665}
Chris Lattner2188e402010-01-04 07:37:31 +00003666
Quentin Colombet5ab55552013-09-09 20:56:48 +00003667/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
3668/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00003669/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00003670/// as subtract operands and their positions in those instructions.
3671/// The rational is that several architectures use the same instruction for
3672/// both subtract and cmp, thus it is better if the order of those operands
3673/// match.
3674/// \return true if Op0 and Op1 should be swapped.
3675static bool swapMayExposeCSEOpportunities(const Value * Op0,
3676 const Value * Op1) {
3677 // Filter out pointer value as those cannot appears directly in subtract.
3678 // FIXME: we may want to go through inttoptrs or bitcasts.
3679 if (Op0->getType()->isPointerTy())
3680 return false;
3681 // Count every uses of both Op0 and Op1 in a subtract.
3682 // Each time Op0 is the first operand, count -1: swapping is bad, the
3683 // subtract has already the same layout as the compare.
3684 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00003685 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003686 // At the end, if the benefit is greater than 0, Op0 should come second to
3687 // expose more CSE opportunities.
3688 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003689 for (const User *U : Op0->users()) {
3690 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003691 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
3692 continue;
3693 // If Op0 is the first argument, this is not beneficial to swap the
3694 // arguments.
3695 int LocalSwapBenefits = -1;
3696 unsigned Op1Idx = 1;
3697 if (BinOp->getOperand(Op1Idx) == Op0) {
3698 Op1Idx = 0;
3699 LocalSwapBenefits = 1;
3700 }
3701 if (BinOp->getOperand(Op1Idx) != Op1)
3702 continue;
3703 GlobalSwapBenefits += LocalSwapBenefits;
3704 }
3705 return GlobalSwapBenefits > 0;
3706}
3707
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003708/// \brief Check that one use is in the same block as the definition and all
Sanjay Patel53523312016-09-12 14:25:46 +00003709/// other uses are in blocks dominated by a given block.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003710///
3711/// \param DI Definition
3712/// \param UI Use
3713/// \param DB Block that must dominate all uses of \p DI outside
3714/// the parent block
3715/// \return true when \p UI is the only use of \p DI in the parent block
3716/// and all other uses of \p DI are in blocks dominated by \p DB.
3717///
3718bool InstCombiner::dominatesAllUses(const Instruction *DI,
3719 const Instruction *UI,
3720 const BasicBlock *DB) const {
3721 assert(DI && UI && "Instruction not defined\n");
Sanjay Patel53523312016-09-12 14:25:46 +00003722 // Ignore incomplete definitions.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003723 if (!DI->getParent())
3724 return false;
Sanjay Patel53523312016-09-12 14:25:46 +00003725 // DI and UI must be in the same block.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003726 if (DI->getParent() != UI->getParent())
3727 return false;
Sanjay Patel53523312016-09-12 14:25:46 +00003728 // Protect from self-referencing blocks.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003729 if (DI->getParent() == DB)
3730 return false;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003731 for (const User *U : DI->users()) {
3732 auto *Usr = cast<Instruction>(U);
Justin Bogner99798402016-08-05 01:06:44 +00003733 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003734 return false;
3735 }
3736 return true;
3737}
3738
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003739/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003740static bool isChainSelectCmpBranch(const SelectInst *SI) {
3741 const BasicBlock *BB = SI->getParent();
3742 if (!BB)
3743 return false;
3744 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3745 if (!BI || BI->getNumSuccessors() != 2)
3746 return false;
3747 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3748 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3749 return false;
3750 return true;
3751}
3752
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003753/// \brief True when a select result is replaced by one of its operands
3754/// in select-icmp sequence. This will eventually result in the elimination
3755/// of the select.
3756///
3757/// \param SI Select instruction
3758/// \param Icmp Compare instruction
3759/// \param SIOpd Operand that replaces the select
3760///
3761/// Notes:
3762/// - The replacement is global and requires dominator information
3763/// - The caller is responsible for the actual replacement
3764///
3765/// Example:
3766///
3767/// entry:
3768/// %4 = select i1 %3, %C* %0, %C* null
3769/// %5 = icmp eq %C* %4, null
3770/// br i1 %5, label %9, label %7
3771/// ...
3772/// ; <label>:7 ; preds = %entry
3773/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3774/// ...
3775///
3776/// can be transformed to
3777///
3778/// %5 = icmp eq %C* %0, null
3779/// %6 = select i1 %3, i1 %5, i1 true
3780/// br i1 %6, label %9, label %7
3781/// ...
3782/// ; <label>:7 ; preds = %entry
3783/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3784///
3785/// Similar when the first operand of the select is a constant or/and
3786/// the compare is for not equal rather than equal.
3787///
3788/// NOTE: The function is only called when the select and compare constants
3789/// are equal, the optimization can work only for EQ predicates. This is not a
3790/// major restriction since a NE compare should be 'normalized' to an equal
3791/// compare, which usually happens in the combiner and test case
Sanjay Patel53523312016-09-12 14:25:46 +00003792/// select-cmp-br.ll checks for it.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003793bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3794 const ICmpInst *Icmp,
3795 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003796 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003797 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3798 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3799 // The check for the unique predecessor is not the best that can be
Sanjay Patel53523312016-09-12 14:25:46 +00003800 // done. But it protects efficiently against cases like when SI's
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003801 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3802 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3803 // replaced can be reached on either path. So the uniqueness check
3804 // guarantees that the path all uses of SI (outside SI's parent) are on
3805 // is disjoint from all other paths out of SI. But that information
3806 // is more expensive to compute, and the trade-off here is in favor
3807 // of compile-time.
3808 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3809 NumSel++;
3810 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3811 return true;
3812 }
3813 }
3814 return false;
3815}
3816
Sanjay Patel3151dec2016-09-12 15:24:31 +00003817/// Try to fold the comparison based on range information we can get by checking
3818/// whether bits are known to be zero or one in the inputs.
3819Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) {
3820 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3821 Type *Ty = Op0->getType();
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003822 ICmpInst::Predicate Pred = I.getPredicate();
Sanjay Patel3151dec2016-09-12 15:24:31 +00003823
3824 // Get scalar or pointer size.
3825 unsigned BitWidth = Ty->isIntOrIntVectorTy()
3826 ? Ty->getScalarSizeInBits()
3827 : DL.getTypeSizeInBits(Ty->getScalarType());
3828
3829 if (!BitWidth)
3830 return nullptr;
3831
3832 // If this is a normal comparison, it demands all bits. If it is a sign bit
3833 // comparison, it only demands the sign bit.
3834 bool IsSignBit = false;
Sanjay Patelf5887f12016-09-12 16:25:41 +00003835 const APInt *CmpC;
3836 if (match(Op1, m_APInt(CmpC))) {
Sanjay Patel3151dec2016-09-12 15:24:31 +00003837 bool UnusedBit;
Sanjay Patelf5887f12016-09-12 16:25:41 +00003838 IsSignBit = isSignBitCheck(Pred, *CmpC, UnusedBit);
Sanjay Patel3151dec2016-09-12 15:24:31 +00003839 }
3840
3841 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3842 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3843
3844 if (SimplifyDemandedBits(I.getOperandUse(0),
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003845 getDemandedBitsLHSMask(I, BitWidth, IsSignBit),
Sanjay Patel3151dec2016-09-12 15:24:31 +00003846 Op0KnownZero, Op0KnownOne, 0))
3847 return &I;
3848
3849 if (SimplifyDemandedBits(I.getOperandUse(1), APInt::getAllOnesValue(BitWidth),
3850 Op1KnownZero, Op1KnownOne, 0))
3851 return &I;
3852
3853 // Given the known and unknown bits, compute a range that the LHS could be
3854 // in. Compute the Min, Max and RHS values based on the known bits. For the
3855 // EQ and NE we use unsigned values.
3856 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3857 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3858 if (I.isSigned()) {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003859 computeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00003860 Op0Max);
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003861 computeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00003862 Op1Max);
3863 } else {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003864 computeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00003865 Op0Max);
Sanjay Pateld93c4c02016-09-15 18:22:25 +00003866 computeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min,
Sanjay Patel3151dec2016-09-12 15:24:31 +00003867 Op1Max);
3868 }
3869
3870 // If Min and Max are known to be the same, then SimplifyDemandedBits
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003871 // figured out that the LHS is a constant. Constant fold this now, so that
3872 // code below can assume that Min != Max.
Sanjay Patel3151dec2016-09-12 15:24:31 +00003873 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003874 return new ICmpInst(Pred, ConstantInt::get(Op0->getType(), Op0Min), Op1);
Sanjay Patel3151dec2016-09-12 15:24:31 +00003875 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003876 return new ICmpInst(Pred, Op0, ConstantInt::get(Op1->getType(), Op1Min));
Sanjay Patel3151dec2016-09-12 15:24:31 +00003877
3878 // Based on the range information we know about the LHS, see if we can
3879 // simplify this comparison. For example, (x&4) < 8 is always true.
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003880 switch (Pred) {
Sanjay Patel3151dec2016-09-12 15:24:31 +00003881 default:
3882 llvm_unreachable("Unknown icmp opcode!");
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003883 case ICmpInst::ICMP_EQ:
Sanjay Patel3151dec2016-09-12 15:24:31 +00003884 case ICmpInst::ICMP_NE: {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003885 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) {
3886 return Pred == CmpInst::ICMP_EQ
3887 ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()))
3888 : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3889 }
Sanjay Patel3151dec2016-09-12 15:24:31 +00003890
Sanjay Patel0531f0a2016-09-12 15:52:28 +00003891 // If all bits are known zero except for one, then we know at most one bit
3892 // is set. If the comparison is against zero, then this is a check to see if
3893 // *that* bit is set.
Sanjay Patel3151dec2016-09-12 15:24:31 +00003894 APInt Op0KnownZeroInverted = ~Op0KnownZero;
3895 if (~Op1KnownZero == 0) {
3896 // If the LHS is an AND with the same constant, look through it.
3897 Value *LHS = nullptr;
Sanjay Patel7577a3d2016-09-15 14:15:47 +00003898 const APInt *LHSC;
3899 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
3900 *LHSC != Op0KnownZeroInverted)
Sanjay Patel3151dec2016-09-12 15:24:31 +00003901 LHS = Op0;
3902
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003903 Value *X;
Sanjay Patel3151dec2016-09-12 15:24:31 +00003904 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
3905 APInt ValToCheck = Op0KnownZeroInverted;
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003906 Type *XTy = X->getType();
Sanjay Patel3151dec2016-09-12 15:24:31 +00003907 if (ValToCheck.isPowerOf2()) {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003908 // ((1 << X) & 8) == 0 -> X != 3
3909 // ((1 << X) & 8) != 0 -> X == 3
3910 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
3911 auto NewPred = ICmpInst::getInversePredicate(Pred);
3912 return new ICmpInst(NewPred, X, CmpC);
Sanjay Patel3151dec2016-09-12 15:24:31 +00003913 } else if ((++ValToCheck).isPowerOf2()) {
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003914 // ((1 << X) & 7) == 0 -> X >= 3
3915 // ((1 << X) & 7) != 0 -> X < 3
3916 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros());
3917 auto NewPred =
3918 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
3919 return new ICmpInst(NewPred, X, CmpC);
Sanjay Patel3151dec2016-09-12 15:24:31 +00003920 }
3921 }
3922
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003923 // Check if the LHS is 8 >>u x and the result is a power of 2 like 1.
Sanjay Patel3151dec2016-09-12 15:24:31 +00003924 const APInt *CI;
3925 if (Op0KnownZeroInverted == 1 &&
Sanjay Patel9efb1bd2016-09-14 23:38:56 +00003926 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) {
3927 // ((8 >>u X) & 1) == 0 -> X != 3
3928 // ((8 >>u X) & 1) != 0 -> X == 3
3929 unsigned CmpVal = CI->countTrailingZeros();
3930 auto NewPred = ICmpInst::getInversePredicate(Pred);
3931 return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal));
3932 }
Sanjay Patel3151dec2016-09-12 15:24:31 +00003933 }
3934 break;
3935 }
3936 case ICmpInst::ICMP_ULT: {
3937 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
3938 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3939 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
3940 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3941 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3942 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3943
3944 const APInt *CmpC;
3945 if (match(Op1, m_APInt(CmpC))) {
3946 // A <u C -> A == C-1 if min(A)+1 == C
3947 if (Op1Max == Op0Min + 1) {
3948 Constant *CMinus1 = ConstantInt::get(Op0->getType(), *CmpC - 1);
3949 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, CMinus1);
3950 }
3951 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3952 if (CmpC->isMinSignedValue()) {
3953 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
3954 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
3955 }
3956 }
3957 break;
3958 }
3959 case ICmpInst::ICMP_UGT: {
3960 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
3961 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3962
3963 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
3964 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3965
3966 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3967 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3968
3969 const APInt *CmpC;
3970 if (match(Op1, m_APInt(CmpC))) {
3971 // A >u C -> A == C+1 if max(a)-1 == C
3972 if (*CmpC == Op0Max - 1)
3973 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3974 ConstantInt::get(Op1->getType(), *CmpC + 1));
3975
3976 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3977 if (CmpC->isMaxSignedValue())
3978 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3979 Constant::getNullValue(Op0->getType()));
3980 }
3981 break;
3982 }
3983 case ICmpInst::ICMP_SLT:
3984 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
3985 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3986 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
3987 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3988 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3989 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3990 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3991 if (Op1Max == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
3992 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3993 Builder->getInt(CI->getValue() - 1));
3994 }
3995 break;
3996 case ICmpInst::ICMP_SGT:
3997 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
3998 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3999 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
4000 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4001
4002 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
4003 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4004 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4005 if (Op1Min == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
4006 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
4007 Builder->getInt(CI->getValue() + 1));
4008 }
4009 break;
4010 case ICmpInst::ICMP_SGE:
4011 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
4012 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
4013 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4014 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
4015 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4016 break;
4017 case ICmpInst::ICMP_SLE:
4018 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
4019 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
4020 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4021 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
4022 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4023 break;
4024 case ICmpInst::ICMP_UGE:
4025 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
4026 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
4027 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4028 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
4029 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4030 break;
4031 case ICmpInst::ICMP_ULE:
4032 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
4033 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
4034 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4035 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
4036 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4037 break;
4038 }
4039
4040 // Turn a signed comparison into an unsigned one if both operands are known to
4041 // have the same sign.
4042 if (I.isSigned() &&
4043 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
4044 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
4045 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
4046
4047 return nullptr;
4048}
4049
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004050/// If we have an icmp le or icmp ge instruction with a constant operand, turn
4051/// it into the appropriate icmp lt or icmp gt instruction. This transform
4052/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00004053static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
4054 ICmpInst::Predicate Pred = I.getPredicate();
4055 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
4056 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
4057 return nullptr;
4058
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004059 Value *Op0 = I.getOperand(0);
4060 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00004061 auto *Op1C = dyn_cast<Constant>(Op1);
4062 if (!Op1C)
4063 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004064
Sanjay Patele9b2c322016-05-17 00:57:57 +00004065 // Check if the constant operand can be safely incremented/decremented without
4066 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
4067 // the edge cases for us, so we just assert on them. For vectors, we must
4068 // handle the edge cases.
4069 Type *Op1Type = Op1->getType();
4070 bool IsSigned = I.isSigned();
4071 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00004072 auto *CI = dyn_cast<ConstantInt>(Op1C);
4073 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00004074 // A <= MAX -> TRUE ; A >= MIN -> TRUE
4075 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
4076 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00004077 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00004078 // are for scalar, we could remove the min/max checks. However, to do that,
4079 // we would have to use insertelement/shufflevector to replace edge values.
4080 unsigned NumElts = Op1Type->getVectorNumElements();
4081 for (unsigned i = 0; i != NumElts; ++i) {
4082 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00004083 if (!Elt)
4084 return nullptr;
4085
Sanjay Patele9b2c322016-05-17 00:57:57 +00004086 if (isa<UndefValue>(Elt))
4087 continue;
Sanjay Patel06b127a2016-09-15 14:37:50 +00004088
Sanjay Patele9b2c322016-05-17 00:57:57 +00004089 // Bail out if we can't determine if this constant is min/max or if we
4090 // know that this constant is min/max.
4091 auto *CI = dyn_cast<ConstantInt>(Elt);
4092 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
4093 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00004094 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00004095 } else {
4096 // ConstantExpr?
4097 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00004098 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004099
Sanjay Patele9b2c322016-05-17 00:57:57 +00004100 // Increment or decrement the constant and set the new comparison predicate:
4101 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00004102 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00004103 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
4104 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
4105 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004106}
4107
Chris Lattner2188e402010-01-04 07:37:31 +00004108Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4109 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00004110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00004111 unsigned Op0Cplxity = getComplexity(Op0);
4112 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004113
Chris Lattner2188e402010-01-04 07:37:31 +00004114 /// Orders the operands of the compare so that they are listed from most
4115 /// complex to least complex. This puts constants before unary operators,
4116 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00004117 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00004118 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00004119 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00004120 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00004121 Changed = true;
4122 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004123
Jingyue Wu5e34ce32015-06-25 20:14:47 +00004124 if (Value *V =
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004125 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004126 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004127
Pete Cooperbc5c5242011-12-01 03:58:40 +00004128 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00004129 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00004130 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00004131 Value *Cond, *SelectTrue, *SelectFalse;
4132 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00004133 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00004134 if (Value *V = dyn_castNegVal(SelectTrue)) {
4135 if (V == SelectFalse)
4136 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
4137 }
4138 else if (Value *V = dyn_castNegVal(SelectFalse)) {
4139 if (V == SelectTrue)
4140 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00004141 }
4142 }
4143 }
4144
Chris Lattner229907c2011-07-18 04:54:35 +00004145 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00004146
4147 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00004148 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00004149 switch (I.getPredicate()) {
4150 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004151 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
4152 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004153 return BinaryOperator::CreateNot(Xor);
4154 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004155 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00004156 return BinaryOperator::CreateXor(Op0, Op1);
4157
4158 case ICmpInst::ICMP_UGT:
4159 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004160 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004161 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
4162 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004163 return BinaryOperator::CreateAnd(Not, Op1);
4164 }
4165 case ICmpInst::ICMP_SGT:
4166 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004167 LLVM_FALLTHROUGH;
Chris Lattner2188e402010-01-04 07:37:31 +00004168 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004169 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004170 return BinaryOperator::CreateAnd(Not, Op0);
4171 }
4172 case ICmpInst::ICMP_UGE:
4173 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004174 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004175 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
4176 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004177 return BinaryOperator::CreateOr(Not, Op1);
4178 }
4179 case ICmpInst::ICMP_SGE:
4180 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
Justin Bognercd1d5aa2016-08-17 20:30:52 +00004181 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004182 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
4183 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00004184 return BinaryOperator::CreateOr(Not, Op0);
4185 }
4186 }
4187 }
4188
Sanjay Patele9b2c322016-05-17 00:57:57 +00004189 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00004190 return NewICmp;
4191
Sanjay Patel06b127a2016-09-15 14:37:50 +00004192 if (Instruction *Res = foldICmpWithConstant(I))
4193 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00004194
Sanjay Patel3151dec2016-09-12 15:24:31 +00004195 if (Instruction *Res = foldICmpUsingKnownBits(I))
4196 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00004197
4198 // Test if the ICmpInst instruction is used exclusively by a select as
4199 // part of a minimum or maximum operation. If so, refrain from doing
4200 // any other folding. This helps out other analyses which understand
4201 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4202 // and CodeGen. And in this case, at least one of the comparison
4203 // operands has at least one user besides the compare (the select),
4204 // which would often largely negate the benefit of folding anyway.
4205 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00004206 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00004207 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4208 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00004209 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004210
Sanjay Patelf58f68c2016-09-10 15:03:44 +00004211 if (Instruction *Res = foldICmpInstWithConstant(I))
Sanjay Patel1271bf92016-07-23 13:06:49 +00004212 return Res;
4213
Sanjay Patel10494b22016-09-16 16:10:22 +00004214 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
4215 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00004216
4217 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
4218 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00004219 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner2188e402010-01-04 07:37:31 +00004220 return NI;
4221 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00004222 if (Instruction *NI = foldGEPICmp(GEP, Op0,
Chris Lattner2188e402010-01-04 07:37:31 +00004223 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
4224 return NI;
4225
Hans Wennborgf1f36512015-10-07 00:20:07 +00004226 // Try to optimize equality comparisons against alloca-based pointers.
4227 if (Op0->getType()->isPointerTy() && I.isEquality()) {
4228 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
4229 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00004230 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
Hans Wennborgf1f36512015-10-07 00:20:07 +00004231 return New;
4232 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00004233 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
Hans Wennborgf1f36512015-10-07 00:20:07 +00004234 return New;
4235 }
4236
Chris Lattner2188e402010-01-04 07:37:31 +00004237 // Test to see if the operands of the icmp are casted versions of other
4238 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4239 // now.
4240 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00004241 if (Op0->getType()->isPointerTy() &&
4242 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00004243 // We keep moving the cast from the left operand over to the right
4244 // operand, where it can often be eliminated completely.
4245 Op0 = CI->getOperand(0);
4246
4247 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
4248 // so eliminate it as well.
4249 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4250 Op1 = CI2->getOperand(0);
4251
4252 // If Op1 is a constant, we can fold the cast into the constant.
4253 if (Op0->getType() != Op1->getType()) {
4254 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4255 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
4256 } else {
4257 // Otherwise, cast the RHS right before the icmp
4258 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
4259 }
4260 }
4261 return new ICmpInst(I.getPredicate(), Op0, Op1);
4262 }
4263 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004264
Chris Lattner2188e402010-01-04 07:37:31 +00004265 if (isa<CastInst>(Op0)) {
4266 // Handle the special case of: icmp (cast bool to X), <cst>
4267 // This comes up when you have code like
4268 // int X = A < B;
4269 // if (X) ...
4270 // For generality, we handle any zero-extension of any operand comparison
4271 // with a constant or another cast from the same type.
4272 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00004273 if (Instruction *R = foldICmpWithCastAndCast(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004274 return R;
4275 }
Chris Lattner2188e402010-01-04 07:37:31 +00004276
Sanjay Patel10494b22016-09-16 16:10:22 +00004277 if (Instruction *Res = foldICmpBinOp(I))
4278 return Res;
Duncan Sandse5220012011-02-17 07:46:37 +00004279
Sanjay Patel10494b22016-09-16 16:10:22 +00004280 {
4281 Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004282 // Transform (A & ~B) == 0 --> (A & B) != 0
4283 // and (A & ~B) != 0 --> (A & B) == 0
4284 // if A is a power of 2.
4285 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004286 match(Op1, m_Zero()) &&
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004287 isKnownToBeAPowerOfTwo(A, DL, false, 0, &I, &DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004288 return new ICmpInst(I.getInversePredicate(),
4289 Builder->CreateAnd(A, B),
4290 Op1);
4291
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004292 // ~x < ~y --> y < x
4293 // ~x < cst --> ~cst < x
4294 if (match(Op0, m_Not(m_Value(A)))) {
4295 if (match(Op1, m_Not(m_Value(B))))
4296 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004297 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004298 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4299 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004300
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004301 Instruction *AddI = nullptr;
4302 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4303 m_Instruction(AddI))) &&
4304 isa<IntegerType>(A->getType())) {
4305 Value *Result;
4306 Constant *Overflow;
4307 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4308 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004309 replaceInstUsesWith(*AddI, Result);
4310 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004311 }
4312 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004313
4314 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4315 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004316 if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this))
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004317 return R;
4318 }
4319 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
Sanjay Pateld93c4c02016-09-15 18:22:25 +00004320 if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this))
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004321 return R;
4322 }
Chris Lattner2188e402010-01-04 07:37:31 +00004323 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004324
Sanjay Patel10494b22016-09-16 16:10:22 +00004325 if (Instruction *Res = foldICmpEquality(I))
4326 return Res;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004327
David Majnemerc1eca5a2014-11-06 23:23:30 +00004328 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4329 // an i1 which indicates whether or not we successfully did the swap.
4330 //
4331 // Replace comparisons between the old value and the expected value with the
4332 // indicator that 'cmpxchg' returns.
4333 //
4334 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4335 // spuriously fail. In those cases, the old value may equal the expected
4336 // value but it is possible for the swap to not occur.
4337 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4338 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4339 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4340 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4341 !ACXI->isWeak())
4342 return ExtractValueInst::Create(ACXI, 1);
4343
Chris Lattner2188e402010-01-04 07:37:31 +00004344 {
4345 Value *X; ConstantInt *Cst;
4346 // icmp X+Cst, X
4347 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004348 return foldICmpAddOpConst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004349
4350 // icmp X, X+Cst
4351 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004352 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004353 }
Craig Topperf40110f2014-04-25 05:29:35 +00004354 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004355}
4356
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004357/// Fold fcmp ([us]itofp x, cst) if possible.
Sanjay Patel43395062016-07-21 18:07:40 +00004358Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
Chris Lattner2188e402010-01-04 07:37:31 +00004359 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004360 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004361 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004362
Chris Lattner2188e402010-01-04 07:37:31 +00004363 // Get the width of the mantissa. We don't want to hack on conversions that
4364 // might lose information from the integer, e.g. "i64 -> float"
4365 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004366 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004367
Matt Arsenault55e73122015-01-06 15:50:59 +00004368 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4369
Chris Lattner2188e402010-01-04 07:37:31 +00004370 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004371
Matt Arsenault55e73122015-01-06 15:50:59 +00004372 if (I.isEquality()) {
4373 FCmpInst::Predicate P = I.getPredicate();
4374 bool IsExact = false;
4375 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4376 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4377
4378 // If the floating point constant isn't an integer value, we know if we will
4379 // ever compare equal / not equal to it.
4380 if (!IsExact) {
4381 // TODO: Can never be -0.0 and other non-representable values
4382 APFloat RHSRoundInt(RHS);
4383 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4384 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4385 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004386 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004387
4388 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004389 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004390 }
4391 }
4392
4393 // TODO: If the constant is exactly representable, is it always OK to do
4394 // equality compares as integer?
4395 }
4396
Arch D. Robison8ed08542015-09-15 17:51:59 +00004397 // Check to see that the input is converted from an integer type that is small
4398 // enough that preserves all bits. TODO: check here for "known" sign bits.
4399 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4400 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004401
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004402 // Following test does NOT adjust InputSize downwards for signed inputs,
4403 // because the most negative value still requires all the mantissa bits
Arch D. Robison8ed08542015-09-15 17:51:59 +00004404 // to distinguish it from one less than that value.
4405 if ((int)InputSize > MantissaWidth) {
4406 // Conversion would lose accuracy. Check if loss can impact comparison.
4407 int Exp = ilogb(RHS);
4408 if (Exp == APFloat::IEK_Inf) {
4409 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004410 if (MaxExponent < (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004411 // Conversion could create infinity.
4412 return nullptr;
4413 } else {
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004414 // Note that if RHS is zero or NaN, then Exp is negative
Arch D. Robison8ed08542015-09-15 17:51:59 +00004415 // and first condition is trivially false.
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004416 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004417 // Conversion could affect comparison.
4418 return nullptr;
4419 }
4420 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004421
Chris Lattner2188e402010-01-04 07:37:31 +00004422 // Otherwise, we can potentially simplify the comparison. We know that it
4423 // will always come through as an integer value and we know the constant is
4424 // not a NAN (it would have been previously simplified).
4425 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004426
Chris Lattner2188e402010-01-04 07:37:31 +00004427 ICmpInst::Predicate Pred;
4428 switch (I.getPredicate()) {
4429 default: llvm_unreachable("Unexpected predicate!");
4430 case FCmpInst::FCMP_UEQ:
4431 case FCmpInst::FCMP_OEQ:
4432 Pred = ICmpInst::ICMP_EQ;
4433 break;
4434 case FCmpInst::FCMP_UGT:
4435 case FCmpInst::FCMP_OGT:
4436 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4437 break;
4438 case FCmpInst::FCMP_UGE:
4439 case FCmpInst::FCMP_OGE:
4440 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4441 break;
4442 case FCmpInst::FCMP_ULT:
4443 case FCmpInst::FCMP_OLT:
4444 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4445 break;
4446 case FCmpInst::FCMP_ULE:
4447 case FCmpInst::FCMP_OLE:
4448 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4449 break;
4450 case FCmpInst::FCMP_UNE:
4451 case FCmpInst::FCMP_ONE:
4452 Pred = ICmpInst::ICMP_NE;
4453 break;
4454 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004455 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004456 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004457 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004458 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004459
Chris Lattner2188e402010-01-04 07:37:31 +00004460 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004461
Chris Lattner2188e402010-01-04 07:37:31 +00004462 // See if the FP constant is too large for the integer. For example,
4463 // comparing an i8 to 300.0.
4464 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004465
Chris Lattner2188e402010-01-04 07:37:31 +00004466 if (!LHSUnsigned) {
4467 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4468 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004469 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004470 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4471 APFloat::rmNearestTiesToEven);
4472 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4473 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4474 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004475 return replaceInstUsesWith(I, Builder->getTrue());
4476 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004477 }
4478 } else {
4479 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4480 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004481 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004482 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4483 APFloat::rmNearestTiesToEven);
4484 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4485 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4486 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004487 return replaceInstUsesWith(I, Builder->getTrue());
4488 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004489 }
4490 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004491
Chris Lattner2188e402010-01-04 07:37:31 +00004492 if (!LHSUnsigned) {
4493 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004494 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004495 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4496 APFloat::rmNearestTiesToEven);
4497 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4498 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4499 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004500 return replaceInstUsesWith(I, Builder->getTrue());
4501 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004502 }
Devang Patel698452b2012-02-13 23:05:18 +00004503 } else {
4504 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004505 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004506 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4507 APFloat::rmNearestTiesToEven);
4508 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4509 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4510 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004511 return replaceInstUsesWith(I, Builder->getTrue());
4512 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004513 }
Chris Lattner2188e402010-01-04 07:37:31 +00004514 }
4515
4516 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4517 // [0, UMAX], but it may still be fractional. See if it is fractional by
4518 // casting the FP value to the integer value and back, checking for equality.
4519 // Don't do this for zero, because -0.0 is not fractional.
4520 Constant *RHSInt = LHSUnsigned
4521 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4522 : ConstantExpr::getFPToSI(RHSC, IntTy);
4523 if (!RHS.isZero()) {
4524 bool Equal = LHSUnsigned
4525 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4526 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4527 if (!Equal) {
4528 // If we had a comparison against a fractional value, we have to adjust
4529 // the compare predicate and sometimes the value. RHSC is rounded towards
4530 // zero at this point.
4531 switch (Pred) {
4532 default: llvm_unreachable("Unexpected integer comparison!");
4533 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004534 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004535 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004536 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004537 case ICmpInst::ICMP_ULE:
4538 // (float)int <= 4.4 --> int <= 4
4539 // (float)int <= -4.4 --> false
4540 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004541 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004542 break;
4543 case ICmpInst::ICMP_SLE:
4544 // (float)int <= 4.4 --> int <= 4
4545 // (float)int <= -4.4 --> int < -4
4546 if (RHS.isNegative())
4547 Pred = ICmpInst::ICMP_SLT;
4548 break;
4549 case ICmpInst::ICMP_ULT:
4550 // (float)int < -4.4 --> false
4551 // (float)int < 4.4 --> int <= 4
4552 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004553 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004554 Pred = ICmpInst::ICMP_ULE;
4555 break;
4556 case ICmpInst::ICMP_SLT:
4557 // (float)int < -4.4 --> int < -4
4558 // (float)int < 4.4 --> int <= 4
4559 if (!RHS.isNegative())
4560 Pred = ICmpInst::ICMP_SLE;
4561 break;
4562 case ICmpInst::ICMP_UGT:
4563 // (float)int > 4.4 --> int > 4
4564 // (float)int > -4.4 --> true
4565 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004566 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004567 break;
4568 case ICmpInst::ICMP_SGT:
4569 // (float)int > 4.4 --> int > 4
4570 // (float)int > -4.4 --> int >= -4
4571 if (RHS.isNegative())
4572 Pred = ICmpInst::ICMP_SGE;
4573 break;
4574 case ICmpInst::ICMP_UGE:
4575 // (float)int >= -4.4 --> true
4576 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004577 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004578 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004579 Pred = ICmpInst::ICMP_UGT;
4580 break;
4581 case ICmpInst::ICMP_SGE:
4582 // (float)int >= -4.4 --> int >= -4
4583 // (float)int >= 4.4 --> int > 4
4584 if (!RHS.isNegative())
4585 Pred = ICmpInst::ICMP_SGT;
4586 break;
4587 }
4588 }
4589 }
4590
4591 // Lower this FP comparison into an appropriate integer version of the
4592 // comparison.
4593 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4594}
4595
4596Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4597 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004598
Chris Lattner2188e402010-01-04 07:37:31 +00004599 /// Orders the operands of the compare so that they are listed from most
4600 /// complex to least complex. This puts constants before unary operators,
4601 /// before binary operators.
4602 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4603 I.swapOperands();
4604 Changed = true;
4605 }
4606
4607 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004608
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004609 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004610 I.getFastMathFlags(), DL, &TLI, &DT, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004611 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004612
4613 // Simplify 'fcmp pred X, X'
4614 if (Op0 == Op1) {
4615 switch (I.getPredicate()) {
4616 default: llvm_unreachable("Unknown predicate!");
4617 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4618 case FCmpInst::FCMP_ULT: // True if unordered or less than
4619 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4620 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4621 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4622 I.setPredicate(FCmpInst::FCMP_UNO);
4623 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4624 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004625
Chris Lattner2188e402010-01-04 07:37:31 +00004626 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4627 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4628 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4629 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4630 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4631 I.setPredicate(FCmpInst::FCMP_ORD);
4632 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4633 return &I;
4634 }
4635 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004636
James Molloy2b21a7c2015-05-20 18:41:25 +00004637 // Test if the FCmpInst instruction is used exclusively by a select as
4638 // part of a minimum or maximum operation. If so, refrain from doing
4639 // any other folding. This helps out other analyses which understand
4640 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4641 // and CodeGen. And in this case, at least one of the comparison
4642 // operands has at least one user besides the compare (the select),
4643 // which would often largely negate the benefit of folding anyway.
4644 if (I.hasOneUse())
4645 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4646 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4647 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4648 return nullptr;
4649
Chris Lattner2188e402010-01-04 07:37:31 +00004650 // Handle fcmp with constant RHS
4651 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4652 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4653 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004654 case Instruction::FPExt: {
4655 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4656 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4657 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4658 if (!RHSF)
4659 break;
4660
4661 const fltSemantics *Sem;
4662 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004663 if (LHSExt->getSrcTy()->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004664 Sem = &APFloat::IEEEhalf();
Dan Gohman518cda42011-12-17 00:04:22 +00004665 else if (LHSExt->getSrcTy()->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004666 Sem = &APFloat::IEEEsingle();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004667 else if (LHSExt->getSrcTy()->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004668 Sem = &APFloat::IEEEdouble();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004669 else if (LHSExt->getSrcTy()->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004670 Sem = &APFloat::IEEEquad();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004671 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004672 Sem = &APFloat::x87DoubleExtended();
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004673 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004674 Sem = &APFloat::PPCDoubleDouble();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004675 else
4676 break;
4677
4678 bool Lossy;
4679 APFloat F = RHSF->getValueAPF();
4680 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4681
Jim Grosbach24ff8342011-09-30 18:45:50 +00004682 // Avoid lossy conversions and denormals. Zero is a special case
4683 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004684 APFloat Fabs = F;
4685 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004686 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004687 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4688 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004689
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004690 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4691 ConstantFP::get(RHSC->getContext(), F));
4692 break;
4693 }
Chris Lattner2188e402010-01-04 07:37:31 +00004694 case Instruction::PHI:
4695 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4696 // block. If in the same block, we're encouraging jump threading. If
4697 // not, we are just pessimizing the code by making an i1 phi.
4698 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004699 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004700 return NV;
4701 break;
4702 case Instruction::SIToFP:
4703 case Instruction::UIToFP:
Sanjay Patel43395062016-07-21 18:07:40 +00004704 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
Chris Lattner2188e402010-01-04 07:37:31 +00004705 return NV;
4706 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004707 case Instruction::FSub: {
4708 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4709 Value *Op;
4710 if (match(LHSI, m_FNeg(m_Value(Op))))
4711 return new FCmpInst(I.getSwappedPredicate(), Op,
4712 ConstantExpr::getFNeg(RHSC));
4713 break;
4714 }
Dan Gohman94732022010-02-24 06:46:09 +00004715 case Instruction::Load:
4716 if (GetElementPtrInst *GEP =
4717 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4718 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4719 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4720 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00004721 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Dan Gohman94732022010-02-24 06:46:09 +00004722 return Res;
4723 }
4724 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004725 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004726 if (!RHSC->isNullValue())
4727 break;
4728
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004729 CallInst *CI = cast<CallInst>(LHSI);
Justin Bogner99798402016-08-05 01:06:44 +00004730 Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004731 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004732 break;
4733
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004734 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004735 switch (I.getPredicate()) {
4736 default:
4737 break;
4738 // fabs(x) < 0 --> false
4739 case FCmpInst::FCMP_OLT:
4740 llvm_unreachable("handled by SimplifyFCmpInst");
4741 // fabs(x) > 0 --> x != 0
4742 case FCmpInst::FCMP_OGT:
4743 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4744 // fabs(x) <= 0 --> x == 0
4745 case FCmpInst::FCMP_OLE:
4746 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4747 // fabs(x) >= 0 --> !isnan(x)
4748 case FCmpInst::FCMP_OGE:
4749 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4750 // fabs(x) == 0 --> x == 0
4751 // fabs(x) != 0 --> x != 0
4752 case FCmpInst::FCMP_OEQ:
4753 case FCmpInst::FCMP_UEQ:
4754 case FCmpInst::FCMP_ONE:
4755 case FCmpInst::FCMP_UNE:
4756 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004757 }
4758 }
Chris Lattner2188e402010-01-04 07:37:31 +00004759 }
Chris Lattner2188e402010-01-04 07:37:31 +00004760 }
4761
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004762 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004763 Value *X, *Y;
4764 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004765 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004766
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004767 // fcmp (fpext x), (fpext y) -> fcmp x, y
4768 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4769 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4770 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4771 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4772 RHSExt->getOperand(0));
4773
Craig Topperf40110f2014-04-25 05:29:35 +00004774 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004775}