blob: b6cdf640b009ecf6a9fa22e4979f8b95c04a0ea1 [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
14#include "InstCombine.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000016#include "llvm/Analysis/InstructionSimplify.h"
17#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/IntrinsicInst.h"
Chris Lattner2188e402010-01-04 07:37:31 +000020#include "llvm/Support/ConstantRange.h"
21#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/Support/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner2188e402010-01-04 07:37:31 +000024using namespace llvm;
25using namespace PatternMatch;
26
Chris Lattner98457102011-02-10 05:23:05 +000027static ConstantInt *getOne(Constant *C) {
28 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
29}
30
Chris Lattner2188e402010-01-04 07:37:31 +000031/// AddOne - Add one to a ConstantInt
32static Constant *AddOne(Constant *C) {
33 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
34}
35/// SubOne - Subtract one from a ConstantInt
Chris Lattner98457102011-02-10 05:23:05 +000036static Constant *SubOne(Constant *C) {
37 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner2188e402010-01-04 07:37:31 +000038}
39
40static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
41 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
42}
43
44static bool HasAddOverflow(ConstantInt *Result,
45 ConstantInt *In1, ConstantInt *In2,
46 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000047 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000048 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000049
50 if (In2->isNegative())
51 return Result->getValue().sgt(In1->getValue());
52 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000053}
54
55/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
56/// overflowed for this type.
57static bool AddWithOverflow(Constant *&Result, Constant *In1,
58 Constant *In2, bool IsSigned = false) {
59 Result = ConstantExpr::getAdd(In1, In2);
60
Chris Lattner229907c2011-07-18 04:54:35 +000061 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000062 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
63 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
64 if (HasAddOverflow(ExtractElement(Result, Idx),
65 ExtractElement(In1, Idx),
66 ExtractElement(In2, Idx),
67 IsSigned))
68 return true;
69 }
70 return false;
71 }
72
73 return HasAddOverflow(cast<ConstantInt>(Result),
74 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
75 IsSigned);
76}
77
78static bool HasSubOverflow(ConstantInt *Result,
79 ConstantInt *In1, ConstantInt *In2,
80 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000081 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000082 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000083
Chris Lattnerb1a15122011-07-15 06:08:15 +000084 if (In2->isNegative())
85 return Result->getValue().slt(In1->getValue());
86
87 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000088}
89
90/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
91/// overflowed for this type.
92static bool SubWithOverflow(Constant *&Result, Constant *In1,
93 Constant *In2, bool IsSigned = false) {
94 Result = ConstantExpr::getSub(In1, In2);
95
Chris Lattner229907c2011-07-18 04:54:35 +000096 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000097 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
98 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
99 if (HasSubOverflow(ExtractElement(Result, Idx),
100 ExtractElement(In1, Idx),
101 ExtractElement(In2, Idx),
102 IsSigned))
103 return true;
104 }
105 return false;
106 }
107
108 return HasSubOverflow(cast<ConstantInt>(Result),
109 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
110 IsSigned);
111}
112
113/// isSignBitCheck - Given an exploded icmp instruction, return true if the
114/// comparison only checks the sign bit. If it only checks the sign bit, set
115/// TrueIfSigned if the result of the comparison is true when the input value is
116/// signed.
117static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
118 bool &TrueIfSigned) {
119 switch (pred) {
120 case ICmpInst::ICMP_SLT: // True if LHS s< 0
121 TrueIfSigned = true;
122 return RHS->isZero();
123 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
124 TrueIfSigned = true;
125 return RHS->isAllOnesValue();
126 case ICmpInst::ICMP_SGT: // True if LHS s> -1
127 TrueIfSigned = false;
128 return RHS->isAllOnesValue();
129 case ICmpInst::ICMP_UGT:
130 // True if LHS u> RHS and RHS == high-bit-mask - 1
131 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000132 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000133 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000134 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
135 TrueIfSigned = true;
136 return RHS->getValue().isSignBit();
137 default:
138 return false;
139 }
140}
141
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000142/// Returns true if the exploded icmp can be expressed as a signed comparison
143/// to zero and updates the predicate accordingly.
144/// The signedness of the comparison is preserved.
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000145static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
146 if (!ICmpInst::isSigned(pred))
147 return false;
148
149 if (RHS->isZero())
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000150 return ICmpInst::isRelational(pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000151
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000152 if (RHS->isOne()) {
153 if (pred == ICmpInst::ICMP_SLT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000154 pred = ICmpInst::ICMP_SLE;
155 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000156 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000157 } else if (RHS->isAllOnesValue()) {
158 if (pred == ICmpInst::ICMP_SGT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000159 pred = ICmpInst::ICMP_SGE;
160 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000161 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000162 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000163
164 return false;
165}
166
Chris Lattner2188e402010-01-04 07:37:31 +0000167// isHighOnes - Return true if the constant is of the form 1+0+.
168// This is the same as lowones(~X).
169static bool isHighOnes(const ConstantInt *CI) {
170 return (~CI->getValue() + 1).isPowerOf2();
171}
172
Jim Grosbach129c52a2011-09-30 18:09:53 +0000173/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner2188e402010-01-04 07:37:31 +0000174/// set of known zero and one bits, compute the maximum and minimum values that
175/// could have the specified known zero and known one bits, returning them in
176/// min/max.
177static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
178 const APInt& KnownOne,
179 APInt& Min, APInt& Max) {
180 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
181 KnownZero.getBitWidth() == Min.getBitWidth() &&
182 KnownZero.getBitWidth() == Max.getBitWidth() &&
183 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
184 APInt UnknownBits = ~(KnownZero|KnownOne);
185
186 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
187 // bit if it is unknown.
188 Min = KnownOne;
189 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000190
Chris Lattner2188e402010-01-04 07:37:31 +0000191 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000192 Min.setBit(Min.getBitWidth()-1);
193 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000194 }
195}
196
197// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
198// a set of known zero and one bits, compute the maximum and minimum values that
199// could have the specified known zero and known one bits, returning them in
200// min/max.
201static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
202 const APInt &KnownOne,
203 APInt &Min, APInt &Max) {
204 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
205 KnownZero.getBitWidth() == Min.getBitWidth() &&
206 KnownZero.getBitWidth() == Max.getBitWidth() &&
207 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
208 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim 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
216
217
218/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
219/// cmp pred (load (gep GV, ...)), cmpcst
220/// where GV is a global variable with a constant initializer. Try to simplify
221/// this into some simple computation that does not need the load. For example
222/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
223///
224/// If AndCst is non-null, then the loaded value is masked with that constant
225/// before doing the comparison. This handles cases like "A[i]&4 == 0".
226Instruction *InstCombiner::
227FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
228 CmpInst &ICI, ConstantInt *AndCst) {
Matt Arsenault5aeae182013-08-19 21:40:31 +0000229 // We need TD information to know the pointer size unless this is inbounds.
230 if (!GEP->isInBounds() && TD == 0)
Matt Arsenault1de76772013-08-15 23:11:07 +0000231 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000232
Chris Lattnerfe741762012-01-31 02:55:06 +0000233 Constant *Init = GV->getInitializer();
234 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
235 return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000236
Chris Lattnerfe741762012-01-31 02:55:06 +0000237 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
238 if (ArrayElementCount > 1024) return 0; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000239
Chris Lattner2188e402010-01-04 07:37:31 +0000240 // There are many forms of this optimization we can handle, for now, just do
241 // the simple index into a single-dimensional array.
242 //
243 // Require: GEP GV, 0, i {{, constant indices}}
244 if (GEP->getNumOperands() < 3 ||
245 !isa<ConstantInt>(GEP->getOperand(1)) ||
246 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
247 isa<Constant>(GEP->getOperand(2)))
248 return 0;
249
250 // Check that indices after the variable are constants and in-range for the
251 // type they index. Collect the indices. This is typically for arrays of
252 // structs.
253 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000254
Chris Lattnerfe741762012-01-31 02:55:06 +0000255 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000256 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
257 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
258 if (Idx == 0) return 0; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000259
Chris Lattner2188e402010-01-04 07:37:31 +0000260 uint64_t IdxVal = Idx->getZExtValue();
261 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000262
Chris Lattner229907c2011-07-18 04:54:35 +0000263 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000264 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000265 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Chris Lattner2188e402010-01-04 07:37:31 +0000266 if (IdxVal >= ATy->getNumElements()) return 0;
267 EltTy = ATy->getElementType();
268 } else {
269 return 0; // Unknown type.
270 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000271
Chris Lattner2188e402010-01-04 07:37:31 +0000272 LaterIndices.push_back(IdxVal);
273 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000274
Chris Lattner2188e402010-01-04 07:37:31 +0000275 enum { Overdefined = -3, Undefined = -2 };
276
277 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000278
Chris Lattner2188e402010-01-04 07:37:31 +0000279 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
280 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
281 // and 87 is the second (and last) index. FirstTrueElement is -2 when
282 // undefined, otherwise set to the first true element. SecondTrueElement is
283 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
284 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
285
286 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
287 // form "i != 47 & i != 87". Same state transitions as for true elements.
288 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000289
Chris Lattner2188e402010-01-04 07:37:31 +0000290 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
291 /// define a state machine that triggers for ranges of values that the index
292 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
293 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
294 /// index in the range (inclusive). We use -2 for undefined here because we
295 /// use relative comparisons and don't want 0-1 to match -1.
296 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000297
Chris Lattner2188e402010-01-04 07:37:31 +0000298 // MagicBitvector - This is a magic bitvector where we set a bit if the
299 // comparison is true for element 'i'. If there are 64 elements or less in
300 // the array, this will fully represent all the comparison results.
301 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000302
303
Chris Lattner2188e402010-01-04 07:37:31 +0000304 // Scan the array and see if one of our patterns matches.
305 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000306 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
307 Constant *Elt = Init->getAggregateElement(i);
308 if (Elt == 0) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000309
Chris Lattner2188e402010-01-04 07:37:31 +0000310 // If this is indexing an array of structures, get the structure element.
311 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000312 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000313
Chris Lattner2188e402010-01-04 07:37:31 +0000314 // If the element is masked, handle it.
315 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000316
Chris Lattner2188e402010-01-04 07:37:31 +0000317 // Find out if the comparison would be true or false for the i'th element.
318 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chad Rosier43a33062011-12-02 01:26:24 +0000319 CompareRHS, TD, TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000320 // If the result is undef for this element, ignore it.
321 if (isa<UndefValue>(C)) {
322 // Extend range state machines to cover this element in case there is an
323 // undef in the middle of the range.
324 if (TrueRangeEnd == (int)i-1)
325 TrueRangeEnd = i;
326 if (FalseRangeEnd == (int)i-1)
327 FalseRangeEnd = i;
328 continue;
329 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000330
Chris Lattner2188e402010-01-04 07:37:31 +0000331 // If we can't compute the result for any of the elements, we have to give
332 // up evaluating the entire conditional.
333 if (!isa<ConstantInt>(C)) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000334
Chris Lattner2188e402010-01-04 07:37:31 +0000335 // Otherwise, we know if the comparison is true or false for this element,
336 // update our state machines.
337 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000338
Chris Lattner2188e402010-01-04 07:37:31 +0000339 // State machine for single/double/range index comparison.
340 if (IsTrueForElt) {
341 // Update the TrueElement state machine.
342 if (FirstTrueElement == Undefined)
343 FirstTrueElement = TrueRangeEnd = i; // First true element.
344 else {
345 // Update double-compare state machine.
346 if (SecondTrueElement == Undefined)
347 SecondTrueElement = i;
348 else
349 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000350
Chris Lattner2188e402010-01-04 07:37:31 +0000351 // Update range state machine.
352 if (TrueRangeEnd == (int)i-1)
353 TrueRangeEnd = i;
354 else
355 TrueRangeEnd = Overdefined;
356 }
357 } else {
358 // Update the FalseElement state machine.
359 if (FirstFalseElement == Undefined)
360 FirstFalseElement = FalseRangeEnd = i; // First false element.
361 else {
362 // Update double-compare state machine.
363 if (SecondFalseElement == Undefined)
364 SecondFalseElement = i;
365 else
366 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000367
Chris Lattner2188e402010-01-04 07:37:31 +0000368 // Update range state machine.
369 if (FalseRangeEnd == (int)i-1)
370 FalseRangeEnd = i;
371 else
372 FalseRangeEnd = Overdefined;
373 }
374 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000375
376
Chris Lattner2188e402010-01-04 07:37:31 +0000377 // If this element is in range, update our magic bitvector.
378 if (i < 64 && IsTrueForElt)
379 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000380
Chris Lattner2188e402010-01-04 07:37:31 +0000381 // If all of our states become overdefined, bail out early. Since the
382 // predicate is expensive, only check it every 8 elements. This is only
383 // really useful for really huge arrays.
384 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
385 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
386 FalseRangeEnd == Overdefined)
387 return 0;
388 }
389
390 // Now that we've scanned the entire array, emit our new comparison(s). We
391 // order the state machines in complexity of the generated code.
392 Value *Idx = GEP->getOperand(2);
393
Matt Arsenault5aeae182013-08-19 21:40:31 +0000394 // If the index is larger than the pointer size of the target, truncate the
395 // index down like the GEP would do implicitly. We don't have to do this for
396 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000397 if (!GEP->isInBounds()) {
398 Type *IntPtrTy = TD->getIntPtrType(GEP->getType());
399 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
400 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
401 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
402 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000403
Chris Lattner2188e402010-01-04 07:37:31 +0000404 // If the comparison is only true for one or two elements, emit direct
405 // comparisons.
406 if (SecondTrueElement != Overdefined) {
407 // None true -> false.
408 if (FirstTrueElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000409 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000410
Chris Lattner2188e402010-01-04 07:37:31 +0000411 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000412
Chris Lattner2188e402010-01-04 07:37:31 +0000413 // True for one element -> 'i == 47'.
414 if (SecondTrueElement == Undefined)
415 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000416
Chris Lattner2188e402010-01-04 07:37:31 +0000417 // True for two elements -> 'i == 47 | i == 72'.
418 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
419 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
420 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
421 return BinaryOperator::CreateOr(C1, C2);
422 }
423
424 // If the comparison is only false for one or two elements, emit direct
425 // comparisons.
426 if (SecondFalseElement != Overdefined) {
427 // None false -> true.
428 if (FirstFalseElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000429 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000430
Chris Lattner2188e402010-01-04 07:37:31 +0000431 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
432
433 // False for one element -> 'i != 47'.
434 if (SecondFalseElement == Undefined)
435 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000436
Chris Lattner2188e402010-01-04 07:37:31 +0000437 // False for two elements -> 'i != 47 & i != 72'.
438 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
439 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
440 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
441 return BinaryOperator::CreateAnd(C1, C2);
442 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000443
Chris Lattner2188e402010-01-04 07:37:31 +0000444 // If the comparison can be replaced with a range comparison for the elements
445 // where it is true, emit the range check.
446 if (TrueRangeEnd != Overdefined) {
447 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000448
Chris Lattner2188e402010-01-04 07:37:31 +0000449 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
450 if (FirstTrueElement) {
451 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
452 Idx = Builder->CreateAdd(Idx, Offs);
453 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000454
Chris Lattner2188e402010-01-04 07:37:31 +0000455 Value *End = ConstantInt::get(Idx->getType(),
456 TrueRangeEnd-FirstTrueElement+1);
457 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
458 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000459
Chris Lattner2188e402010-01-04 07:37:31 +0000460 // False range check.
461 if (FalseRangeEnd != Overdefined) {
462 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
463 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
464 if (FirstFalseElement) {
465 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
466 Idx = Builder->CreateAdd(Idx, Offs);
467 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000468
Chris Lattner2188e402010-01-04 07:37:31 +0000469 Value *End = ConstantInt::get(Idx->getType(),
470 FalseRangeEnd-FirstFalseElement);
471 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
472 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000473
474
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000475 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000476 // of this load, replace it with computation that does:
477 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000478 {
479 Type *Ty = 0;
480
481 // Look for an appropriate type:
482 // - The type of Idx if the magic fits
483 // - The smallest fitting legal type if we have a DataLayout
484 // - Default to i32
485 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
486 Ty = Idx->getType();
487 else if (TD)
488 Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
489 else if (ArrayElementCount <= 32)
Chris Lattner2188e402010-01-04 07:37:31 +0000490 Ty = Type::getInt32Ty(Init->getContext());
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000491
492 if (Ty != 0) {
493 Value *V = Builder->CreateIntCast(Idx, Ty, false);
494 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
495 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
496 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
497 }
Chris Lattner2188e402010-01-04 07:37:31 +0000498 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000499
Chris Lattner2188e402010-01-04 07:37:31 +0000500 return 0;
501}
502
503
504/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
505/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
506/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
507/// be complex, and scales are involved. The above expression would also be
508/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
509/// This later form is less amenable to optimization though, and we are allowed
510/// to generate the first by knowing that pointer arithmetic doesn't overflow.
511///
512/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000513///
Eli Friedman1754a252011-05-18 23:11:30 +0000514static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000515 DataLayout &TD = *IC.getDataLayout();
Chris Lattner2188e402010-01-04 07:37:31 +0000516 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000517
Chris Lattner2188e402010-01-04 07:37:31 +0000518 // Check to see if this gep only has a single variable index. If so, and if
519 // any constant indices are a multiple of its scale, then we can compute this
520 // in terms of the scale of the variable index. For example, if the GEP
521 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
522 // because the expression will cross zero at the same point.
523 unsigned i, e = GEP->getNumOperands();
524 int64_t Offset = 0;
525 for (i = 1; i != e; ++i, ++GTI) {
526 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
527 // Compute the aggregate offset of constant indices.
528 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000529
Chris Lattner2188e402010-01-04 07:37:31 +0000530 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000531 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner2188e402010-01-04 07:37:31 +0000532 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
533 } else {
534 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
535 Offset += Size*CI->getSExtValue();
536 }
537 } else {
538 // Found our variable index.
539 break;
540 }
541 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000542
Chris Lattner2188e402010-01-04 07:37:31 +0000543 // If there are no variable indices, we must have a constant offset, just
544 // evaluate it the general way.
545 if (i == e) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000546
Chris Lattner2188e402010-01-04 07:37:31 +0000547 Value *VariableIdx = GEP->getOperand(i);
548 // Determine the scale factor of the variable element. For example, this is
549 // 4 if the variable index is into an array of i32.
550 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000551
Chris Lattner2188e402010-01-04 07:37:31 +0000552 // Verify that there are no other variable indices. If so, emit the hard way.
553 for (++i, ++GTI; i != e; ++i, ++GTI) {
554 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
555 if (!CI) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000556
Chris Lattner2188e402010-01-04 07:37:31 +0000557 // Compute the aggregate offset of constant indices.
558 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000559
Chris Lattner2188e402010-01-04 07:37:31 +0000560 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000561 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner2188e402010-01-04 07:37:31 +0000562 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
563 } else {
564 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
565 Offset += Size*CI->getSExtValue();
566 }
567 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000568
Matt Arsenault745101d2013-08-21 19:53:10 +0000569
570
Chris Lattner2188e402010-01-04 07:37:31 +0000571 // Okay, we know we have a single variable index, which must be a
572 // pointer/array/vector index. If there is no offset, life is simple, return
573 // the index.
Matt Arsenault745101d2013-08-21 19:53:10 +0000574 Type *IntPtrTy = TD.getIntPtrType(GEP->getOperand(0)->getType());
575 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000576 if (Offset == 0) {
577 // Cast to intptrty in case a truncation occurs. If an extension is needed,
578 // we don't need to bother extending: the extension won't affect where the
579 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000580 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000581 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
582 }
Chris Lattner2188e402010-01-04 07:37:31 +0000583 return VariableIdx;
584 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000585
Chris Lattner2188e402010-01-04 07:37:31 +0000586 // Otherwise, there is an index. The computation we will do will be modulo
587 // the pointer size, so get it.
588 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000589
Chris Lattner2188e402010-01-04 07:37:31 +0000590 Offset &= PtrSizeMask;
591 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000592
Chris Lattner2188e402010-01-04 07:37:31 +0000593 // To do this transformation, any constant index must be a multiple of the
594 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
595 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
596 // multiple of the variable scale.
597 int64_t NewOffs = Offset / (int64_t)VariableScale;
598 if (Offset != NewOffs*(int64_t)VariableScale)
599 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000600
Chris Lattner2188e402010-01-04 07:37:31 +0000601 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000602 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000603 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
604 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000605 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000606 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000607}
608
609/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
610/// else. At this point we know that the GEP is on the LHS of the comparison.
611Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
612 ICmpInst::Predicate Cond,
613 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000614 // Don't transform signed compares of GEPs into index compares. Even if the
615 // GEP is inbounds, the final add of the base pointer can have signed overflow
616 // and would change the result of the icmp.
617 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000618 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000619 if (ICmpInst::isSigned(Cond))
620 return 0;
621
Chris Lattner2188e402010-01-04 07:37:31 +0000622 // Look through bitcasts.
623 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
624 RHS = BCI->getOperand(0);
625
626 Value *PtrBase = GEPLHS->getOperand(0);
627 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
628 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
629 // This transformation (ignoring the base and scales) is valid because we
630 // know pointers can't overflow since the gep is inbounds. See if we can
631 // output an optimized form.
Eli Friedman1754a252011-05-18 23:11:30 +0000632 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000633
Chris Lattner2188e402010-01-04 07:37:31 +0000634 // If not, synthesize the offset the hard way.
635 if (Offset == 0)
636 Offset = EmitGEPOffset(GEPLHS);
637 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
638 Constant::getNullValue(Offset->getType()));
639 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
640 // If the base pointers are different, but the indices are the same, just
641 // compare the base pointer.
642 if (PtrBase != GEPRHS->getOperand(0)) {
643 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
644 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
645 GEPRHS->getOperand(0)->getType();
646 if (IndicesTheSame)
647 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
648 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
649 IndicesTheSame = false;
650 break;
651 }
652
653 // If all indices are the same, just compare the base pointers.
654 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000655 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000656
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000657 // If we're comparing GEPs with two base pointers that only differ in type
658 // and both GEPs have only constant indices or just one use, then fold
659 // the compare with the adjusted indices.
Benjamin Kramerac8ecc42012-02-20 18:45:10 +0000660 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000661 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
662 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
663 PtrBase->stripPointerCasts() ==
664 GEPRHS->getOperand(0)->stripPointerCasts()) {
665 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
666 EmitGEPOffset(GEPLHS),
667 EmitGEPOffset(GEPRHS));
668 return ReplaceInstUsesWith(I, Cmp);
669 }
670
Chris Lattner2188e402010-01-04 07:37:31 +0000671 // Otherwise, the base pointers are different and the indices are
672 // different, bail out.
673 return 0;
674 }
675
676 // If one of the GEPs has all zero indices, recurse.
677 bool AllZeros = true;
678 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
679 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
680 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
681 AllZeros = false;
682 break;
683 }
684 if (AllZeros)
685 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +0000686 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +0000687
688 // If the other GEP has all zero indices, recurse.
689 AllZeros = true;
690 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
691 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
692 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
693 AllZeros = false;
694 break;
695 }
696 if (AllZeros)
697 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
698
Stuart Hastings66a82b92011-05-14 05:55:10 +0000699 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +0000700 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
701 // If the GEPs only differ by one index, compare it.
702 unsigned NumDifferences = 0; // Keep track of # differences.
703 unsigned DiffOperand = 0; // The operand that differs.
704 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
705 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
706 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
707 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
708 // Irreconcilable differences.
709 NumDifferences = 2;
710 break;
711 } else {
712 if (NumDifferences++) break;
713 DiffOperand = i;
714 }
715 }
716
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +0000717 if (NumDifferences == 0) // SAME GEP?
718 return ReplaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +0000719 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +0000720
Stuart Hastings66a82b92011-05-14 05:55:10 +0000721 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +0000722 Value *LHSV = GEPLHS->getOperand(DiffOperand);
723 Value *RHSV = GEPRHS->getOperand(DiffOperand);
724 // Make sure we do a signed comparison here.
725 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
726 }
727 }
728
729 // Only lower this if the icmp is the only user of the GEP or if we expect
730 // the result to fold to a constant!
731 if (TD &&
Stuart Hastings66a82b92011-05-14 05:55:10 +0000732 GEPsInBounds &&
Chris Lattner2188e402010-01-04 07:37:31 +0000733 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
734 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
735 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
736 Value *L = EmitGEPOffset(GEPLHS);
737 Value *R = EmitGEPOffset(GEPRHS);
738 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
739 }
740 }
741 return 0;
742}
743
744/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000745Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner2188e402010-01-04 07:37:31 +0000746 Value *X, ConstantInt *CI,
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000747 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000748 // If we have X+0, exit early (simplifying logic below) and let it get folded
749 // elsewhere. icmp X+0, X -> icmp X, X
750 if (CI->isZero()) {
751 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
752 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
753 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000754
Chris Lattner2188e402010-01-04 07:37:31 +0000755 // (X+4) == X -> false.
756 if (Pred == ICmpInst::ICMP_EQ)
Jakub Staszakbddea112013-06-06 20:18:46 +0000757 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +0000758
759 // (X+4) != X -> true.
760 if (Pred == ICmpInst::ICMP_NE)
Jakub Staszakbddea112013-06-06 20:18:46 +0000761 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000762
Chris Lattner2188e402010-01-04 07:37:31 +0000763 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000764 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +0000765 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000766
Chris Lattner8c92b572010-01-08 17:48:19 +0000767 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +0000768 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
769 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
770 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +0000771 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +0000772 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +0000773 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
774 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000775
Chris Lattner2188e402010-01-04 07:37:31 +0000776 // (X+1) >u X --> X <u (0-1) --> X != 255
777 // (X+2) >u X --> X <u (0-2) --> X <u 254
778 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +0000779 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +0000780 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000781
Chris Lattner2188e402010-01-04 07:37:31 +0000782 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
783 ConstantInt *SMax = ConstantInt::get(X->getContext(),
784 APInt::getSignedMaxValue(BitWidth));
785
786 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
787 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
788 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
789 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
790 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
791 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +0000792 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +0000793 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000794
Chris Lattner2188e402010-01-04 07:37:31 +0000795 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
796 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
797 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
798 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
799 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
800 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +0000801
Chris Lattner2188e402010-01-04 07:37:31 +0000802 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +0000803 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000804 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
805}
806
807/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
808/// and CmpRHS are both known to be integer constants.
809Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
810 ConstantInt *DivRHS) {
811 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
812 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000813
814 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +0000815 // then don't attempt this transform. The code below doesn't have the
816 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +0000817 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +0000818 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +0000819 // (x /u C1) <u C2. Simply casting the operands and result won't
820 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +0000821 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +0000822 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
823 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
824 return 0;
825 if (DivRHS->isZero())
826 return 0; // The ProdOV computation fails on divide by zero.
827 if (DivIsSigned && DivRHS->isAllOnesValue())
828 return 0; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +0000829 if (DivRHS->isOne()) {
830 // This eliminates some funny cases with INT_MIN.
831 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
832 return &ICI;
833 }
Chris Lattner2188e402010-01-04 07:37:31 +0000834
835 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +0000836 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
837 // C2 (CI). By solving for X we can turn this into a range check
838 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +0000839 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
840
841 // Determine if the product overflows by seeing if the product is
842 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +0000843 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +0000844 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
845 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
846
847 // Get the ICmp opcode
848 ICmpInst::Predicate Pred = ICI.getPredicate();
849
Chris Lattner98457102011-02-10 05:23:05 +0000850 /// If the division is known to be exact, then there is no remainder from the
851 /// divide, so the covered range size is unit, otherwise it is the divisor.
852 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000853
Chris Lattner2188e402010-01-04 07:37:31 +0000854 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +0000855 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +0000856 // Compute this interval based on the constants involved and the signedness of
857 // the compare/divide. This computes a half-open interval, keeping track of
858 // whether either value in the interval overflows. After analysis each
859 // overflow variable is set to 0 if it's corresponding bound variable is valid
860 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
861 int LoOverflow = 0, HiOverflow = 0;
862 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner98457102011-02-10 05:23:05 +0000863
Chris Lattner2188e402010-01-04 07:37:31 +0000864 if (!DivIsSigned) { // udiv
865 // e.g. X/5 op 3 --> [15, 20)
866 LoBound = Prod;
867 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +0000868 if (!HiOverflow) {
869 // If this is not an exact divide, then many values in the range collapse
870 // to the same result value.
871 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
872 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000873
Chris Lattner2188e402010-01-04 07:37:31 +0000874 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
875 if (CmpRHSV == 0) { // (X / pos) op 0
876 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +0000877 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
878 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +0000879 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
880 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
881 HiOverflow = LoOverflow = ProdOV;
882 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000883 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000884 } else { // (X / pos) op neg
885 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
886 HiBound = AddOne(Prod);
887 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
888 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +0000889 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000890 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +0000891 }
Chris Lattner2188e402010-01-04 07:37:31 +0000892 }
Chris Lattnerb1a15122011-07-15 06:08:15 +0000893 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +0000894 if (DivI->isExact())
895 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000896 if (CmpRHSV == 0) { // (X / neg) op 0
897 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +0000898 LoBound = AddOne(RangeSize);
899 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000900 if (HiBound == DivRHS) { // -INTMIN = INTMIN
901 HiOverflow = 1; // [INTMIN+1, overflow)
902 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
903 }
904 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
905 // e.g. X/-5 op 3 --> [-19, -14)
906 HiBound = AddOne(Prod);
907 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
908 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000909 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +0000910 } else { // (X / neg) op neg
911 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
912 LoOverflow = HiOverflow = ProdOV;
913 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000914 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000915 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000916
Chris Lattner2188e402010-01-04 07:37:31 +0000917 // Dividing by a negative swaps the condition. LT <-> GT
918 Pred = ICmpInst::getSwappedPredicate(Pred);
919 }
920
921 Value *X = DivI->getOperand(0);
922 switch (Pred) {
923 default: llvm_unreachable("Unhandled icmp opcode!");
924 case ICmpInst::ICMP_EQ:
925 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000926 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +0000927 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000928 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
929 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000930 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000931 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
932 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000933 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
934 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +0000935 case ICmpInst::ICMP_NE:
936 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000937 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +0000938 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000939 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
940 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000941 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000942 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
943 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000944 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
945 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +0000946 case ICmpInst::ICMP_ULT:
947 case ICmpInst::ICMP_SLT:
948 if (LoOverflow == +1) // Low bound is greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000949 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000950 if (LoOverflow == -1) // Low bound is less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000951 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +0000952 return new ICmpInst(Pred, X, LoBound);
953 case ICmpInst::ICMP_UGT:
954 case ICmpInst::ICMP_SGT:
955 if (HiOverflow == +1) // High bound greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000956 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +0000957 if (HiOverflow == -1) // High bound less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000958 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000959 if (Pred == ICmpInst::ICMP_UGT)
960 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000961 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +0000962 }
963}
964
Chris Lattnerd369f572011-02-13 07:43:07 +0000965/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
966Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
967 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +0000968 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000969
Chris Lattnerd369f572011-02-13 07:43:07 +0000970 // Check that the shift amount is in range. If not, don't perform
971 // undefined shifts. When the shift is visited it will be
972 // simplified.
973 uint32_t TypeBits = CmpRHSV.getBitWidth();
974 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +0000975 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattnerd369f572011-02-13 07:43:07 +0000976 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000977
Chris Lattner43273af2011-02-13 08:07:21 +0000978 if (!ICI.isEquality()) {
979 // If we have an unsigned comparison and an ashr, we can't simplify this.
980 // Similarly for signed comparisons with lshr.
981 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
982 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000983
Eli Friedman865866e2011-05-25 23:26:20 +0000984 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
985 // by a power of 2. Since we already have logic to simplify these,
986 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +0000987 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +0000988 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattner43273af2011-02-13 08:07:21 +0000989 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000990
Chris Lattner43273af2011-02-13 08:07:21 +0000991 // Revisit the shift (to delete it).
992 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000993
Chris Lattner43273af2011-02-13 08:07:21 +0000994 Constant *DivCst =
995 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000996
Chris Lattner43273af2011-02-13 08:07:21 +0000997 Value *Tmp =
998 Shr->getOpcode() == Instruction::AShr ?
999 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1000 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001001
Chris Lattner43273af2011-02-13 08:07:21 +00001002 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001003
Chris Lattner43273af2011-02-13 08:07:21 +00001004 // If the builder folded the binop, just return it.
1005 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1006 if (TheDiv == 0)
1007 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001008
Chris Lattner43273af2011-02-13 08:07:21 +00001009 // Otherwise, fold this div/compare.
1010 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1011 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001012
Chris Lattner43273af2011-02-13 08:07:21 +00001013 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1014 assert(Res && "This div/cst should have folded!");
1015 return Res;
1016 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001017
1018
Chris Lattnerd369f572011-02-13 07:43:07 +00001019 // If we are comparing against bits always shifted out, the
1020 // comparison cannot succeed.
1021 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001022 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001023 if (Shr->getOpcode() == Instruction::LShr)
1024 Comp = Comp.lshr(ShAmtVal);
1025 else
1026 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001027
Chris Lattnerd369f572011-02-13 07:43:07 +00001028 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1029 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001030 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattnerd369f572011-02-13 07:43:07 +00001031 return ReplaceInstUsesWith(ICI, Cst);
1032 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001033
Chris Lattnerd369f572011-02-13 07:43:07 +00001034 // Otherwise, check to see if the bits shifted out are known to be zero.
1035 // If so, we can compare against the unshifted value:
1036 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001037 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001038 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001039
Chris Lattnerd369f572011-02-13 07:43:07 +00001040 if (Shr->hasOneUse()) {
1041 // Otherwise strength reduce the shift into an and.
1042 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001043 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001044
Chris Lattnerd369f572011-02-13 07:43:07 +00001045 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1046 Mask, Shr->getName()+".mask");
1047 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1048 }
1049 return 0;
1050}
1051
Chris Lattner2188e402010-01-04 07:37:31 +00001052
1053/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1054///
1055Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1056 Instruction *LHSI,
1057 ConstantInt *RHS) {
1058 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001059
Chris Lattner2188e402010-01-04 07:37:31 +00001060 switch (LHSI->getOpcode()) {
1061 case Instruction::Trunc:
1062 if (ICI.isEquality() && LHSI->hasOneUse()) {
1063 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1064 // of the high bits truncated out of x are known.
1065 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1066 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001067 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001068 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001069
Chris Lattner2188e402010-01-04 07:37:31 +00001070 // If all the high bits are known, we can do this xform.
1071 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1072 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001073 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001074 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001075 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001076 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001077 }
1078 }
1079 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001080
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001081 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1082 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001083 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1084 // fold the xor.
1085 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1086 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1087 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001088
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001089 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001090 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001091 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001092 ICI.setOperand(0, CompareVal);
1093 Worklist.Add(LHSI);
1094 return &ICI;
1095 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001096
Chris Lattner2188e402010-01-04 07:37:31 +00001097 // Was the old condition true if the operand is positive?
1098 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001099
Chris Lattner2188e402010-01-04 07:37:31 +00001100 // If so, the new one isn't.
1101 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001102
Chris Lattner2188e402010-01-04 07:37:31 +00001103 if (isTrueIfPositive)
1104 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1105 SubOne(RHS));
1106 else
1107 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1108 AddOne(RHS));
1109 }
1110
1111 if (LHSI->hasOneUse()) {
1112 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001113 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1114 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001115 ICmpInst::Predicate Pred = ICI.isSigned()
1116 ? ICI.getUnsignedPredicate()
1117 : ICI.getSignedPredicate();
1118 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001119 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001120 }
1121
1122 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001123 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1124 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001125 ICmpInst::Predicate Pred = ICI.isSigned()
1126 ? ICI.getUnsignedPredicate()
1127 : ICI.getSignedPredicate();
1128 Pred = ICI.getSwappedPredicate(Pred);
1129 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001130 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001131 }
1132 }
David Majnemer72d76272013-07-09 09:20:58 +00001133
1134 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1135 // iff -C is a power of 2
1136 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001137 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1138 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001139
1140 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1141 // iff -C is a power of 2
1142 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001143 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1144 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001145 }
1146 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001147 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001148 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1149 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001150 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001151
Chris Lattner2188e402010-01-04 07:37:31 +00001152 // If the LHS is an AND of a truncating cast, we can widen the
1153 // and/compare to be the input width without changing the value
1154 // produced, eliminating a cast.
1155 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1156 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001157 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001158 // Extending a relational comparison when we're checking the sign
1159 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001160 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001161 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001162 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001163 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001164 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001165 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001166 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001167 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001168 }
1169 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001170
1171 // If the LHS is an AND of a zext, and we have an equality compare, we can
1172 // shrink the and/compare to the smaller type, eliminating the cast.
1173 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001174 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001175 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1176 // should fold the icmp to true/false in that case.
1177 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1178 Value *NewAnd =
1179 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001180 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001181 NewAnd->takeName(LHSI);
1182 return new ICmpInst(ICI.getPredicate(), NewAnd,
1183 ConstantExpr::getTrunc(RHS, Ty));
1184 }
1185 }
1186
Chris Lattner2188e402010-01-04 07:37:31 +00001187 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1188 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1189 // happens a LOT in code produced by the C front-end, for bitfield
1190 // access.
1191 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1192 if (Shift && !Shift->isShift())
1193 Shift = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001194
Chris Lattner2188e402010-01-04 07:37:31 +00001195 ConstantInt *ShAmt;
1196 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001197
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001198 // This seemingly simple opportunity to fold away a shift turns out to
1199 // be rather complicated. See PR17827
1200 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001201 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001202 bool CanFold = false;
1203 unsigned ShiftOpcode = Shift->getOpcode();
1204 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001205 // There may be some constraints that make this possible,
1206 // but nothing simple has been discovered yet.
1207 CanFold = false;
1208 } else if (ShiftOpcode == Instruction::Shl) {
1209 // For a left shift, we can fold if the comparison is not signed.
1210 // We can also fold a signed comparison if the mask value and
1211 // comparison value are not negative. These constraints may not be
1212 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001213 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001214 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001215 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001216 } else if (ShiftOpcode == Instruction::LShr) {
1217 // For a logical right shift, we can fold if the comparison is not
1218 // signed. We can also fold a signed comparison if the shifted mask
1219 // value and the shifted comparison value are not negative.
1220 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001221 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001222 if (!ICI.isSigned())
1223 CanFold = true;
1224 else {
1225 ConstantInt *ShiftedAndCst =
1226 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1227 ConstantInt *ShiftedRHSCst =
1228 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1229
1230 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1231 CanFold = true;
1232 }
Chris Lattner2188e402010-01-04 07:37:31 +00001233 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001234
Chris Lattner2188e402010-01-04 07:37:31 +00001235 if (CanFold) {
1236 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001237 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001238 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1239 else
1240 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001241
Chris Lattner2188e402010-01-04 07:37:31 +00001242 // Check to see if we are shifting out any of the bits being
1243 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001244 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001245 // If we shifted bits out, the fold is not going to work out.
1246 // As a special case, check to see if this means that the
1247 // result is always true or false now.
1248 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Jakub Staszakbddea112013-06-06 20:18:46 +00001249 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001250 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Jakub Staszakbddea112013-06-06 20:18:46 +00001251 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001252 } else {
1253 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001254 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001255 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001256 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001257 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001258 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1259 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001260 LHSI->setOperand(0, Shift->getOperand(0));
1261 Worklist.Add(Shift); // Shift is dead.
1262 return &ICI;
1263 }
1264 }
1265 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001266
Chris Lattner2188e402010-01-04 07:37:31 +00001267 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1268 // preferable because it allows the C<<Y expression to be hoisted out
1269 // of a loop if Y is invariant and X is not.
1270 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1271 ICI.isEquality() && !Shift->isArithmeticShift() &&
1272 !isa<Constant>(Shift->getOperand(0))) {
1273 // Compute C << Y.
1274 Value *NS;
1275 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001276 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001277 } else {
1278 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001279 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001280 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001281
Chris Lattner2188e402010-01-04 07:37:31 +00001282 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001283 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001284 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001285
Chris Lattner2188e402010-01-04 07:37:31 +00001286 ICI.setOperand(0, NewAnd);
1287 return &ICI;
1288 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001289
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001290 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1291 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001292 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001293 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1294 if ((NTZ < AndCst->getBitWidth()) &&
1295 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001296 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1297 Constant::getNullValue(RHS->getType()));
1298 }
Chris Lattner2188e402010-01-04 07:37:31 +00001299 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001300
Chris Lattner2188e402010-01-04 07:37:31 +00001301 // Try to optimize things like "A[i]&42 == 0" to index computations.
1302 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1303 if (GetElementPtrInst *GEP =
1304 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1305 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1306 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1307 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1308 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1309 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1310 return Res;
1311 }
1312 }
David Majnemer414d4e52013-07-09 08:09:32 +00001313
1314 // X & -C == -C -> X > u ~C
1315 // X & -C != -C -> X <= u ~C
1316 // iff C is a power of 2
1317 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1318 return new ICmpInst(
1319 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1320 : ICmpInst::ICMP_ULE,
1321 LHSI->getOperand(0), SubOne(RHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001322 break;
1323
1324 case Instruction::Or: {
1325 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1326 break;
1327 Value *P, *Q;
1328 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1329 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1330 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001331 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1332 Constant::getNullValue(P->getType()));
1333 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1334 Constant::getNullValue(Q->getType()));
1335 Instruction *Op;
1336 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1337 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1338 else
1339 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1340 return Op;
1341 }
1342 break;
1343 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001344
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001345 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1346 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1347 if (!Val) break;
1348
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001349 // If this is a signed comparison to 0 and the mul is sign preserving,
1350 // use the mul LHS operand instead.
1351 ICmpInst::Predicate pred = ICI.getPredicate();
1352 if (isSignTest(pred, RHS) && !Val->isZero() &&
1353 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1354 return new ICmpInst(Val->isNegative() ?
1355 ICmpInst::getSwappedPredicate(pred) : pred,
1356 LHSI->getOperand(0),
1357 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001358
1359 break;
1360 }
1361
Chris Lattner2188e402010-01-04 07:37:31 +00001362 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001363 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001364 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1365 if (!ShAmt) {
1366 Value *X;
1367 // (1 << X) pred P2 -> X pred Log2(P2)
1368 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1369 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1370 ICmpInst::Predicate Pred = ICI.getPredicate();
1371 if (ICI.isUnsigned()) {
1372 if (!RHSVIsPowerOf2) {
1373 // (1 << X) < 30 -> X <= 4
1374 // (1 << X) <= 30 -> X <= 4
1375 // (1 << X) >= 30 -> X > 4
1376 // (1 << X) > 30 -> X > 4
1377 if (Pred == ICmpInst::ICMP_ULT)
1378 Pred = ICmpInst::ICMP_ULE;
1379 else if (Pred == ICmpInst::ICMP_UGE)
1380 Pred = ICmpInst::ICMP_UGT;
1381 }
1382 unsigned RHSLog2 = RHSV.logBase2();
1383
1384 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1385 // (1 << X) > 2147483648 -> X > 31 -> false
1386 // (1 << X) <= 2147483648 -> X <= 31 -> true
1387 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1388 if (RHSLog2 == TypeBits-1) {
1389 if (Pred == ICmpInst::ICMP_UGE)
1390 Pred = ICmpInst::ICMP_EQ;
1391 else if (Pred == ICmpInst::ICMP_UGT)
1392 return ReplaceInstUsesWith(ICI, Builder->getFalse());
1393 else if (Pred == ICmpInst::ICMP_ULE)
1394 return ReplaceInstUsesWith(ICI, Builder->getTrue());
1395 else if (Pred == ICmpInst::ICMP_ULT)
1396 Pred = ICmpInst::ICMP_NE;
1397 }
1398
1399 return new ICmpInst(Pred, X,
1400 ConstantInt::get(RHS->getType(), RHSLog2));
1401 } else if (ICI.isSigned()) {
1402 if (RHSV.isAllOnesValue()) {
1403 // (1 << X) <= -1 -> X == 31
1404 if (Pred == ICmpInst::ICMP_SLE)
1405 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1406 ConstantInt::get(RHS->getType(), TypeBits-1));
1407
1408 // (1 << X) > -1 -> X != 31
1409 if (Pred == ICmpInst::ICMP_SGT)
1410 return new ICmpInst(ICmpInst::ICMP_NE, X,
1411 ConstantInt::get(RHS->getType(), TypeBits-1));
1412 } else if (!RHSV) {
1413 // (1 << X) < 0 -> X == 31
1414 // (1 << X) <= 0 -> X == 31
1415 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1416 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1417 ConstantInt::get(RHS->getType(), TypeBits-1));
1418
1419 // (1 << X) >= 0 -> X != 31
1420 // (1 << X) > 0 -> X != 31
1421 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1422 return new ICmpInst(ICmpInst::ICMP_NE, X,
1423 ConstantInt::get(RHS->getType(), TypeBits-1));
1424 }
1425 } else if (ICI.isEquality()) {
1426 if (RHSVIsPowerOf2)
1427 return new ICmpInst(
1428 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1429
1430 return ReplaceInstUsesWith(
1431 ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
1432 : Builder->getTrue());
1433 }
1434 }
1435 break;
1436 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001437
Chris Lattner2188e402010-01-04 07:37:31 +00001438 // Check that the shift amount is in range. If not, don't perform
1439 // undefined shifts. When the shift is visited it will be
1440 // simplified.
1441 if (ShAmt->uge(TypeBits))
1442 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001443
Chris Lattner2188e402010-01-04 07:37:31 +00001444 if (ICI.isEquality()) {
1445 // If we are comparing against bits always shifted out, the
1446 // comparison cannot succeed.
1447 Constant *Comp =
1448 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1449 ShAmt);
1450 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1451 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001452 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner2188e402010-01-04 07:37:31 +00001453 return ReplaceInstUsesWith(ICI, Cst);
1454 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001455
Chris Lattner98457102011-02-10 05:23:05 +00001456 // If the shift is NUW, then it is just shifting out zeros, no need for an
1457 // AND.
1458 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1459 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1460 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001461
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001462 // If the shift is NSW and we compare to 0, then it is just shifting out
1463 // sign bits, no need for an AND either.
1464 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1465 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1466 ConstantExpr::getLShr(RHS, ShAmt));
1467
Chris Lattner2188e402010-01-04 07:37:31 +00001468 if (LHSI->hasOneUse()) {
1469 // Otherwise strength reduce the shift into an and.
1470 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00001471 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1472 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001473
Chris Lattner2188e402010-01-04 07:37:31 +00001474 Value *And =
1475 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1476 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00001477 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00001478 }
1479 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001480
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001481 // If this is a signed comparison to 0 and the shift is sign preserving,
1482 // use the shift LHS operand instead.
1483 ICmpInst::Predicate pred = ICI.getPredicate();
1484 if (isSignTest(pred, RHS) &&
1485 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1486 return new ICmpInst(pred,
1487 LHSI->getOperand(0),
1488 Constant::getNullValue(RHS->getType()));
1489
Chris Lattner2188e402010-01-04 07:37:31 +00001490 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1491 bool TrueIfSigned = false;
1492 if (LHSI->hasOneUse() &&
1493 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1494 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00001495 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00001496 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00001497 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00001498 Value *And =
1499 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1500 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1501 And, Constant::getNullValue(And->getType()));
1502 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001503
1504 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001505 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1506 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001507 // This enables to get rid of the shift in favor of a trunc which can be
1508 // free on the target. It has the additional benefit of comparing to a
1509 // smaller constant, which will be target friendly.
1510 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001511 if (LHSI->hasOneUse() &&
1512 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001513 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1514 Constant *NCI = ConstantExpr::getTrunc(
1515 ConstantExpr::getAShr(RHS,
1516 ConstantInt::get(RHS->getType(), Amt)),
1517 NTy);
1518 return new ICmpInst(ICI.getPredicate(),
1519 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00001520 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001521 }
1522
Chris Lattner2188e402010-01-04 07:37:31 +00001523 break;
1524 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001525
Chris Lattner2188e402010-01-04 07:37:31 +00001526 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00001527 case Instruction::AShr: {
1528 // Handle equality comparisons of shift-by-constant.
1529 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1530 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1531 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00001532 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00001533 }
1534
1535 // Handle exact shr's.
1536 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1537 if (RHSV.isMinValue())
1538 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1539 }
Chris Lattner2188e402010-01-04 07:37:31 +00001540 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00001541 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001542
Chris Lattner2188e402010-01-04 07:37:31 +00001543 case Instruction::SDiv:
1544 case Instruction::UDiv:
1545 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00001546 // Fold this div into the comparison, producing a range check.
1547 // Determine, based on the divide type, what the range is being
1548 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00001549 // it, otherwise compute the range [low, hi) bounding the new value.
1550 // See: InsertRangeTest above for the kinds of replacements possible.
1551 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1552 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1553 DivRHS))
1554 return R;
1555 break;
1556
David Majnemerf2a9a512013-07-09 07:50:59 +00001557 case Instruction::Sub: {
1558 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1559 if (!LHSC) break;
1560 const APInt &LHSV = LHSC->getValue();
1561
1562 // C1-X <u C2 -> (X|(C2-1)) == C1
1563 // iff C1 & (C2-1) == C2-1
1564 // C2 is a power of 2
1565 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1566 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1567 return new ICmpInst(ICmpInst::ICMP_EQ,
1568 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1569 LHSC);
1570
David Majnemereeed73b2013-07-09 09:24:35 +00001571 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00001572 // iff C1 & C2 == C2
1573 // C2+1 is a power of 2
1574 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1575 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1576 return new ICmpInst(ICmpInst::ICMP_NE,
1577 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1578 break;
1579 }
1580
Chris Lattner2188e402010-01-04 07:37:31 +00001581 case Instruction::Add:
1582 // Fold: icmp pred (add X, C1), C2
1583 if (!ICI.isEquality()) {
1584 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1585 if (!LHSC) break;
1586 const APInt &LHSV = LHSC->getValue();
1587
1588 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1589 .subtract(LHSV);
1590
1591 if (ICI.isSigned()) {
1592 if (CR.getLower().isSignBit()) {
1593 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001594 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001595 } else if (CR.getUpper().isSignBit()) {
1596 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001597 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001598 }
1599 } else {
1600 if (CR.getLower().isMinValue()) {
1601 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001602 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001603 } else if (CR.getUpper().isMinValue()) {
1604 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001605 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001606 }
1607 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00001608
David Majnemerbafa5372013-07-09 07:58:32 +00001609 // X-C1 <u C2 -> (X & -C2) == C1
1610 // iff C1 & (C2-1) == 0
1611 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00001612 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00001613 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00001614 return new ICmpInst(ICmpInst::ICMP_EQ,
1615 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1616 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00001617
David Majnemereeed73b2013-07-09 09:24:35 +00001618 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00001619 // iff C1 & C2 == 0
1620 // C2+1 is a power of 2
1621 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1622 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1623 return new ICmpInst(ICmpInst::ICMP_NE,
1624 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1625 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00001626 }
1627 break;
1628 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001629
Chris Lattner2188e402010-01-04 07:37:31 +00001630 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1631 if (ICI.isEquality()) {
1632 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001633
1634 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner2188e402010-01-04 07:37:31 +00001635 // the second operand is a constant, simplify a bit.
1636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1637 switch (BO->getOpcode()) {
1638 case Instruction::SRem:
1639 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1640 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1641 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohman4ce1fb12010-04-08 23:03:40 +00001642 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001643 Value *NewRem =
1644 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1645 BO->getName());
1646 return new ICmpInst(ICI.getPredicate(), NewRem,
1647 Constant::getNullValue(BO->getType()));
1648 }
1649 }
1650 break;
1651 case Instruction::Add:
1652 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1653 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1654 if (BO->hasOneUse())
1655 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1656 ConstantExpr::getSub(RHS, BOp1C));
1657 } else if (RHSV == 0) {
1658 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1659 // efficiently invertible, or if the add has just this one use.
1660 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001661
Chris Lattner2188e402010-01-04 07:37:31 +00001662 if (Value *NegVal = dyn_castNegVal(BOp1))
1663 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner31b106d2011-04-26 20:02:45 +00001664 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner2188e402010-01-04 07:37:31 +00001665 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner31b106d2011-04-26 20:02:45 +00001666 if (BO->hasOneUse()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001667 Value *Neg = Builder->CreateNeg(BOp1);
1668 Neg->takeName(BO);
1669 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1670 }
1671 }
1672 break;
1673 case Instruction::Xor:
1674 // For the xor case, we can xor two constants together, eliminating
1675 // the explicit xor.
Benjamin Kramerc9708492011-06-13 15:24:24 +00001676 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1677 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner2188e402010-01-04 07:37:31 +00001678 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001679 } else if (RHSV == 0) {
1680 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner2188e402010-01-04 07:37:31 +00001681 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1682 BO->getOperand(1));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001683 }
Chris Lattner2188e402010-01-04 07:37:31 +00001684 break;
Benjamin Kramerc9708492011-06-13 15:24:24 +00001685 case Instruction::Sub:
1686 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1687 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1688 if (BO->hasOneUse())
1689 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1690 ConstantExpr::getSub(BOp0C, RHS));
1691 } else if (RHSV == 0) {
1692 // Replace ((sub A, B) != 0) with (A != B)
1693 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1694 BO->getOperand(1));
1695 }
1696 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001697 case Instruction::Or:
1698 // If bits are being or'd in that are not present in the constant we
1699 // are comparing against, then the comparison could never succeed!
Eli Friedman0428a612010-07-29 18:03:33 +00001700 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001701 Constant *NotCI = ConstantExpr::getNot(RHS);
1702 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Jakub Staszakbddea112013-06-06 20:18:46 +00001703 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Chris Lattner2188e402010-01-04 07:37:31 +00001704 }
1705 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001706
Chris Lattner2188e402010-01-04 07:37:31 +00001707 case Instruction::And:
1708 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1709 // If bits are being compared against that are and'd out, then the
1710 // comparison can never succeed!
1711 if ((RHSV & ~BOC->getValue()) != 0)
Jakub Staszakbddea112013-06-06 20:18:46 +00001712 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001713
Chris Lattner2188e402010-01-04 07:37:31 +00001714 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1715 if (RHS == BOC && RHSV.isPowerOf2())
1716 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1717 ICmpInst::ICMP_NE, LHSI,
1718 Constant::getNullValue(RHS->getType()));
Benjamin Kramer9eca5fe2011-07-04 20:16:36 +00001719
1720 // Don't perform the following transforms if the AND has multiple uses
1721 if (!BO->hasOneUse())
1722 break;
1723
Chris Lattner2188e402010-01-04 07:37:31 +00001724 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1725 if (BOC->getValue().isSignBit()) {
1726 Value *X = BO->getOperand(0);
1727 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001728 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001729 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1730 return new ICmpInst(pred, X, Zero);
1731 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001732
Chris Lattner2188e402010-01-04 07:37:31 +00001733 // ((X & ~7) == 0) --> X < 8
1734 if (RHSV == 0 && isHighOnes(BOC)) {
1735 Value *X = BO->getOperand(0);
1736 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001737 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001738 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1739 return new ICmpInst(pred, X, NegX);
1740 }
1741 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001742 break;
1743 case Instruction::Mul:
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001744 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001745 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1746 // The trivial case (mul X, 0) is handled by InstSimplify
1747 // General case : (mul X, C) != 0 iff X != 0
1748 // (mul X, C) == 0 iff X == 0
1749 if (!BOC->isZero())
1750 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1751 Constant::getNullValue(RHS->getType()));
1752 }
1753 }
1754 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001755 default: break;
1756 }
1757 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1758 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner54f4e392010-01-05 18:09:56 +00001759 switch (II->getIntrinsicID()) {
1760 case Intrinsic::bswap:
Chris Lattner2188e402010-01-04 07:37:31 +00001761 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001762 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszakbddea112013-06-06 20:18:46 +00001763 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner2188e402010-01-04 07:37:31 +00001764 return &ICI;
Chris Lattner54f4e392010-01-05 18:09:56 +00001765 case Intrinsic::ctlz:
1766 case Intrinsic::cttz:
1767 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1768 if (RHSV == RHS->getType()->getBitWidth()) {
1769 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001770 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001771 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1772 return &ICI;
1773 }
1774 break;
1775 case Intrinsic::ctpop:
1776 // popcount(A) == 0 -> A == 0 and likewise for !=
1777 if (RHS->isZero()) {
1778 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001779 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001780 ICI.setOperand(1, RHS);
1781 return &ICI;
1782 }
1783 break;
1784 default:
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001785 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001786 }
1787 }
1788 }
1789 return 0;
1790}
1791
1792/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1793/// We only handle extending casts so far.
1794///
1795Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1796 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1797 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001798 Type *SrcTy = LHSCIOp->getType();
1799 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00001800 Value *RHSCIOp;
1801
Jim Grosbach129c52a2011-09-30 18:09:53 +00001802 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00001803 // integer type is the same size as the pointer type.
1804 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
Matt Arsenault06adeca2013-09-30 21:06:18 +00001805 TD->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001806 Value *RHSOp = 0;
1807 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1808 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1809 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1810 RHSOp = RHSC->getOperand(0);
1811 // If the pointer types don't match, insert a bitcast.
1812 if (LHSCIOp->getType() != RHSOp->getType())
1813 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1814 }
1815
1816 if (RHSOp)
1817 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1818 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001819
Chris Lattner2188e402010-01-04 07:37:31 +00001820 // The code below only handles extension cast instructions, so far.
1821 // Enforce this.
1822 if (LHSCI->getOpcode() != Instruction::ZExt &&
1823 LHSCI->getOpcode() != Instruction::SExt)
1824 return 0;
1825
1826 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1827 bool isSignedCmp = ICI.isSigned();
1828
1829 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1830 // Not an extension from the same type?
1831 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001832 if (RHSCIOp->getType() != LHSCIOp->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00001833 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001834
Chris Lattner2188e402010-01-04 07:37:31 +00001835 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1836 // and the other is a zext), then we can't handle this.
1837 if (CI->getOpcode() != LHSCI->getOpcode())
1838 return 0;
1839
1840 // Deal with equality cases early.
1841 if (ICI.isEquality())
1842 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1843
1844 // A signed comparison of sign extended values simplifies into a
1845 // signed comparison.
1846 if (isSignedCmp && isSignedExt)
1847 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1848
1849 // The other three cases all fold into an unsigned comparison.
1850 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1851 }
1852
1853 // If we aren't dealing with a constant on the RHS, exit early
1854 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1855 if (!CI)
1856 return 0;
1857
1858 // Compute the constant that would happen if we truncated to SrcTy then
1859 // reextended to DestTy.
1860 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1861 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1862 Res1, DestTy);
1863
1864 // If the re-extended constant didn't change...
1865 if (Res2 == CI) {
1866 // Deal with equality cases early.
1867 if (ICI.isEquality())
1868 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1869
1870 // A signed comparison of sign extended values simplifies into a
1871 // signed comparison.
1872 if (isSignedExt && isSignedCmp)
1873 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1874
1875 // The other three cases all fold into an unsigned comparison.
1876 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1877 }
1878
Jim Grosbach129c52a2011-09-30 18:09:53 +00001879 // The re-extended constant changed so the constant cannot be represented
Chris Lattner2188e402010-01-04 07:37:31 +00001880 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00001881 // All the cases that fold to true or false will have already been handled
1882 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00001883
Duncan Sands8fb2c382011-01-20 13:21:55 +00001884 if (isSignedCmp || !isSignedExt)
1885 return 0;
Chris Lattner2188e402010-01-04 07:37:31 +00001886
1887 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1888 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00001889
1890 // We're performing an unsigned comp with a sign extended value.
1891 // This is true if the input is >= 0. [aka >s -1]
1892 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1893 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00001894
1895 // Finally, return the value computed.
Duncan Sands8fb2c382011-01-20 13:21:55 +00001896 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner2188e402010-01-04 07:37:31 +00001897 return ReplaceInstUsesWith(ICI, Result);
1898
Duncan Sands8fb2c382011-01-20 13:21:55 +00001899 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00001900 return BinaryOperator::CreateNot(Result);
1901}
1902
Chris Lattneree61c1d2010-12-19 17:52:50 +00001903/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1904/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00001905/// If this is of the form:
1906/// sum = a + b
1907/// if (sum+128 >u 255)
1908/// Then replace it with llvm.sadd.with.overflow.i8.
1909///
Chris Lattneree61c1d2010-12-19 17:52:50 +00001910static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1911 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00001912 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00001913 // The transformation we're trying to do here is to transform this into an
1914 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1915 // with a narrower add, and discard the add-with-constant that is part of the
1916 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001917
Chris Lattnerf29562d2010-12-19 17:59:02 +00001918 // In order to eliminate the add-with-constant, the compare can be its only
1919 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00001920 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattnerf29562d2010-12-19 17:59:02 +00001921 if (!AddWithCst->hasOneUse()) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001922
Chris Lattnerc56c8452010-12-19 18:22:06 +00001923 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1924 if (!CI2->getValue().isPowerOf2()) return 0;
1925 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1926 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001927
Chris Lattnerc56c8452010-12-19 18:22:06 +00001928 // The width of the new add formed is 1 more than the bias.
1929 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001930
Chris Lattnerc56c8452010-12-19 18:22:06 +00001931 // Check to see that CI1 is an all-ones value with NewWidth bits.
1932 if (CI1->getBitWidth() == NewWidth ||
1933 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1934 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001935
Eli Friedmanb3f9b062011-11-28 23:32:19 +00001936 // This is only really a signed overflow check if the inputs have been
1937 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1938 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1939 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1940 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1941 IC.ComputeNumSignBits(B) < NeededSignBits)
1942 return 0;
1943
Jim Grosbach129c52a2011-09-30 18:09:53 +00001944 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00001945 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1946 // and truncates that discard the high bits of the add. Verify that this is
1947 // the case.
1948 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1949 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1950 UI != E; ++UI) {
1951 if (*UI == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001952
Chris Lattnerc56c8452010-12-19 18:22:06 +00001953 // Only accept truncates for now. We would really like a nice recursive
1954 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1955 // chain to see which bits of a value are actually demanded. If the
1956 // original add had another add which was then immediately truncated, we
1957 // could still do the transformation.
1958 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1959 if (TI == 0 ||
1960 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1961 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001962
Chris Lattneree61c1d2010-12-19 17:52:50 +00001963 // If the pattern matches, truncate the inputs to the narrower type and
1964 // use the sadd_with_overflow intrinsic to efficiently compute both the
1965 // result and the overflow bit.
Chris Lattner79874562010-12-19 18:35:09 +00001966 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001967
Jay Foadb804a2b2011-07-12 14:06:48 +00001968 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner79874562010-12-19 18:35:09 +00001969 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramere6e19332011-07-14 17:45:39 +00001970 NewType);
Chris Lattner79874562010-12-19 18:35:09 +00001971
Chris Lattnerce2995a2010-12-19 18:38:44 +00001972 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001973
Chris Lattner79874562010-12-19 18:35:09 +00001974 // Put the new code above the original add, in case there are any uses of the
1975 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00001976 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001977
Chris Lattner79874562010-12-19 18:35:09 +00001978 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1979 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1980 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1981 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1982 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001983
Chris Lattneree61c1d2010-12-19 17:52:50 +00001984 // The inner add was the result of the narrow add, zero extended to the
1985 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattnerce2995a2010-12-19 18:38:44 +00001986 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001987
Chris Lattner79874562010-12-19 18:35:09 +00001988 // The original icmp gets replaced with the overflow value.
1989 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00001990}
Chris Lattner2188e402010-01-04 07:37:31 +00001991
Chris Lattner5e0c0c72010-12-19 19:37:52 +00001992static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1993 InstCombiner &IC) {
1994 // Don't bother doing this transformation for pointers, don't do it for
1995 // vectors.
1996 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001997
Chris Lattner5e0c0c72010-12-19 19:37:52 +00001998 // If the add is a constant expr, then we don't bother transforming it.
1999 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
2000 if (OrigAdd == 0) return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002001
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002002 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002003
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002004 // Put the new code above the original add, in case there are any uses of the
2005 // add between the add and the compare.
2006 InstCombiner::BuilderTy *Builder = IC.Builder;
2007 Builder->SetInsertPoint(OrigAdd);
2008
2009 Module *M = I.getParent()->getParent()->getParent();
Jay Foadb804a2b2011-07-12 14:06:48 +00002010 Type *Ty = LHS->getType();
Benjamin Kramere6e19332011-07-14 17:45:39 +00002011 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002012 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
2013 Value *Add = Builder->CreateExtractValue(Call, 0);
2014
2015 IC.ReplaceInstUsesWith(*OrigAdd, Add);
2016
2017 // The original icmp gets replaced with the overflow value.
2018 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2019}
2020
Owen Andersond490c2d2011-01-11 00:36:45 +00002021// DemandedBitsLHSMask - When performing a comparison against a constant,
2022// it is possible that not all the bits in the LHS are demanded. This helper
2023// method computes the mask that IS demanded.
2024static APInt DemandedBitsLHSMask(ICmpInst &I,
2025 unsigned BitWidth, bool isSignCheck) {
2026 if (isSignCheck)
2027 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002028
Owen Andersond490c2d2011-01-11 00:36:45 +00002029 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2030 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002031 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002032
Owen Andersond490c2d2011-01-11 00:36:45 +00002033 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002034 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002035 // correspond to the trailing ones of the comparand. The value of these
2036 // bits doesn't impact the outcome of the comparison, because any value
2037 // greater than the RHS must differ in a bit higher than these due to carry.
2038 case ICmpInst::ICMP_UGT: {
2039 unsigned trailingOnes = RHS.countTrailingOnes();
2040 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2041 return ~lowBitsSet;
2042 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002043
Owen Andersond490c2d2011-01-11 00:36:45 +00002044 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2045 // Any value less than the RHS must differ in a higher bit because of carries.
2046 case ICmpInst::ICMP_ULT: {
2047 unsigned trailingZeros = RHS.countTrailingZeros();
2048 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2049 return ~lowBitsSet;
2050 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002051
Owen Andersond490c2d2011-01-11 00:36:45 +00002052 default:
2053 return APInt::getAllOnesValue(BitWidth);
2054 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002055
Owen Andersond490c2d2011-01-11 00:36:45 +00002056}
Chris Lattner2188e402010-01-04 07:37:31 +00002057
Quentin Colombet5ab55552013-09-09 20:56:48 +00002058/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2059/// should be swapped.
2060/// The descision is based on how many times these two operands are reused
2061/// as subtract operands and their positions in those instructions.
2062/// The rational is that several architectures use the same instruction for
2063/// both subtract and cmp, thus it is better if the order of those operands
2064/// match.
2065/// \return true if Op0 and Op1 should be swapped.
2066static bool swapMayExposeCSEOpportunities(const Value * Op0,
2067 const Value * Op1) {
2068 // Filter out pointer value as those cannot appears directly in subtract.
2069 // FIXME: we may want to go through inttoptrs or bitcasts.
2070 if (Op0->getType()->isPointerTy())
2071 return false;
2072 // Count every uses of both Op0 and Op1 in a subtract.
2073 // Each time Op0 is the first operand, count -1: swapping is bad, the
2074 // subtract has already the same layout as the compare.
2075 // Each time Op0 is the second operand, count +1: swapping is good, the
2076 // subtract has a diffrent layout as the compare.
2077 // At the end, if the benefit is greater than 0, Op0 should come second to
2078 // expose more CSE opportunities.
2079 int GlobalSwapBenefits = 0;
2080 for (Value::const_use_iterator UI = Op0->use_begin(), UIEnd = Op0->use_end(); UI != UIEnd; ++UI) {
2081 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(*UI);
2082 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2083 continue;
2084 // If Op0 is the first argument, this is not beneficial to swap the
2085 // arguments.
2086 int LocalSwapBenefits = -1;
2087 unsigned Op1Idx = 1;
2088 if (BinOp->getOperand(Op1Idx) == Op0) {
2089 Op1Idx = 0;
2090 LocalSwapBenefits = 1;
2091 }
2092 if (BinOp->getOperand(Op1Idx) != Op1)
2093 continue;
2094 GlobalSwapBenefits += LocalSwapBenefits;
2095 }
2096 return GlobalSwapBenefits > 0;
2097}
2098
Chris Lattner2188e402010-01-04 07:37:31 +00002099Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2100 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00002101 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002102 unsigned Op0Cplxity = getComplexity(Op0);
2103 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002104
Chris Lattner2188e402010-01-04 07:37:31 +00002105 /// Orders the operands of the compare so that they are listed from most
2106 /// complex to least complex. This puts constants before unary operators,
2107 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002108 if (Op0Cplxity < Op1Cplxity ||
2109 (Op0Cplxity == Op1Cplxity &&
2110 swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002111 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00002112 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002113 Changed = true;
2114 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002115
Chris Lattner2188e402010-01-04 07:37:31 +00002116 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
2117 return ReplaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002118
Pete Cooperbc5c5242011-12-01 03:58:40 +00002119 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00002120 // ie, abs(val) != 0 -> val != 0
Pete Cooperbc5c5242011-12-01 03:58:40 +00002121 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2122 {
Pete Cooperfdddc272011-12-01 19:13:26 +00002123 Value *Cond, *SelectTrue, *SelectFalse;
2124 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00002125 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00002126 if (Value *V = dyn_castNegVal(SelectTrue)) {
2127 if (V == SelectFalse)
2128 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2129 }
2130 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2131 if (V == SelectTrue)
2132 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00002133 }
2134 }
2135 }
2136
Chris Lattner229907c2011-07-18 04:54:35 +00002137 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002138
2139 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sands9dff9be2010-02-15 16:12:20 +00002140 if (Ty->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00002141 switch (I.getPredicate()) {
2142 default: llvm_unreachable("Invalid icmp instruction!");
2143 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2144 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2145 return BinaryOperator::CreateNot(Xor);
2146 }
2147 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2148 return BinaryOperator::CreateXor(Op0, Op1);
2149
2150 case ICmpInst::ICMP_UGT:
2151 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2152 // FALL THROUGH
2153 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2154 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2155 return BinaryOperator::CreateAnd(Not, Op1);
2156 }
2157 case ICmpInst::ICMP_SGT:
2158 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2159 // FALL THROUGH
2160 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2161 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2162 return BinaryOperator::CreateAnd(Not, Op0);
2163 }
2164 case ICmpInst::ICMP_UGE:
2165 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2166 // FALL THROUGH
2167 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2168 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2169 return BinaryOperator::CreateOr(Not, Op1);
2170 }
2171 case ICmpInst::ICMP_SGE:
2172 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2173 // FALL THROUGH
2174 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2175 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2176 return BinaryOperator::CreateOr(Not, Op0);
2177 }
2178 }
2179 }
2180
2181 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002182 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00002183 BitWidth = Ty->getScalarSizeInBits();
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002184 else if (TD) // Pointers require TD info to get their size.
2185 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002186
Chris Lattner2188e402010-01-04 07:37:31 +00002187 bool isSignBit = false;
2188
2189 // See if we are doing a comparison with a constant.
2190 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2191 Value *A = 0, *B = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002192
Owen Anderson1294ea72010-12-17 18:08:00 +00002193 // Match the following pattern, which is a common idiom when writing
2194 // overflow-safe integer arithmetic function. The source performs an
2195 // addition in wider type, and explicitly checks for overflow using
2196 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2197 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00002198 //
2199 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00002200 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00002201 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00002202 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00002203 // sum = a + b
2204 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00002205 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00002206 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00002207 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00002208 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00002209 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00002210 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00002211 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002212
Chris Lattner2188e402010-01-04 07:37:31 +00002213 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2214 if (I.isEquality() && CI->isZero() &&
2215 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2216 // (icmp cond A B) if cond is equality
2217 return new ICmpInst(I.getPredicate(), A, B);
2218 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002219
Chris Lattner2188e402010-01-04 07:37:31 +00002220 // If we have an icmp le or icmp ge instruction, turn it into the
2221 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2222 // them being folded in the code below. The SimplifyICmpInst code has
2223 // already handled the edge cases for us, so we just assert on them.
2224 switch (I.getPredicate()) {
2225 default: break;
2226 case ICmpInst::ICMP_ULE:
2227 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2228 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002229 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002230 case ICmpInst::ICMP_SLE:
2231 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2232 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002233 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002234 case ICmpInst::ICMP_UGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002235 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002236 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002237 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002238 case ICmpInst::ICMP_SGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002239 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002240 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002241 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002242 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002243
Chris Lattner2188e402010-01-04 07:37:31 +00002244 // If this comparison is a normal comparison, it demands all
2245 // bits, if it is a sign bit comparison, it only demands the sign bit.
2246 bool UnusedBit;
2247 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2248 }
2249
2250 // See if we can fold the comparison based on range information we can get
2251 // by checking whether bits are known to be zero or one in the input.
2252 if (BitWidth != 0) {
2253 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2254 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2255
2256 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00002257 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00002258 Op0KnownZero, Op0KnownOne, 0))
2259 return &I;
2260 if (SimplifyDemandedBits(I.getOperandUse(1),
2261 APInt::getAllOnesValue(BitWidth),
2262 Op1KnownZero, Op1KnownOne, 0))
2263 return &I;
2264
2265 // Given the known and unknown bits, compute a range that the LHS could be
2266 // in. Compute the Min, Max and RHS values based on the known bits. For the
2267 // EQ and NE we use unsigned values.
2268 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2269 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2270 if (I.isSigned()) {
2271 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2272 Op0Min, Op0Max);
2273 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2274 Op1Min, Op1Max);
2275 } else {
2276 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2277 Op0Min, Op0Max);
2278 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2279 Op1Min, Op1Max);
2280 }
2281
2282 // If Min and Max are known to be the same, then SimplifyDemandedBits
2283 // figured out that the LHS is a constant. Just constant fold this now so
2284 // that code below can assume that Min != Max.
2285 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2286 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00002287 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002288 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2289 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00002290 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00002291
2292 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00002293 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00002294 switch (I.getPredicate()) {
2295 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00002296 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00002297 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002298 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002299
Chris Lattnerf7e89612010-11-21 06:44:42 +00002300 // If all bits are known zero except for one, then we know at most one
2301 // bit is set. If the comparison is against zero, then this is a check
2302 // to see if *that* bit is set.
2303 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2304 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2305 // If the LHS is an AND with the same constant, look through it.
2306 Value *LHS = 0;
2307 ConstantInt *LHSC = 0;
2308 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2309 LHSC->getValue() != Op0KnownZeroInverted)
2310 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002311
Chris Lattnerf7e89612010-11-21 06:44:42 +00002312 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattnere5afa152010-11-23 02:42:04 +00002313 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattnerf7e89612010-11-21 06:44:42 +00002314 Value *X = 0;
2315 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2316 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattnere5afa152010-11-23 02:42:04 +00002317 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerf7e89612010-11-21 06:44:42 +00002318 ConstantInt::get(X->getType(), CmpVal));
2319 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002320
Chris Lattnerf7e89612010-11-21 06:44:42 +00002321 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattnere5afa152010-11-23 02:42:04 +00002322 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00002323 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002324 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00002325 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00002326 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00002327 ConstantInt::get(X->getType(),
2328 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00002329 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002330
Chris Lattner2188e402010-01-04 07:37:31 +00002331 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002332 }
2333 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00002334 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002335 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002336
Chris Lattnerf7e89612010-11-21 06:44:42 +00002337 // If all bits are known zero except for one, then we know at most one
2338 // bit is set. If the comparison is against zero, then this is a check
2339 // to see if *that* bit is set.
2340 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2341 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2342 // If the LHS is an AND with the same constant, look through it.
2343 Value *LHS = 0;
2344 ConstantInt *LHSC = 0;
2345 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2346 LHSC->getValue() != Op0KnownZeroInverted)
2347 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002348
Chris Lattnerf7e89612010-11-21 06:44:42 +00002349 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattnere5afa152010-11-23 02:42:04 +00002350 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattnerf7e89612010-11-21 06:44:42 +00002351 Value *X = 0;
2352 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2353 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattnere5afa152010-11-23 02:42:04 +00002354 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerf7e89612010-11-21 06:44:42 +00002355 ConstantInt::get(X->getType(), CmpVal));
2356 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002357
Chris Lattnerf7e89612010-11-21 06:44:42 +00002358 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattnere5afa152010-11-23 02:42:04 +00002359 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00002360 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002361 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00002362 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00002363 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00002364 ConstantInt::get(X->getType(),
2365 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00002366 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002367
Chris Lattner2188e402010-01-04 07:37:31 +00002368 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002369 }
Chris Lattner2188e402010-01-04 07:37:31 +00002370 case ICmpInst::ICMP_ULT:
2371 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002372 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002373 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002374 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002375 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2376 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2377 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2378 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2379 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002380 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002381
2382 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2383 if (CI->isMinValue(true))
2384 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2385 Constant::getAllOnesValue(Op0->getType()));
2386 }
2387 break;
2388 case ICmpInst::ICMP_UGT:
2389 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002390 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002391 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002392 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002393
2394 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2395 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2396 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2397 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2398 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002399 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002400
2401 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2402 if (CI->isMaxValue(true))
2403 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2404 Constant::getNullValue(Op0->getType()));
2405 }
2406 break;
2407 case ICmpInst::ICMP_SLT:
2408 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002409 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002410 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002411 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002412 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2413 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2414 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2415 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2416 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002417 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002418 }
2419 break;
2420 case ICmpInst::ICMP_SGT:
2421 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002422 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002423 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002424 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002425
2426 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2427 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2428 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2429 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2430 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002431 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002432 }
2433 break;
2434 case ICmpInst::ICMP_SGE:
2435 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2436 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002437 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002438 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002439 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002440 break;
2441 case ICmpInst::ICMP_SLE:
2442 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2443 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002444 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002445 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002446 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002447 break;
2448 case ICmpInst::ICMP_UGE:
2449 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2450 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002451 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002452 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002453 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002454 break;
2455 case ICmpInst::ICMP_ULE:
2456 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2457 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002458 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002459 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002460 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002461 break;
2462 }
2463
2464 // Turn a signed comparison into an unsigned one if both operands
2465 // are known to have the same sign.
2466 if (I.isSigned() &&
2467 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2468 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2469 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2470 }
2471
2472 // Test if the ICmpInst instruction is used exclusively by a select as
2473 // part of a minimum or maximum operation. If so, refrain from doing
2474 // any other folding. This helps out other analyses which understand
2475 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2476 // and CodeGen. And in this case, at least one of the comparison
2477 // operands has at least one user besides the compare (the select),
2478 // which would often largely negate the benefit of folding anyway.
2479 if (I.hasOneUse())
2480 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2481 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2482 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2483 return 0;
2484
2485 // See if we are doing a comparison between a constant and an instruction that
2486 // can be folded into the comparison.
2487 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002488 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2489 // instruction, see if that instruction also has constants so that the
2490 // instruction can be folded into the icmp
Chris Lattner2188e402010-01-04 07:37:31 +00002491 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2492 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2493 return Res;
2494 }
2495
2496 // Handle icmp with constant (but not simple integer constant) RHS
2497 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2498 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2499 switch (LHSI->getOpcode()) {
2500 case Instruction::GetElementPtr:
2501 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2502 if (RHSC->isNullValue() &&
2503 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2504 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2505 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2506 break;
2507 case Instruction::PHI:
2508 // Only fold icmp into the PHI if the phi and icmp are in the same
2509 // block. If in the same block, we're encouraging jump threading. If
2510 // not, we are just pessimizing the code by making an i1 phi.
2511 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00002512 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00002513 return NV;
2514 break;
2515 case Instruction::Select: {
2516 // If either operand of the select is a constant, we can fold the
2517 // comparison into the select arms, which will cause one to be
2518 // constant folded and the select turned into a bitwise or.
2519 Value *Op1 = 0, *Op2 = 0;
2520 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2521 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2522 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2523 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2524
2525 // We only want to perform this transformation if it will not lead to
2526 // additional code. This is true if either both sides of the select
2527 // fold to a constant (in which case the icmp is replaced with a select
2528 // which will usually simplify) or this is the only user of the
2529 // select (in which case we are trading a select+icmp for a simpler
2530 // select+icmp).
2531 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2532 if (!Op1)
2533 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2534 RHSC, I.getName());
2535 if (!Op2)
2536 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2537 RHSC, I.getName());
2538 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2539 }
2540 break;
2541 }
Chris Lattner2188e402010-01-04 07:37:31 +00002542 case Instruction::IntToPtr:
2543 // icmp pred inttoptr(X), null -> icmp pred X, 0
2544 if (RHSC->isNullValue() && TD &&
Matt Arsenault745101d2013-08-21 19:53:10 +00002545 TD->getIntPtrType(RHSC->getType()) ==
Chris Lattner2188e402010-01-04 07:37:31 +00002546 LHSI->getOperand(0)->getType())
2547 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2548 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2549 break;
2550
2551 case Instruction::Load:
2552 // Try to optimize things like "A[i] > 4" to index computations.
2553 if (GetElementPtrInst *GEP =
2554 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2555 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2556 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2557 !cast<LoadInst>(LHSI)->isVolatile())
2558 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2559 return Res;
2560 }
2561 break;
2562 }
2563 }
2564
2565 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2566 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2567 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2568 return NI;
2569 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2570 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2571 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2572 return NI;
2573
2574 // Test to see if the operands of the icmp are casted versions of other
2575 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2576 // now.
2577 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002578 if (Op0->getType()->isPointerTy() &&
2579 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002580 // We keep moving the cast from the left operand over to the right
2581 // operand, where it can often be eliminated completely.
2582 Op0 = CI->getOperand(0);
2583
2584 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2585 // so eliminate it as well.
2586 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2587 Op1 = CI2->getOperand(0);
2588
2589 // If Op1 is a constant, we can fold the cast into the constant.
2590 if (Op0->getType() != Op1->getType()) {
2591 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2592 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2593 } else {
2594 // Otherwise, cast the RHS right before the icmp
2595 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2596 }
2597 }
2598 return new ICmpInst(I.getPredicate(), Op0, Op1);
2599 }
2600 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002601
Chris Lattner2188e402010-01-04 07:37:31 +00002602 if (isa<CastInst>(Op0)) {
2603 // Handle the special case of: icmp (cast bool to X), <cst>
2604 // This comes up when you have code like
2605 // int X = A < B;
2606 // if (X) ...
2607 // For generality, we handle any zero-extension of any operand comparison
2608 // with a constant or another cast from the same type.
2609 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2610 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2611 return R;
2612 }
Chris Lattner2188e402010-01-04 07:37:31 +00002613
Duncan Sandse5220012011-02-17 07:46:37 +00002614 // Special logic for binary operators.
2615 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2616 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2617 if (BO0 || BO1) {
2618 CmpInst::Predicate Pred = I.getPredicate();
2619 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2620 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2621 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2622 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2623 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2624 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2625 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2626 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2627 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2628
2629 // Analyze the case when either Op0 or Op1 is an add instruction.
2630 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2631 Value *A = 0, *B = 0, *C = 0, *D = 0;
2632 if (BO0 && BO0->getOpcode() == Instruction::Add)
2633 A = BO0->getOperand(0), B = BO0->getOperand(1);
2634 if (BO1 && BO1->getOpcode() == Instruction::Add)
2635 C = BO1->getOperand(0), D = BO1->getOperand(1);
2636
2637 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2638 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2639 return new ICmpInst(Pred, A == Op1 ? B : A,
2640 Constant::getNullValue(Op1->getType()));
2641
2642 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2643 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2644 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2645 C == Op0 ? D : C);
2646
Duncan Sands84653b32011-02-18 16:25:37 +00002647 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00002648 if (A && C && (A == C || A == D || B == C || B == D) &&
2649 NoOp0WrapProblem && NoOp1WrapProblem &&
2650 // Try not to increase register pressure.
2651 BO0->hasOneUse() && BO1->hasOneUse()) {
2652 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00002653 Value *Y, *Z;
2654 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002655 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00002656 Y = B;
2657 Z = D;
2658 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002659 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00002660 Y = B;
2661 Z = C;
2662 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002663 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00002664 Y = A;
2665 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002666 } else {
2667 assert(B == D);
2668 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00002669 Y = A;
2670 Z = C;
2671 }
Duncan Sandse5220012011-02-17 07:46:37 +00002672 return new ICmpInst(Pred, Y, Z);
2673 }
2674
David Majnemerb81cd632013-04-11 20:05:46 +00002675 // icmp slt (X + -1), Y -> icmp sle X, Y
2676 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2677 match(B, m_AllOnes()))
2678 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2679
2680 // icmp sge (X + -1), Y -> icmp sgt X, Y
2681 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2682 match(B, m_AllOnes()))
2683 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2684
2685 // icmp sle (X + 1), Y -> icmp slt X, Y
2686 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2687 match(B, m_One()))
2688 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2689
2690 // icmp sgt (X + 1), Y -> icmp sge X, Y
2691 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2692 match(B, m_One()))
2693 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2694
2695 // if C1 has greater magnitude than C2:
2696 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2697 // s.t. C3 = C1 - C2
2698 //
2699 // if C2 has greater magnitude than C1:
2700 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2701 // s.t. C3 = C2 - C1
2702 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2703 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2704 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2705 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2706 const APInt &AP1 = C1->getValue();
2707 const APInt &AP2 = C2->getValue();
2708 if (AP1.isNegative() == AP2.isNegative()) {
2709 APInt AP1Abs = C1->getValue().abs();
2710 APInt AP2Abs = C2->getValue().abs();
2711 if (AP1Abs.uge(AP2Abs)) {
2712 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2713 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2714 return new ICmpInst(Pred, NewAdd, C);
2715 } else {
2716 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2717 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2718 return new ICmpInst(Pred, A, NewAdd);
2719 }
2720 }
2721 }
2722
2723
Duncan Sandse5220012011-02-17 07:46:37 +00002724 // Analyze the case when either Op0 or Op1 is a sub instruction.
2725 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2726 A = 0; B = 0; C = 0; D = 0;
2727 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2728 A = BO0->getOperand(0), B = BO0->getOperand(1);
2729 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2730 C = BO1->getOperand(0), D = BO1->getOperand(1);
2731
Duncan Sands84653b32011-02-18 16:25:37 +00002732 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2733 if (A == Op1 && NoOp0WrapProblem)
2734 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2735
2736 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2737 if (C == Op0 && NoOp1WrapProblem)
2738 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2739
2740 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00002741 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2742 // Try not to increase register pressure.
2743 BO0->hasOneUse() && BO1->hasOneUse())
2744 return new ICmpInst(Pred, A, C);
2745
Duncan Sands84653b32011-02-18 16:25:37 +00002746 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2747 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2748 // Try not to increase register pressure.
2749 BO0->hasOneUse() && BO1->hasOneUse())
2750 return new ICmpInst(Pred, D, B);
2751
Nick Lewycky25cc3382011-03-05 04:28:48 +00002752 BinaryOperator *SRem = NULL;
Nick Lewyckyafc80982011-03-08 06:29:47 +00002753 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00002754 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2755 Op1 == BO0->getOperand(1))
2756 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00002757 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00002758 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2759 Op0 == BO1->getOperand(1))
2760 SRem = BO1;
2761 if (SRem) {
2762 // We don't check hasOneUse to avoid increasing register pressure because
2763 // the value we use is the same value this instruction was already using.
2764 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2765 default: break;
2766 case ICmpInst::ICMP_EQ:
Nick Lewycky92db8e82011-03-06 03:36:19 +00002767 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00002768 case ICmpInst::ICMP_NE:
Nick Lewycky92db8e82011-03-06 03:36:19 +00002769 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00002770 case ICmpInst::ICMP_SGT:
2771 case ICmpInst::ICMP_SGE:
2772 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2773 Constant::getAllOnesValue(SRem->getType()));
2774 case ICmpInst::ICMP_SLT:
2775 case ICmpInst::ICMP_SLE:
2776 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2777 Constant::getNullValue(SRem->getType()));
2778 }
2779 }
2780
Duncan Sandse5220012011-02-17 07:46:37 +00002781 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2782 BO0->hasOneUse() && BO1->hasOneUse() &&
2783 BO0->getOperand(1) == BO1->getOperand(1)) {
2784 switch (BO0->getOpcode()) {
2785 default: break;
2786 case Instruction::Add:
2787 case Instruction::Sub:
2788 case Instruction::Xor:
2789 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2790 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2791 BO1->getOperand(0));
2792 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2793 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2794 if (CI->getValue().isSignBit()) {
2795 ICmpInst::Predicate Pred = I.isSigned()
2796 ? I.getUnsignedPredicate()
2797 : I.getSignedPredicate();
2798 return new ICmpInst(Pred, BO0->getOperand(0),
2799 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00002800 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002801
Chris Lattnerb1a15122011-07-15 06:08:15 +00002802 if (CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00002803 ICmpInst::Predicate Pred = I.isSigned()
2804 ? I.getUnsignedPredicate()
2805 : I.getSignedPredicate();
2806 Pred = I.getSwappedPredicate(Pred);
2807 return new ICmpInst(Pred, BO0->getOperand(0),
2808 BO1->getOperand(0));
2809 }
Chris Lattner2188e402010-01-04 07:37:31 +00002810 }
Duncan Sandse5220012011-02-17 07:46:37 +00002811 break;
2812 case Instruction::Mul:
2813 if (!I.isEquality())
2814 break;
2815
2816 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2817 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2818 // Mask = -1 >> count-trailing-zeros(Cst).
2819 if (!CI->isZero() && !CI->isOne()) {
2820 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002821 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00002822 APInt::getLowBitsSet(AP.getBitWidth(),
2823 AP.getBitWidth() -
2824 AP.countTrailingZeros()));
2825 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2826 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2827 return new ICmpInst(I.getPredicate(), And1, And2);
2828 }
2829 }
2830 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00002831 case Instruction::UDiv:
2832 case Instruction::LShr:
2833 if (I.isSigned())
2834 break;
2835 // fall-through
2836 case Instruction::SDiv:
2837 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002838 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002839 break;
2840 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2841 BO1->getOperand(0));
2842 case Instruction::Shl: {
2843 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2844 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2845 if (!NUW && !NSW)
2846 break;
2847 if (!NSW && I.isSigned())
2848 break;
2849 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2850 BO1->getOperand(0));
2851 }
Chris Lattner2188e402010-01-04 07:37:31 +00002852 }
2853 }
2854 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002855
Chris Lattner2188e402010-01-04 07:37:31 +00002856 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00002857 // Transform (A & ~B) == 0 --> (A & B) != 0
2858 // and (A & ~B) != 0 --> (A & B) == 0
2859 // if A is a power of 2.
2860 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2861 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
2862 return new ICmpInst(I.getInversePredicate(),
2863 Builder->CreateAnd(A, B),
2864 Op1);
2865
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00002866 // ~x < ~y --> y < x
2867 // ~x < cst --> ~cst < x
2868 if (match(Op0, m_Not(m_Value(A)))) {
2869 if (match(Op1, m_Not(m_Value(B))))
2870 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00002871 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00002872 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2873 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002874
2875 // (a+b) <u a --> llvm.uadd.with.overflow.
2876 // (a+b) <u b --> llvm.uadd.with.overflow.
2877 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach129c52a2011-09-30 18:09:53 +00002878 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002879 (Op1 == A || Op1 == B))
2880 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2881 return R;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002882
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002883 // a >u (a+b) --> llvm.uadd.with.overflow.
2884 // b >u (a+b) --> llvm.uadd.with.overflow.
2885 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2886 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2887 (Op0 == A || Op0 == B))
2888 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2889 return R;
Chris Lattner2188e402010-01-04 07:37:31 +00002890 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002891
Chris Lattner2188e402010-01-04 07:37:31 +00002892 if (I.isEquality()) {
2893 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00002894
Chris Lattner2188e402010-01-04 07:37:31 +00002895 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2896 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2897 Value *OtherVal = A == Op1 ? B : A;
2898 return new ICmpInst(I.getPredicate(), OtherVal,
2899 Constant::getNullValue(A->getType()));
2900 }
2901
2902 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2903 // A^c1 == C^c2 --> A == C^(c1^c2)
2904 ConstantInt *C1, *C2;
2905 if (match(B, m_ConstantInt(C1)) &&
2906 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00002907 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002908 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00002909 return new ICmpInst(I.getPredicate(), A, Xor);
2910 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002911
Chris Lattner2188e402010-01-04 07:37:31 +00002912 // A^B == A^D -> B == D
2913 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2914 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2915 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2916 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2917 }
2918 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002919
Chris Lattner2188e402010-01-04 07:37:31 +00002920 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2921 (A == Op0 || B == Op0)) {
2922 // A == (A^B) -> B == 0
2923 Value *OtherVal = A == Op0 ? B : A;
2924 return new ICmpInst(I.getPredicate(), OtherVal,
2925 Constant::getNullValue(A->getType()));
2926 }
2927
Chris Lattner2188e402010-01-04 07:37:31 +00002928 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00002929 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00002930 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002931 Value *X = 0, *Y = 0, *Z = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002932
Chris Lattner2188e402010-01-04 07:37:31 +00002933 if (A == C) {
2934 X = B; Y = D; Z = A;
2935 } else if (A == D) {
2936 X = B; Y = C; Z = A;
2937 } else if (B == C) {
2938 X = A; Y = D; Z = B;
2939 } else if (B == D) {
2940 X = A; Y = C; Z = B;
2941 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002942
Chris Lattner2188e402010-01-04 07:37:31 +00002943 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002944 Op1 = Builder->CreateXor(X, Y);
2945 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00002946 I.setOperand(0, Op1);
2947 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2948 return &I;
2949 }
2950 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002951
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00002952 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00002953 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00002954 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00002955 if ((Op0->hasOneUse() &&
2956 match(Op0, m_ZExt(m_Value(A))) &&
2957 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2958 (Op1->hasOneUse() &&
2959 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2960 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00002961 APInt Pow2 = Cst1->getValue() + 1;
2962 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2963 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2964 return new ICmpInst(I.getPredicate(), A,
2965 Builder->CreateTrunc(B, A->getType()));
2966 }
2967
Benjamin Kramer03f3e242013-11-16 16:00:48 +00002968 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
2969 // For lshr and ashr pairs.
2970 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2971 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
2972 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2973 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
2974 unsigned TypeBits = Cst1->getBitWidth();
2975 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
2976 if (ShAmt < TypeBits && ShAmt != 0) {
2977 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
2978 ? ICmpInst::ICMP_UGE
2979 : ICmpInst::ICMP_ULT;
2980 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
2981 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
2982 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
2983 }
2984 }
2985
Chris Lattner1b06c712011-04-26 20:18:20 +00002986 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2987 // "icmp (and X, mask), cst"
2988 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00002989 if (Op0->hasOneUse() &&
2990 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2991 m_ConstantInt(ShAmt))))) &&
2992 match(Op1, m_ConstantInt(Cst1)) &&
2993 // Only do this when A has multiple uses. This is most important to do
2994 // when it exposes other optimizations.
2995 !A->hasOneUse()) {
2996 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002997
Chris Lattner1b06c712011-04-26 20:18:20 +00002998 if (ShAmt < ASize) {
2999 APInt MaskV =
3000 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3001 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003002
Chris Lattner1b06c712011-04-26 20:18:20 +00003003 APInt CmpV = Cst1->getValue().zext(ASize);
3004 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003005
Chris Lattner1b06c712011-04-26 20:18:20 +00003006 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3007 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3008 }
3009 }
Chris Lattner2188e402010-01-04 07:37:31 +00003010 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003011
Chris Lattner2188e402010-01-04 07:37:31 +00003012 {
3013 Value *X; ConstantInt *Cst;
3014 // icmp X+Cst, X
3015 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003016 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003017
3018 // icmp X, X+Cst
3019 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003020 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003021 }
3022 return Changed ? &I : 0;
3023}
3024
Chris Lattner2188e402010-01-04 07:37:31 +00003025/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
3026///
3027Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3028 Instruction *LHSI,
3029 Constant *RHSC) {
3030 if (!isa<ConstantFP>(RHSC)) return 0;
3031 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003032
Chris Lattner2188e402010-01-04 07:37:31 +00003033 // Get the width of the mantissa. We don't want to hack on conversions that
3034 // might lose information from the integer, e.g. "i64 -> float"
3035 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
3036 if (MantissaWidth == -1) return 0; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003037
Chris Lattner2188e402010-01-04 07:37:31 +00003038 // Check to see that the input is converted from an integer type that is small
3039 // enough that preserves all bits. TODO: check here for "known" sign bits.
3040 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3041 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003042
Chris Lattner2188e402010-01-04 07:37:31 +00003043 // If this is a uitofp instruction, we need an extra bit to hold the sign.
3044 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3045 if (LHSUnsigned)
3046 ++InputSize;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003047
Chris Lattner2188e402010-01-04 07:37:31 +00003048 // If the conversion would lose info, don't hack on this.
3049 if ((int)InputSize > MantissaWidth)
3050 return 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003051
Chris Lattner2188e402010-01-04 07:37:31 +00003052 // Otherwise, we can potentially simplify the comparison. We know that it
3053 // will always come through as an integer value and we know the constant is
3054 // not a NAN (it would have been previously simplified).
3055 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00003056
Chris Lattner2188e402010-01-04 07:37:31 +00003057 ICmpInst::Predicate Pred;
3058 switch (I.getPredicate()) {
3059 default: llvm_unreachable("Unexpected predicate!");
3060 case FCmpInst::FCMP_UEQ:
3061 case FCmpInst::FCMP_OEQ:
3062 Pred = ICmpInst::ICMP_EQ;
3063 break;
3064 case FCmpInst::FCMP_UGT:
3065 case FCmpInst::FCMP_OGT:
3066 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3067 break;
3068 case FCmpInst::FCMP_UGE:
3069 case FCmpInst::FCMP_OGE:
3070 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3071 break;
3072 case FCmpInst::FCMP_ULT:
3073 case FCmpInst::FCMP_OLT:
3074 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3075 break;
3076 case FCmpInst::FCMP_ULE:
3077 case FCmpInst::FCMP_OLE:
3078 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3079 break;
3080 case FCmpInst::FCMP_UNE:
3081 case FCmpInst::FCMP_ONE:
3082 Pred = ICmpInst::ICMP_NE;
3083 break;
3084 case FCmpInst::FCMP_ORD:
Jakub Staszakbddea112013-06-06 20:18:46 +00003085 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003086 case FCmpInst::FCMP_UNO:
Jakub Staszakbddea112013-06-06 20:18:46 +00003087 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003088 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003089
Chris Lattner229907c2011-07-18 04:54:35 +00003090 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003091
Chris Lattner2188e402010-01-04 07:37:31 +00003092 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003093
Chris Lattner2188e402010-01-04 07:37:31 +00003094 // See if the FP constant is too large for the integer. For example,
3095 // comparing an i8 to 300.0.
3096 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003097
Chris Lattner2188e402010-01-04 07:37:31 +00003098 if (!LHSUnsigned) {
3099 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3100 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003101 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003102 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3103 APFloat::rmNearestTiesToEven);
3104 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3105 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3106 Pred == ICmpInst::ICMP_SLE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003107 return ReplaceInstUsesWith(I, Builder->getTrue());
3108 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003109 }
3110 } else {
3111 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3112 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003113 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003114 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3115 APFloat::rmNearestTiesToEven);
3116 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3117 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3118 Pred == ICmpInst::ICMP_ULE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003119 return ReplaceInstUsesWith(I, Builder->getTrue());
3120 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003121 }
3122 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003123
Chris Lattner2188e402010-01-04 07:37:31 +00003124 if (!LHSUnsigned) {
3125 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003126 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003127 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3128 APFloat::rmNearestTiesToEven);
3129 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3130 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3131 Pred == ICmpInst::ICMP_SGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003132 return ReplaceInstUsesWith(I, Builder->getTrue());
3133 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003134 }
Devang Patel698452b2012-02-13 23:05:18 +00003135 } else {
3136 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003137 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00003138 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3139 APFloat::rmNearestTiesToEven);
3140 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3141 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3142 Pred == ICmpInst::ICMP_UGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003143 return ReplaceInstUsesWith(I, Builder->getTrue());
3144 return ReplaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00003145 }
Chris Lattner2188e402010-01-04 07:37:31 +00003146 }
3147
3148 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3149 // [0, UMAX], but it may still be fractional. See if it is fractional by
3150 // casting the FP value to the integer value and back, checking for equality.
3151 // Don't do this for zero, because -0.0 is not fractional.
3152 Constant *RHSInt = LHSUnsigned
3153 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3154 : ConstantExpr::getFPToSI(RHSC, IntTy);
3155 if (!RHS.isZero()) {
3156 bool Equal = LHSUnsigned
3157 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3158 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3159 if (!Equal) {
3160 // If we had a comparison against a fractional value, we have to adjust
3161 // the compare predicate and sometimes the value. RHSC is rounded towards
3162 // zero at this point.
3163 switch (Pred) {
3164 default: llvm_unreachable("Unexpected integer comparison!");
3165 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Jakub Staszakbddea112013-06-06 20:18:46 +00003166 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003167 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Jakub Staszakbddea112013-06-06 20:18:46 +00003168 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003169 case ICmpInst::ICMP_ULE:
3170 // (float)int <= 4.4 --> int <= 4
3171 // (float)int <= -4.4 --> false
3172 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003173 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003174 break;
3175 case ICmpInst::ICMP_SLE:
3176 // (float)int <= 4.4 --> int <= 4
3177 // (float)int <= -4.4 --> int < -4
3178 if (RHS.isNegative())
3179 Pred = ICmpInst::ICMP_SLT;
3180 break;
3181 case ICmpInst::ICMP_ULT:
3182 // (float)int < -4.4 --> false
3183 // (float)int < 4.4 --> int <= 4
3184 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003185 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003186 Pred = ICmpInst::ICMP_ULE;
3187 break;
3188 case ICmpInst::ICMP_SLT:
3189 // (float)int < -4.4 --> int < -4
3190 // (float)int < 4.4 --> int <= 4
3191 if (!RHS.isNegative())
3192 Pred = ICmpInst::ICMP_SLE;
3193 break;
3194 case ICmpInst::ICMP_UGT:
3195 // (float)int > 4.4 --> int > 4
3196 // (float)int > -4.4 --> true
3197 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003198 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003199 break;
3200 case ICmpInst::ICMP_SGT:
3201 // (float)int > 4.4 --> int > 4
3202 // (float)int > -4.4 --> int >= -4
3203 if (RHS.isNegative())
3204 Pred = ICmpInst::ICMP_SGE;
3205 break;
3206 case ICmpInst::ICMP_UGE:
3207 // (float)int >= -4.4 --> true
3208 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00003209 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003210 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003211 Pred = ICmpInst::ICMP_UGT;
3212 break;
3213 case ICmpInst::ICMP_SGE:
3214 // (float)int >= -4.4 --> int >= -4
3215 // (float)int >= 4.4 --> int > 4
3216 if (!RHS.isNegative())
3217 Pred = ICmpInst::ICMP_SGT;
3218 break;
3219 }
3220 }
3221 }
3222
3223 // Lower this FP comparison into an appropriate integer version of the
3224 // comparison.
3225 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3226}
3227
3228Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3229 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003230
Chris Lattner2188e402010-01-04 07:37:31 +00003231 /// Orders the operands of the compare so that they are listed from most
3232 /// complex to least complex. This puts constants before unary operators,
3233 /// before binary operators.
3234 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3235 I.swapOperands();
3236 Changed = true;
3237 }
3238
3239 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003240
Chris Lattner2188e402010-01-04 07:37:31 +00003241 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
3242 return ReplaceInstUsesWith(I, V);
3243
3244 // Simplify 'fcmp pred X, X'
3245 if (Op0 == Op1) {
3246 switch (I.getPredicate()) {
3247 default: llvm_unreachable("Unknown predicate!");
3248 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3249 case FCmpInst::FCMP_ULT: // True if unordered or less than
3250 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3251 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3252 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3253 I.setPredicate(FCmpInst::FCMP_UNO);
3254 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3255 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003256
Chris Lattner2188e402010-01-04 07:37:31 +00003257 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
3258 case FCmpInst::FCMP_OEQ: // True if ordered and equal
3259 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
3260 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
3261 // Canonicalize these to be 'fcmp ord %X, 0.0'.
3262 I.setPredicate(FCmpInst::FCMP_ORD);
3263 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3264 return &I;
3265 }
3266 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003267
Chris Lattner2188e402010-01-04 07:37:31 +00003268 // Handle fcmp with constant RHS
3269 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3270 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3271 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003272 case Instruction::FPExt: {
3273 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3274 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3275 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3276 if (!RHSF)
3277 break;
3278
3279 const fltSemantics *Sem;
3280 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00003281 if (LHSExt->getSrcTy()->isHalfTy())
3282 Sem = &APFloat::IEEEhalf;
3283 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003284 Sem = &APFloat::IEEEsingle;
3285 else if (LHSExt->getSrcTy()->isDoubleTy())
3286 Sem = &APFloat::IEEEdouble;
3287 else if (LHSExt->getSrcTy()->isFP128Ty())
3288 Sem = &APFloat::IEEEquad;
3289 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3290 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00003291 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3292 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003293 else
3294 break;
3295
3296 bool Lossy;
3297 APFloat F = RHSF->getValueAPF();
3298 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3299
Jim Grosbach24ff8342011-09-30 18:45:50 +00003300 // Avoid lossy conversions and denormals. Zero is a special case
3301 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00003302 APFloat Fabs = F;
3303 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003304 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00003305 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3306 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00003307
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003308 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3309 ConstantFP::get(RHSC->getContext(), F));
3310 break;
3311 }
Chris Lattner2188e402010-01-04 07:37:31 +00003312 case Instruction::PHI:
3313 // Only fold fcmp into the PHI if the phi and fcmp are in the same
3314 // block. If in the same block, we're encouraging jump threading. If
3315 // not, we are just pessimizing the code by making an i1 phi.
3316 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003317 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003318 return NV;
3319 break;
3320 case Instruction::SIToFP:
3321 case Instruction::UIToFP:
3322 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3323 return NV;
3324 break;
3325 case Instruction::Select: {
3326 // If either operand of the select is a constant, we can fold the
3327 // comparison into the select arms, which will cause one to be
3328 // constant folded and the select turned into a bitwise or.
3329 Value *Op1 = 0, *Op2 = 0;
3330 if (LHSI->hasOneUse()) {
3331 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3332 // Fold the known value into the constant operand.
3333 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3334 // Insert a new FCmp of the other select operand.
3335 Op2 = Builder->CreateFCmp(I.getPredicate(),
3336 LHSI->getOperand(2), RHSC, I.getName());
3337 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3338 // Fold the known value into the constant operand.
3339 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3340 // Insert a new FCmp of the other select operand.
3341 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3342 RHSC, I.getName());
3343 }
3344 }
3345
3346 if (Op1)
3347 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3348 break;
3349 }
Benjamin Kramera8c5d082011-03-31 10:12:15 +00003350 case Instruction::FSub: {
3351 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3352 Value *Op;
3353 if (match(LHSI, m_FNeg(m_Value(Op))))
3354 return new FCmpInst(I.getSwappedPredicate(), Op,
3355 ConstantExpr::getFNeg(RHSC));
3356 break;
3357 }
Dan Gohman94732022010-02-24 06:46:09 +00003358 case Instruction::Load:
3359 if (GetElementPtrInst *GEP =
3360 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3361 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3362 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3363 !cast<LoadInst>(LHSI)->isVolatile())
3364 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3365 return Res;
3366 }
3367 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00003368 case Instruction::Call: {
3369 CallInst *CI = cast<CallInst>(LHSI);
3370 LibFunc::Func Func;
3371 // Various optimization for fabs compared with zero.
Benjamin Kramer9d032422012-08-18 22:04:34 +00003372 if (RHSC->isNullValue() && CI->getCalledFunction() &&
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00003373 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3374 TLI->has(Func)) {
3375 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3376 Func == LibFunc::fabsl) {
3377 switch (I.getPredicate()) {
3378 default: break;
3379 // fabs(x) < 0 --> false
3380 case FCmpInst::FCMP_OLT:
3381 return ReplaceInstUsesWith(I, Builder->getFalse());
3382 // fabs(x) > 0 --> x != 0
3383 case FCmpInst::FCMP_OGT:
3384 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3385 RHSC);
3386 // fabs(x) <= 0 --> x == 0
3387 case FCmpInst::FCMP_OLE:
3388 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3389 RHSC);
3390 // fabs(x) >= 0 --> !isnan(x)
3391 case FCmpInst::FCMP_OGE:
3392 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3393 RHSC);
3394 // fabs(x) == 0 --> x == 0
3395 // fabs(x) != 0 --> x != 0
3396 case FCmpInst::FCMP_OEQ:
3397 case FCmpInst::FCMP_UEQ:
3398 case FCmpInst::FCMP_ONE:
3399 case FCmpInst::FCMP_UNE:
3400 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3401 RHSC);
3402 }
3403 }
3404 }
3405 }
Chris Lattner2188e402010-01-04 07:37:31 +00003406 }
Chris Lattner2188e402010-01-04 07:37:31 +00003407 }
3408
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00003409 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00003410 Value *X, *Y;
3411 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00003412 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00003413
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00003414 // fcmp (fpext x), (fpext y) -> fcmp x, y
3415 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3416 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3417 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3418 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3419 RHSExt->getOperand(0));
3420
Chris Lattner2188e402010-01-04 07:37:31 +00003421 return Changed ? &I : 0;
3422}