blob: 53089928c3f5b76f705ca21b4a838c13ff36a788 [file] [log] [blame]
Chris Lattner02446fc2010-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"
15#include "llvm/IntrinsicInst.h"
Eli Friedman74703252011-07-20 21:57:23 +000016#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner02446fc2010-01-04 07:37:31 +000017#include "llvm/Analysis/InstructionSimplify.h"
18#include "llvm/Analysis/MemoryBuiltins.h"
19#include "llvm/Target/TargetData.h"
20#include "llvm/Support/ConstantRange.h"
21#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/Support/PatternMatch.h"
23using namespace llvm;
24using namespace PatternMatch;
25
Chris Lattnerb20c0b52011-02-10 05:23:05 +000026static ConstantInt *getOne(Constant *C) {
27 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
28}
29
Chris Lattner02446fc2010-01-04 07:37:31 +000030/// AddOne - Add one to a ConstantInt
31static Constant *AddOne(Constant *C) {
32 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
33}
34/// SubOne - Subtract one from a ConstantInt
Chris Lattnerb20c0b52011-02-10 05:23:05 +000035static Constant *SubOne(Constant *C) {
36 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner02446fc2010-01-04 07:37:31 +000037}
38
39static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
40 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
41}
42
43static bool HasAddOverflow(ConstantInt *Result,
44 ConstantInt *In1, ConstantInt *In2,
45 bool IsSigned) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +000046 if (!IsSigned)
Chris Lattner02446fc2010-01-04 07:37:31 +000047 return Result->getValue().ult(In1->getValue());
Chris Lattnerc73b24d2011-07-15 06:08:15 +000048
49 if (In2->isNegative())
50 return Result->getValue().sgt(In1->getValue());
51 return Result->getValue().slt(In1->getValue());
Chris Lattner02446fc2010-01-04 07:37:31 +000052}
53
54/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
55/// overflowed for this type.
56static bool AddWithOverflow(Constant *&Result, Constant *In1,
57 Constant *In2, bool IsSigned = false) {
58 Result = ConstantExpr::getAdd(In1, In2);
59
Chris Lattnerdb125cf2011-07-18 04:54:35 +000060 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner02446fc2010-01-04 07:37:31 +000061 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
62 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
63 if (HasAddOverflow(ExtractElement(Result, Idx),
64 ExtractElement(In1, Idx),
65 ExtractElement(In2, Idx),
66 IsSigned))
67 return true;
68 }
69 return false;
70 }
71
72 return HasAddOverflow(cast<ConstantInt>(Result),
73 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
74 IsSigned);
75}
76
77static bool HasSubOverflow(ConstantInt *Result,
78 ConstantInt *In1, ConstantInt *In2,
79 bool IsSigned) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +000080 if (!IsSigned)
Chris Lattner02446fc2010-01-04 07:37:31 +000081 return Result->getValue().ugt(In1->getValue());
Jim Grosbach0cc4a952011-09-30 18:09:53 +000082
Chris Lattnerc73b24d2011-07-15 06:08:15 +000083 if (In2->isNegative())
84 return Result->getValue().slt(In1->getValue());
85
86 return Result->getValue().sgt(In1->getValue());
Chris Lattner02446fc2010-01-04 07:37:31 +000087}
88
89/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
90/// overflowed for this type.
91static bool SubWithOverflow(Constant *&Result, Constant *In1,
92 Constant *In2, bool IsSigned = false) {
93 Result = ConstantExpr::getSub(In1, In2);
94
Chris Lattnerdb125cf2011-07-18 04:54:35 +000095 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner02446fc2010-01-04 07:37:31 +000096 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
97 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
98 if (HasSubOverflow(ExtractElement(Result, Idx),
99 ExtractElement(In1, Idx),
100 ExtractElement(In2, Idx),
101 IsSigned))
102 return true;
103 }
104 return false;
105 }
106
107 return HasSubOverflow(cast<ConstantInt>(Result),
108 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
109 IsSigned);
110}
111
112/// isSignBitCheck - Given an exploded icmp instruction, return true if the
113/// comparison only checks the sign bit. If it only checks the sign bit, set
114/// TrueIfSigned if the result of the comparison is true when the input value is
115/// signed.
116static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
117 bool &TrueIfSigned) {
118 switch (pred) {
119 case ICmpInst::ICMP_SLT: // True if LHS s< 0
120 TrueIfSigned = true;
121 return RHS->isZero();
122 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
123 TrueIfSigned = true;
124 return RHS->isAllOnesValue();
125 case ICmpInst::ICMP_SGT: // True if LHS s> -1
126 TrueIfSigned = false;
127 return RHS->isAllOnesValue();
128 case ICmpInst::ICMP_UGT:
129 // True if LHS u> RHS and RHS == high-bit-mask - 1
130 TrueIfSigned = true;
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000131 return RHS->isMaxValue(true);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000132 case ICmpInst::ICMP_UGE:
Chris Lattner02446fc2010-01-04 07:37:31 +0000133 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
134 TrueIfSigned = true;
135 return RHS->getValue().isSignBit();
136 default:
137 return false;
138 }
139}
140
141// isHighOnes - Return true if the constant is of the form 1+0+.
142// This is the same as lowones(~X).
143static bool isHighOnes(const ConstantInt *CI) {
144 return (~CI->getValue() + 1).isPowerOf2();
145}
146
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000147/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner02446fc2010-01-04 07:37:31 +0000148/// set of known zero and one bits, compute the maximum and minimum values that
149/// could have the specified known zero and known one bits, returning them in
150/// min/max.
151static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
152 const APInt& KnownOne,
153 APInt& Min, APInt& Max) {
154 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
155 KnownZero.getBitWidth() == Min.getBitWidth() &&
156 KnownZero.getBitWidth() == Max.getBitWidth() &&
157 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
158 APInt UnknownBits = ~(KnownZero|KnownOne);
159
160 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
161 // bit if it is unknown.
162 Min = KnownOne;
163 Max = KnownOne|UnknownBits;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000164
Chris Lattner02446fc2010-01-04 07:37:31 +0000165 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad7a874dd2010-12-01 08:53:58 +0000166 Min.setBit(Min.getBitWidth()-1);
167 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner02446fc2010-01-04 07:37:31 +0000168 }
169}
170
171// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
172// a set of known zero and one bits, compute the maximum and minimum values that
173// could have the specified known zero and known one bits, returning them in
174// min/max.
175static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
176 const APInt &KnownOne,
177 APInt &Min, APInt &Max) {
178 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
179 KnownZero.getBitWidth() == Min.getBitWidth() &&
180 KnownZero.getBitWidth() == Max.getBitWidth() &&
181 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
182 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000183
Chris Lattner02446fc2010-01-04 07:37:31 +0000184 // The minimum value is when the unknown bits are all zeros.
185 Min = KnownOne;
186 // The maximum value is when the unknown bits are all ones.
187 Max = KnownOne|UnknownBits;
188}
189
190
191
192/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
193/// cmp pred (load (gep GV, ...)), cmpcst
194/// where GV is a global variable with a constant initializer. Try to simplify
195/// this into some simple computation that does not need the load. For example
196/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
197///
198/// If AndCst is non-null, then the loaded value is masked with that constant
199/// before doing the comparison. This handles cases like "A[i]&4 == 0".
200Instruction *InstCombiner::
201FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
202 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000203 // We need TD information to know the pointer size unless this is inbounds.
204 if (!GEP->isInBounds() && TD == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000205
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000206 Constant *Init = GV->getInitializer();
207 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
208 return 0;
209
210 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
211 if (ArrayElementCount > 1024) return 0; // Don't blow up on huge arrays.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000212
Chris Lattner02446fc2010-01-04 07:37:31 +0000213 // There are many forms of this optimization we can handle, for now, just do
214 // the simple index into a single-dimensional array.
215 //
216 // Require: GEP GV, 0, i {{, constant indices}}
217 if (GEP->getNumOperands() < 3 ||
218 !isa<ConstantInt>(GEP->getOperand(1)) ||
219 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
220 isa<Constant>(GEP->getOperand(2)))
221 return 0;
222
223 // Check that indices after the variable are constants and in-range for the
224 // type they index. Collect the indices. This is typically for arrays of
225 // structs.
226 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000227
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000228 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner02446fc2010-01-04 07:37:31 +0000229 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
230 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
231 if (Idx == 0) return 0; // Variable index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000232
Chris Lattner02446fc2010-01-04 07:37:31 +0000233 uint64_t IdxVal = Idx->getZExtValue();
234 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000235
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000236 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner02446fc2010-01-04 07:37:31 +0000237 EltTy = STy->getElementType(IdxVal);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000238 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000239 if (IdxVal >= ATy->getNumElements()) return 0;
240 EltTy = ATy->getElementType();
241 } else {
242 return 0; // Unknown type.
243 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000244
Chris Lattner02446fc2010-01-04 07:37:31 +0000245 LaterIndices.push_back(IdxVal);
246 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000247
Chris Lattner02446fc2010-01-04 07:37:31 +0000248 enum { Overdefined = -3, Undefined = -2 };
249
250 // Variables for our state machines.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000251
Chris Lattner02446fc2010-01-04 07:37:31 +0000252 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
253 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
254 // and 87 is the second (and last) index. FirstTrueElement is -2 when
255 // undefined, otherwise set to the first true element. SecondTrueElement is
256 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
257 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
258
259 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
260 // form "i != 47 & i != 87". Same state transitions as for true elements.
261 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000262
Chris Lattner02446fc2010-01-04 07:37:31 +0000263 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
264 /// define a state machine that triggers for ranges of values that the index
265 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
266 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
267 /// index in the range (inclusive). We use -2 for undefined here because we
268 /// use relative comparisons and don't want 0-1 to match -1.
269 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000270
Chris Lattner02446fc2010-01-04 07:37:31 +0000271 // MagicBitvector - This is a magic bitvector where we set a bit if the
272 // comparison is true for element 'i'. If there are 64 elements or less in
273 // the array, this will fully represent all the comparison results.
274 uint64_t MagicBitvector = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000275
276
Chris Lattner02446fc2010-01-04 07:37:31 +0000277 // Scan the array and see if one of our patterns matches.
278 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000279 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
280 Constant *Elt = Init->getAggregateElement(i);
281 if (Elt == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000282
Chris Lattner02446fc2010-01-04 07:37:31 +0000283 // If this is indexing an array of structures, get the structure element.
284 if (!LaterIndices.empty())
Jay Foadfc6d3a42011-07-13 10:26:04 +0000285 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000286
Chris Lattner02446fc2010-01-04 07:37:31 +0000287 // If the element is masked, handle it.
288 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000289
Chris Lattner02446fc2010-01-04 07:37:31 +0000290 // Find out if the comparison would be true or false for the i'th element.
291 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chad Rosieraab8e282011-12-02 01:26:24 +0000292 CompareRHS, TD, TLI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000293 // If the result is undef for this element, ignore it.
294 if (isa<UndefValue>(C)) {
295 // Extend range state machines to cover this element in case there is an
296 // undef in the middle of the range.
297 if (TrueRangeEnd == (int)i-1)
298 TrueRangeEnd = i;
299 if (FalseRangeEnd == (int)i-1)
300 FalseRangeEnd = i;
301 continue;
302 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000303
Chris Lattner02446fc2010-01-04 07:37:31 +0000304 // If we can't compute the result for any of the elements, we have to give
305 // up evaluating the entire conditional.
306 if (!isa<ConstantInt>(C)) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000307
Chris Lattner02446fc2010-01-04 07:37:31 +0000308 // Otherwise, we know if the comparison is true or false for this element,
309 // update our state machines.
310 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000311
Chris Lattner02446fc2010-01-04 07:37:31 +0000312 // State machine for single/double/range index comparison.
313 if (IsTrueForElt) {
314 // Update the TrueElement state machine.
315 if (FirstTrueElement == Undefined)
316 FirstTrueElement = TrueRangeEnd = i; // First true element.
317 else {
318 // Update double-compare state machine.
319 if (SecondTrueElement == Undefined)
320 SecondTrueElement = i;
321 else
322 SecondTrueElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000323
Chris Lattner02446fc2010-01-04 07:37:31 +0000324 // Update range state machine.
325 if (TrueRangeEnd == (int)i-1)
326 TrueRangeEnd = i;
327 else
328 TrueRangeEnd = Overdefined;
329 }
330 } else {
331 // Update the FalseElement state machine.
332 if (FirstFalseElement == Undefined)
333 FirstFalseElement = FalseRangeEnd = i; // First false element.
334 else {
335 // Update double-compare state machine.
336 if (SecondFalseElement == Undefined)
337 SecondFalseElement = i;
338 else
339 SecondFalseElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000340
Chris Lattner02446fc2010-01-04 07:37:31 +0000341 // Update range state machine.
342 if (FalseRangeEnd == (int)i-1)
343 FalseRangeEnd = i;
344 else
345 FalseRangeEnd = Overdefined;
346 }
347 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000348
349
Chris Lattner02446fc2010-01-04 07:37:31 +0000350 // If this element is in range, update our magic bitvector.
351 if (i < 64 && IsTrueForElt)
352 MagicBitvector |= 1ULL << i;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000353
Chris Lattner02446fc2010-01-04 07:37:31 +0000354 // If all of our states become overdefined, bail out early. Since the
355 // predicate is expensive, only check it every 8 elements. This is only
356 // really useful for really huge arrays.
357 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
358 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
359 FalseRangeEnd == Overdefined)
360 return 0;
361 }
362
363 // Now that we've scanned the entire array, emit our new comparison(s). We
364 // order the state machines in complexity of the generated code.
365 Value *Idx = GEP->getOperand(2);
366
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000367 // If the index is larger than the pointer size of the target, truncate the
368 // index down like the GEP would do implicitly. We don't have to do this for
369 // an inbounds GEP because the index can't be out of range.
370 if (!GEP->isInBounds() &&
371 Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
372 Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000373
Chris Lattner02446fc2010-01-04 07:37:31 +0000374 // If the comparison is only true for one or two elements, emit direct
375 // comparisons.
376 if (SecondTrueElement != Overdefined) {
377 // None true -> false.
378 if (FirstTrueElement == Undefined)
379 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000380
Chris Lattner02446fc2010-01-04 07:37:31 +0000381 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000382
Chris Lattner02446fc2010-01-04 07:37:31 +0000383 // True for one element -> 'i == 47'.
384 if (SecondTrueElement == Undefined)
385 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000386
Chris Lattner02446fc2010-01-04 07:37:31 +0000387 // True for two elements -> 'i == 47 | i == 72'.
388 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
389 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
390 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
391 return BinaryOperator::CreateOr(C1, C2);
392 }
393
394 // If the comparison is only false for one or two elements, emit direct
395 // comparisons.
396 if (SecondFalseElement != Overdefined) {
397 // None false -> true.
398 if (FirstFalseElement == Undefined)
399 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000400
Chris Lattner02446fc2010-01-04 07:37:31 +0000401 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
402
403 // False for one element -> 'i != 47'.
404 if (SecondFalseElement == Undefined)
405 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000406
Chris Lattner02446fc2010-01-04 07:37:31 +0000407 // False for two elements -> 'i != 47 & i != 72'.
408 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
409 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
410 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
411 return BinaryOperator::CreateAnd(C1, C2);
412 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000413
Chris Lattner02446fc2010-01-04 07:37:31 +0000414 // If the comparison can be replaced with a range comparison for the elements
415 // where it is true, emit the range check.
416 if (TrueRangeEnd != Overdefined) {
417 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000418
Chris Lattner02446fc2010-01-04 07:37:31 +0000419 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
420 if (FirstTrueElement) {
421 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
422 Idx = Builder->CreateAdd(Idx, Offs);
423 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000424
Chris Lattner02446fc2010-01-04 07:37:31 +0000425 Value *End = ConstantInt::get(Idx->getType(),
426 TrueRangeEnd-FirstTrueElement+1);
427 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
428 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000429
Chris Lattner02446fc2010-01-04 07:37:31 +0000430 // False range check.
431 if (FalseRangeEnd != Overdefined) {
432 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
433 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
434 if (FirstFalseElement) {
435 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
436 Idx = Builder->CreateAdd(Idx, Offs);
437 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000438
Chris Lattner02446fc2010-01-04 07:37:31 +0000439 Value *End = ConstantInt::get(Idx->getType(),
440 FalseRangeEnd-FirstFalseElement);
441 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
442 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000443
444
Chris Lattner02446fc2010-01-04 07:37:31 +0000445 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
446 // of this load, replace it with computation that does:
447 // ((magic_cst >> i) & 1) != 0
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000448 if (ArrayElementCount <= 32 ||
449 (TD && ArrayElementCount <= 64 && TD->isLegalInteger(64))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000450 Type *Ty;
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000451 if (ArrayElementCount <= 32)
Chris Lattner02446fc2010-01-04 07:37:31 +0000452 Ty = Type::getInt32Ty(Init->getContext());
453 else
454 Ty = Type::getInt64Ty(Init->getContext());
455 Value *V = Builder->CreateIntCast(Idx, Ty, false);
456 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
457 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
458 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
459 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000460
Chris Lattner02446fc2010-01-04 07:37:31 +0000461 return 0;
462}
463
464
465/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
466/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
467/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
468/// be complex, and scales are involved. The above expression would also be
469/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
470/// This later form is less amenable to optimization though, and we are allowed
471/// to generate the first by knowing that pointer arithmetic doesn't overflow.
472///
473/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000474///
Eli Friedman107ffd52011-05-18 23:11:30 +0000475static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000476 TargetData &TD = *IC.getTargetData();
477 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000478
Chris Lattner02446fc2010-01-04 07:37:31 +0000479 // Check to see if this gep only has a single variable index. If so, and if
480 // any constant indices are a multiple of its scale, then we can compute this
481 // in terms of the scale of the variable index. For example, if the GEP
482 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
483 // because the expression will cross zero at the same point.
484 unsigned i, e = GEP->getNumOperands();
485 int64_t Offset = 0;
486 for (i = 1; i != e; ++i, ++GTI) {
487 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
488 // Compute the aggregate offset of constant indices.
489 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000490
Chris Lattner02446fc2010-01-04 07:37:31 +0000491 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000492 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000493 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
494 } else {
495 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
496 Offset += Size*CI->getSExtValue();
497 }
498 } else {
499 // Found our variable index.
500 break;
501 }
502 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000503
Chris Lattner02446fc2010-01-04 07:37:31 +0000504 // If there are no variable indices, we must have a constant offset, just
505 // evaluate it the general way.
506 if (i == e) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000507
Chris Lattner02446fc2010-01-04 07:37:31 +0000508 Value *VariableIdx = GEP->getOperand(i);
509 // Determine the scale factor of the variable element. For example, this is
510 // 4 if the variable index is into an array of i32.
511 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000512
Chris Lattner02446fc2010-01-04 07:37:31 +0000513 // Verify that there are no other variable indices. If so, emit the hard way.
514 for (++i, ++GTI; i != e; ++i, ++GTI) {
515 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
516 if (!CI) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000517
Chris Lattner02446fc2010-01-04 07:37:31 +0000518 // Compute the aggregate offset of constant indices.
519 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000520
Chris Lattner02446fc2010-01-04 07:37:31 +0000521 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000522 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000523 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
524 } else {
525 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
526 Offset += Size*CI->getSExtValue();
527 }
528 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000529
Chris Lattner02446fc2010-01-04 07:37:31 +0000530 // Okay, we know we have a single variable index, which must be a
531 // pointer/array/vector index. If there is no offset, life is simple, return
532 // the index.
533 unsigned IntPtrWidth = TD.getPointerSizeInBits();
534 if (Offset == 0) {
535 // Cast to intptrty in case a truncation occurs. If an extension is needed,
536 // we don't need to bother extending: the extension won't affect where the
537 // computation crosses zero.
Eli Friedman107ffd52011-05-18 23:11:30 +0000538 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000539 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Eli Friedman107ffd52011-05-18 23:11:30 +0000540 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
541 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000542 return VariableIdx;
543 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000544
Chris Lattner02446fc2010-01-04 07:37:31 +0000545 // Otherwise, there is an index. The computation we will do will be modulo
546 // the pointer size, so get it.
547 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000548
Chris Lattner02446fc2010-01-04 07:37:31 +0000549 Offset &= PtrSizeMask;
550 VariableScale &= PtrSizeMask;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000551
Chris Lattner02446fc2010-01-04 07:37:31 +0000552 // To do this transformation, any constant index must be a multiple of the
553 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
554 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
555 // multiple of the variable scale.
556 int64_t NewOffs = Offset / (int64_t)VariableScale;
557 if (Offset != NewOffs*(int64_t)VariableScale)
558 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000559
Chris Lattner02446fc2010-01-04 07:37:31 +0000560 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000561 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner02446fc2010-01-04 07:37:31 +0000562 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman107ffd52011-05-18 23:11:30 +0000563 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
564 true /*Signed*/);
Chris Lattner02446fc2010-01-04 07:37:31 +0000565 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman107ffd52011-05-18 23:11:30 +0000566 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner02446fc2010-01-04 07:37:31 +0000567}
568
569/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
570/// else. At this point we know that the GEP is on the LHS of the comparison.
571Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
572 ICmpInst::Predicate Cond,
573 Instruction &I) {
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000574 // Don't transform signed compares of GEPs into index compares. Even if the
575 // GEP is inbounds, the final add of the base pointer can have signed overflow
576 // and would change the result of the icmp.
577 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramera42d5c42012-02-21 13:40:06 +0000578 // the maximum signed value for the pointer type.
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000579 if (ICmpInst::isSigned(Cond))
580 return 0;
581
Chris Lattner02446fc2010-01-04 07:37:31 +0000582 // Look through bitcasts.
583 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
584 RHS = BCI->getOperand(0);
585
586 Value *PtrBase = GEPLHS->getOperand(0);
587 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
588 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
589 // This transformation (ignoring the base and scales) is valid because we
590 // know pointers can't overflow since the gep is inbounds. See if we can
591 // output an optimized form.
Eli Friedman107ffd52011-05-18 23:11:30 +0000592 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000593
Chris Lattner02446fc2010-01-04 07:37:31 +0000594 // If not, synthesize the offset the hard way.
595 if (Offset == 0)
596 Offset = EmitGEPOffset(GEPLHS);
597 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
598 Constant::getNullValue(Offset->getType()));
599 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
600 // If the base pointers are different, but the indices are the same, just
601 // compare the base pointer.
602 if (PtrBase != GEPRHS->getOperand(0)) {
603 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
604 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
605 GEPRHS->getOperand(0)->getType();
606 if (IndicesTheSame)
607 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
608 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
609 IndicesTheSame = false;
610 break;
611 }
612
613 // If all indices are the same, just compare the base pointers.
614 if (IndicesTheSame)
615 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
616 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
617
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000618 // If we're comparing GEPs with two base pointers that only differ in type
619 // and both GEPs have only constant indices or just one use, then fold
620 // the compare with the adjusted indices.
Benjamin Kramer6ad48f42012-02-20 18:45:10 +0000621 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000622 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
623 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
624 PtrBase->stripPointerCasts() ==
625 GEPRHS->getOperand(0)->stripPointerCasts()) {
626 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
627 EmitGEPOffset(GEPLHS),
628 EmitGEPOffset(GEPRHS));
629 return ReplaceInstUsesWith(I, Cmp);
630 }
631
Chris Lattner02446fc2010-01-04 07:37:31 +0000632 // Otherwise, the base pointers are different and the indices are
633 // different, bail out.
634 return 0;
635 }
636
637 // If one of the GEPs has all zero indices, recurse.
638 bool AllZeros = true;
639 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
640 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
641 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
642 AllZeros = false;
643 break;
644 }
645 if (AllZeros)
646 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
647 ICmpInst::getSwappedPredicate(Cond), I);
648
649 // If the other GEP has all zero indices, recurse.
650 AllZeros = true;
651 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
652 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
653 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
654 AllZeros = false;
655 break;
656 }
657 if (AllZeros)
658 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
659
Stuart Hastings67f071e2011-05-14 05:55:10 +0000660 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner02446fc2010-01-04 07:37:31 +0000661 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
662 // If the GEPs only differ by one index, compare it.
663 unsigned NumDifferences = 0; // Keep track of # differences.
664 unsigned DiffOperand = 0; // The operand that differs.
665 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
666 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
667 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
668 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
669 // Irreconcilable differences.
670 NumDifferences = 2;
671 break;
672 } else {
673 if (NumDifferences++) break;
674 DiffOperand = i;
675 }
676 }
677
678 if (NumDifferences == 0) // SAME GEP?
679 return ReplaceInstUsesWith(I, // No comparison is needed here.
680 ConstantInt::get(Type::getInt1Ty(I.getContext()),
681 ICmpInst::isTrueWhenEqual(Cond)));
682
Stuart Hastings67f071e2011-05-14 05:55:10 +0000683 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000684 Value *LHSV = GEPLHS->getOperand(DiffOperand);
685 Value *RHSV = GEPRHS->getOperand(DiffOperand);
686 // Make sure we do a signed comparison here.
687 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
688 }
689 }
690
691 // Only lower this if the icmp is the only user of the GEP or if we expect
692 // the result to fold to a constant!
693 if (TD &&
Stuart Hastings67f071e2011-05-14 05:55:10 +0000694 GEPsInBounds &&
Chris Lattner02446fc2010-01-04 07:37:31 +0000695 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
696 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
697 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
698 Value *L = EmitGEPOffset(GEPLHS);
699 Value *R = EmitGEPOffset(GEPRHS);
700 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
701 }
702 }
703 return 0;
704}
705
706/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
707Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
708 Value *X, ConstantInt *CI,
709 ICmpInst::Predicate Pred,
710 Value *TheAdd) {
711 // If we have X+0, exit early (simplifying logic below) and let it get folded
712 // elsewhere. icmp X+0, X -> icmp X, X
713 if (CI->isZero()) {
714 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
715 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
716 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000717
Chris Lattner02446fc2010-01-04 07:37:31 +0000718 // (X+4) == X -> false.
719 if (Pred == ICmpInst::ICMP_EQ)
720 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
721
722 // (X+4) != X -> true.
723 if (Pred == ICmpInst::ICMP_NE)
724 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
725
Chris Lattner02446fc2010-01-04 07:37:31 +0000726 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000727 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner02446fc2010-01-04 07:37:31 +0000728 // operators.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000729
Chris Lattner9aa1e242010-01-08 17:48:19 +0000730 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner02446fc2010-01-04 07:37:31 +0000731 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
732 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
733 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000734 Value *R =
Chris Lattner9aa1e242010-01-08 17:48:19 +0000735 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000736 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
737 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000738
Chris Lattner02446fc2010-01-04 07:37:31 +0000739 // (X+1) >u X --> X <u (0-1) --> X != 255
740 // (X+2) >u X --> X <u (0-2) --> X <u 254
741 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandsa7724332011-02-17 07:46:37 +0000742 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000743 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000744
Chris Lattner02446fc2010-01-04 07:37:31 +0000745 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
746 ConstantInt *SMax = ConstantInt::get(X->getContext(),
747 APInt::getSignedMaxValue(BitWidth));
748
749 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
750 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
751 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
752 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
753 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
754 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandsa7724332011-02-17 07:46:37 +0000755 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000756 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000757
Chris Lattner02446fc2010-01-04 07:37:31 +0000758 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
759 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
760 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
761 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
762 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
763 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000764
Chris Lattner02446fc2010-01-04 07:37:31 +0000765 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
766 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
767 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
768}
769
770/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
771/// and CmpRHS are both known to be integer constants.
772Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
773 ConstantInt *DivRHS) {
774 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
775 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000776
777 // FIXME: If the operand types don't match the type of the divide
Chris Lattner02446fc2010-01-04 07:37:31 +0000778 // then don't attempt this transform. The code below doesn't have the
779 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000780 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner02446fc2010-01-04 07:37:31 +0000781 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000782 // (x /u C1) <u C2. Simply casting the operands and result won't
783 // work. :( The if statement below tests that condition and bails
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000784 // if it finds it.
Chris Lattner02446fc2010-01-04 07:37:31 +0000785 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
786 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
787 return 0;
788 if (DivRHS->isZero())
789 return 0; // The ProdOV computation fails on divide by zero.
790 if (DivIsSigned && DivRHS->isAllOnesValue())
791 return 0; // The overflow computation also screws up here
Chris Lattnerbb75d332011-02-13 08:07:21 +0000792 if (DivRHS->isOne()) {
793 // This eliminates some funny cases with INT_MIN.
794 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
795 return &ICI;
796 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000797
798 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000799 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
800 // C2 (CI). By solving for X we can turn this into a range check
801 // instead of computing a divide.
Chris Lattner02446fc2010-01-04 07:37:31 +0000802 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
803
804 // Determine if the product overflows by seeing if the product is
805 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000806 // as in the LHS instruction that we're folding.
Chris Lattner02446fc2010-01-04 07:37:31 +0000807 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
808 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
809
810 // Get the ICmp opcode
811 ICmpInst::Predicate Pred = ICI.getPredicate();
812
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000813 /// If the division is known to be exact, then there is no remainder from the
814 /// divide, so the covered range size is unit, otherwise it is the divisor.
815 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000816
Chris Lattner02446fc2010-01-04 07:37:31 +0000817 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000818 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner02446fc2010-01-04 07:37:31 +0000819 // Compute this interval based on the constants involved and the signedness of
820 // the compare/divide. This computes a half-open interval, keeping track of
821 // whether either value in the interval overflows. After analysis each
822 // overflow variable is set to 0 if it's corresponding bound variable is valid
823 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
824 int LoOverflow = 0, HiOverflow = 0;
825 Constant *LoBound = 0, *HiBound = 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000826
Chris Lattner02446fc2010-01-04 07:37:31 +0000827 if (!DivIsSigned) { // udiv
828 // e.g. X/5 op 3 --> [15, 20)
829 LoBound = Prod;
830 HiOverflow = LoOverflow = ProdOV;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000831 if (!HiOverflow) {
832 // If this is not an exact divide, then many values in the range collapse
833 // to the same result value.
834 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
835 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000836
Chris Lattner02446fc2010-01-04 07:37:31 +0000837 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
838 if (CmpRHSV == 0) { // (X / pos) op 0
839 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000840 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
841 HiBound = RangeSize;
Chris Lattner02446fc2010-01-04 07:37:31 +0000842 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
843 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
844 HiOverflow = LoOverflow = ProdOV;
845 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000846 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000847 } else { // (X / pos) op neg
848 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
849 HiBound = AddOne(Prod);
850 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
851 if (!LoOverflow) {
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000852 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000853 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000854 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000855 }
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000856 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000857 if (DivI->isExact())
858 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000859 if (CmpRHSV == 0) { // (X / neg) op 0
860 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000861 LoBound = AddOne(RangeSize);
862 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000863 if (HiBound == DivRHS) { // -INTMIN = INTMIN
864 HiOverflow = 1; // [INTMIN+1, overflow)
865 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
866 }
867 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
868 // e.g. X/-5 op 3 --> [-19, -14)
869 HiBound = AddOne(Prod);
870 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
871 if (!LoOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000872 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner02446fc2010-01-04 07:37:31 +0000873 } else { // (X / neg) op neg
874 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
875 LoOverflow = HiOverflow = ProdOV;
876 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000877 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000878 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000879
Chris Lattner02446fc2010-01-04 07:37:31 +0000880 // Dividing by a negative swaps the condition. LT <-> GT
881 Pred = ICmpInst::getSwappedPredicate(Pred);
882 }
883
884 Value *X = DivI->getOperand(0);
885 switch (Pred) {
886 default: llvm_unreachable("Unhandled icmp opcode!");
887 case ICmpInst::ICMP_EQ:
888 if (LoOverflow && HiOverflow)
889 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000890 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000891 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
892 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000893 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000894 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
895 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000896 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
897 DivIsSigned, true));
Chris Lattner02446fc2010-01-04 07:37:31 +0000898 case ICmpInst::ICMP_NE:
899 if (LoOverflow && HiOverflow)
900 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000901 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000902 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
903 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000904 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000905 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
906 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000907 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
908 DivIsSigned, false));
Chris Lattner02446fc2010-01-04 07:37:31 +0000909 case ICmpInst::ICMP_ULT:
910 case ICmpInst::ICMP_SLT:
911 if (LoOverflow == +1) // Low bound is greater than input range.
912 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
913 if (LoOverflow == -1) // Low bound is less than input range.
914 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
915 return new ICmpInst(Pred, X, LoBound);
916 case ICmpInst::ICMP_UGT:
917 case ICmpInst::ICMP_SGT:
918 if (HiOverflow == +1) // High bound greater than input range.
919 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000920 if (HiOverflow == -1) // High bound less than input range.
Chris Lattner02446fc2010-01-04 07:37:31 +0000921 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
922 if (Pred == ICmpInst::ICMP_UGT)
923 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000924 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner02446fc2010-01-04 07:37:31 +0000925 }
926}
927
Chris Lattner74542aa2011-02-13 07:43:07 +0000928/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
929Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
930 ConstantInt *ShAmt) {
Chris Lattner74542aa2011-02-13 07:43:07 +0000931 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000932
Chris Lattner74542aa2011-02-13 07:43:07 +0000933 // Check that the shift amount is in range. If not, don't perform
934 // undefined shifts. When the shift is visited it will be
935 // simplified.
936 uint32_t TypeBits = CmpRHSV.getBitWidth();
937 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnerbb75d332011-02-13 08:07:21 +0000938 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattner74542aa2011-02-13 07:43:07 +0000939 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000940
Chris Lattnerbb75d332011-02-13 08:07:21 +0000941 if (!ICI.isEquality()) {
942 // If we have an unsigned comparison and an ashr, we can't simplify this.
943 // Similarly for signed comparisons with lshr.
944 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
945 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000946
Eli Friedmana831a9b2011-05-25 23:26:20 +0000947 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
948 // by a power of 2. Since we already have logic to simplify these,
949 // transform to div and then simplify the resultant comparison.
Chris Lattnerbb75d332011-02-13 08:07:21 +0000950 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedmana831a9b2011-05-25 23:26:20 +0000951 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattnerbb75d332011-02-13 08:07:21 +0000952 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000953
Chris Lattnerbb75d332011-02-13 08:07:21 +0000954 // Revisit the shift (to delete it).
955 Worklist.Add(Shr);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000956
Chris Lattnerbb75d332011-02-13 08:07:21 +0000957 Constant *DivCst =
958 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000959
Chris Lattnerbb75d332011-02-13 08:07:21 +0000960 Value *Tmp =
961 Shr->getOpcode() == Instruction::AShr ?
962 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
963 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000964
Chris Lattnerbb75d332011-02-13 08:07:21 +0000965 ICI.setOperand(0, Tmp);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000966
Chris Lattnerbb75d332011-02-13 08:07:21 +0000967 // If the builder folded the binop, just return it.
968 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
969 if (TheDiv == 0)
970 return &ICI;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000971
Chris Lattnerbb75d332011-02-13 08:07:21 +0000972 // Otherwise, fold this div/compare.
973 assert(TheDiv->getOpcode() == Instruction::SDiv ||
974 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000975
Chris Lattnerbb75d332011-02-13 08:07:21 +0000976 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
977 assert(Res && "This div/cst should have folded!");
978 return Res;
979 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000980
981
Chris Lattner74542aa2011-02-13 07:43:07 +0000982 // If we are comparing against bits always shifted out, the
983 // comparison cannot succeed.
984 APInt Comp = CmpRHSV << ShAmtVal;
985 ConstantInt *ShiftedCmpRHS = ConstantInt::get(ICI.getContext(), Comp);
986 if (Shr->getOpcode() == Instruction::LShr)
987 Comp = Comp.lshr(ShAmtVal);
988 else
989 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000990
Chris Lattner74542aa2011-02-13 07:43:07 +0000991 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
992 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
993 Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
994 IsICMP_NE);
995 return ReplaceInstUsesWith(ICI, Cst);
996 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000997
Chris Lattner74542aa2011-02-13 07:43:07 +0000998 // Otherwise, check to see if the bits shifted out are known to be zero.
999 // If so, we can compare against the unshifted value:
1000 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattnere5116f82011-02-13 18:30:09 +00001001 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattner74542aa2011-02-13 07:43:07 +00001002 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001003
Chris Lattner74542aa2011-02-13 07:43:07 +00001004 if (Shr->hasOneUse()) {
1005 // Otherwise strength reduce the shift into an and.
1006 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1007 Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001008
Chris Lattner74542aa2011-02-13 07:43:07 +00001009 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1010 Mask, Shr->getName()+".mask");
1011 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1012 }
1013 return 0;
1014}
1015
Chris Lattner02446fc2010-01-04 07:37:31 +00001016
1017/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1018///
1019Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1020 Instruction *LHSI,
1021 ConstantInt *RHS) {
1022 const APInt &RHSV = RHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001023
Chris Lattner02446fc2010-01-04 07:37:31 +00001024 switch (LHSI->getOpcode()) {
1025 case Instruction::Trunc:
1026 if (ICI.isEquality() && LHSI->hasOneUse()) {
1027 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1028 // of the high bits truncated out of x are known.
1029 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1030 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1031 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
1032 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1033 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001034
Chris Lattner02446fc2010-01-04 07:37:31 +00001035 // If all the high bits are known, we can do this xform.
1036 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1037 // Pull in the high bits from known-ones set.
Jay Foad40f8f622010-12-07 08:25:19 +00001038 APInt NewRHS = RHS->getValue().zext(SrcBits);
Chris Lattner02446fc2010-01-04 07:37:31 +00001039 NewRHS |= KnownOne;
1040 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1041 ConstantInt::get(ICI.getContext(), NewRHS));
1042 }
1043 }
1044 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001045
Chris Lattner02446fc2010-01-04 07:37:31 +00001046 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
1047 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1048 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1049 // fold the xor.
1050 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1051 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1052 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001053
Chris Lattner02446fc2010-01-04 07:37:31 +00001054 // If the sign bit of the XorCST is not set, there is no change to
1055 // the operation, just stop using the Xor.
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001056 if (!XorCST->isNegative()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001057 ICI.setOperand(0, CompareVal);
1058 Worklist.Add(LHSI);
1059 return &ICI;
1060 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001061
Chris Lattner02446fc2010-01-04 07:37:31 +00001062 // Was the old condition true if the operand is positive?
1063 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001064
Chris Lattner02446fc2010-01-04 07:37:31 +00001065 // If so, the new one isn't.
1066 isTrueIfPositive ^= true;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001067
Chris Lattner02446fc2010-01-04 07:37:31 +00001068 if (isTrueIfPositive)
1069 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1070 SubOne(RHS));
1071 else
1072 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1073 AddOne(RHS));
1074 }
1075
1076 if (LHSI->hasOneUse()) {
1077 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1078 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1079 const APInt &SignBit = XorCST->getValue();
1080 ICmpInst::Predicate Pred = ICI.isSigned()
1081 ? ICI.getUnsignedPredicate()
1082 : ICI.getSignedPredicate();
1083 return new ICmpInst(Pred, LHSI->getOperand(0),
1084 ConstantInt::get(ICI.getContext(),
1085 RHSV ^ SignBit));
1086 }
1087
1088 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001089 if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001090 const APInt &NotSignBit = XorCST->getValue();
1091 ICmpInst::Predicate Pred = ICI.isSigned()
1092 ? ICI.getUnsignedPredicate()
1093 : ICI.getSignedPredicate();
1094 Pred = ICI.getSwappedPredicate(Pred);
1095 return new ICmpInst(Pred, LHSI->getOperand(0),
1096 ConstantInt::get(ICI.getContext(),
1097 RHSV ^ NotSignBit));
1098 }
1099 }
1100 }
1101 break;
1102 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
1103 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1104 LHSI->getOperand(0)->hasOneUse()) {
1105 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001106
Chris Lattner02446fc2010-01-04 07:37:31 +00001107 // If the LHS is an AND of a truncating cast, we can widen the
1108 // and/compare to be the input width without changing the value
1109 // produced, eliminating a cast.
1110 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1111 // We can do this transformation if either the AND constant does not
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001112 // have its sign bit set or if it is an equality comparison.
Chris Lattner02446fc2010-01-04 07:37:31 +00001113 // Extending a relational comparison when we're checking the sign
1114 // bit would not work.
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001115 if (ICI.isEquality() ||
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001116 (!AndCST->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001117 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001118 Builder->CreateAnd(Cast->getOperand(0),
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001119 ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1120 NewAnd->takeName(LHSI);
Chris Lattner02446fc2010-01-04 07:37:31 +00001121 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001122 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001123 }
1124 }
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001125
1126 // If the LHS is an AND of a zext, and we have an equality compare, we can
1127 // shrink the and/compare to the smaller type, eliminating the cast.
1128 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001129 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001130 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1131 // should fold the icmp to true/false in that case.
1132 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1133 Value *NewAnd =
1134 Builder->CreateAnd(Cast->getOperand(0),
1135 ConstantExpr::getTrunc(AndCST, Ty));
1136 NewAnd->takeName(LHSI);
1137 return new ICmpInst(ICI.getPredicate(), NewAnd,
1138 ConstantExpr::getTrunc(RHS, Ty));
1139 }
1140 }
1141
Chris Lattner02446fc2010-01-04 07:37:31 +00001142 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1143 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1144 // happens a LOT in code produced by the C front-end, for bitfield
1145 // access.
1146 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1147 if (Shift && !Shift->isShift())
1148 Shift = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001149
Chris Lattner02446fc2010-01-04 07:37:31 +00001150 ConstantInt *ShAmt;
1151 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001152 Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
1153 Type *AndTy = AndCST->getType(); // Type of the and.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001154
Chris Lattner02446fc2010-01-04 07:37:31 +00001155 // We can fold this as long as we can't shift unknown bits
1156 // into the mask. This can only happen with signed shift
1157 // rights, as they sign-extend.
1158 if (ShAmt) {
1159 bool CanFold = Shift->isLogicalShift();
1160 if (!CanFold) {
1161 // To test for the bad case of the signed shr, see if any
1162 // of the bits shifted in could be tested after the mask.
1163 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1164 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001165
Chris Lattner02446fc2010-01-04 07:37:31 +00001166 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001167 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
Chris Lattner02446fc2010-01-04 07:37:31 +00001168 AndCST->getValue()) == 0)
1169 CanFold = true;
1170 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001171
Chris Lattner02446fc2010-01-04 07:37:31 +00001172 if (CanFold) {
1173 Constant *NewCst;
1174 if (Shift->getOpcode() == Instruction::Shl)
1175 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1176 else
1177 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001178
Chris Lattner02446fc2010-01-04 07:37:31 +00001179 // Check to see if we are shifting out any of the bits being
1180 // compared.
1181 if (ConstantExpr::get(Shift->getOpcode(),
1182 NewCst, ShAmt) != RHS) {
1183 // If we shifted bits out, the fold is not going to work out.
1184 // As a special case, check to see if this means that the
1185 // result is always true or false now.
1186 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1187 return ReplaceInstUsesWith(ICI,
1188 ConstantInt::getFalse(ICI.getContext()));
1189 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1190 return ReplaceInstUsesWith(ICI,
1191 ConstantInt::getTrue(ICI.getContext()));
1192 } else {
1193 ICI.setOperand(1, NewCst);
1194 Constant *NewAndCST;
1195 if (Shift->getOpcode() == Instruction::Shl)
1196 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1197 else
1198 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1199 LHSI->setOperand(1, NewAndCST);
1200 LHSI->setOperand(0, Shift->getOperand(0));
1201 Worklist.Add(Shift); // Shift is dead.
1202 return &ICI;
1203 }
1204 }
1205 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001206
Chris Lattner02446fc2010-01-04 07:37:31 +00001207 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1208 // preferable because it allows the C<<Y expression to be hoisted out
1209 // of a loop if Y is invariant and X is not.
1210 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1211 ICI.isEquality() && !Shift->isArithmeticShift() &&
1212 !isa<Constant>(Shift->getOperand(0))) {
1213 // Compute C << Y.
1214 Value *NS;
1215 if (Shift->getOpcode() == Instruction::LShr) {
Benjamin Kramera9390a42011-09-27 20:39:19 +00001216 NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001217 } else {
1218 // Insert a logical shift.
Benjamin Kramera9390a42011-09-27 20:39:19 +00001219 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001220 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001221
Chris Lattner02446fc2010-01-04 07:37:31 +00001222 // Compute X & (C << Y).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001223 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001224 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001225
Chris Lattner02446fc2010-01-04 07:37:31 +00001226 ICI.setOperand(0, NewAnd);
1227 return &ICI;
1228 }
1229 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001230
Chris Lattner02446fc2010-01-04 07:37:31 +00001231 // Try to optimize things like "A[i]&42 == 0" to index computations.
1232 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1233 if (GetElementPtrInst *GEP =
1234 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1235 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1236 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1237 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1238 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1239 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1240 return Res;
1241 }
1242 }
1243 break;
1244
1245 case Instruction::Or: {
1246 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1247 break;
1248 Value *P, *Q;
1249 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1250 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1251 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner02446fc2010-01-04 07:37:31 +00001252 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1253 Constant::getNullValue(P->getType()));
1254 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1255 Constant::getNullValue(Q->getType()));
1256 Instruction *Op;
1257 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1258 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1259 else
1260 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1261 return Op;
1262 }
1263 break;
1264 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001265
Chris Lattner02446fc2010-01-04 07:37:31 +00001266 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
1267 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1268 if (!ShAmt) break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001269
Chris Lattner02446fc2010-01-04 07:37:31 +00001270 uint32_t TypeBits = RHSV.getBitWidth();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001271
Chris Lattner02446fc2010-01-04 07:37:31 +00001272 // Check that the shift amount is in range. If not, don't perform
1273 // undefined shifts. When the shift is visited it will be
1274 // simplified.
1275 if (ShAmt->uge(TypeBits))
1276 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001277
Chris Lattner02446fc2010-01-04 07:37:31 +00001278 if (ICI.isEquality()) {
1279 // If we are comparing against bits always shifted out, the
1280 // comparison cannot succeed.
1281 Constant *Comp =
1282 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1283 ShAmt);
1284 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1285 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1286 Constant *Cst =
1287 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1288 return ReplaceInstUsesWith(ICI, Cst);
1289 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001290
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001291 // If the shift is NUW, then it is just shifting out zeros, no need for an
1292 // AND.
1293 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1294 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1295 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001296
Chris Lattner02446fc2010-01-04 07:37:31 +00001297 if (LHSI->hasOneUse()) {
1298 // Otherwise strength reduce the shift into an and.
1299 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1300 Constant *Mask =
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001301 ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
Chris Lattner02446fc2010-01-04 07:37:31 +00001302 TypeBits-ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001303
Chris Lattner02446fc2010-01-04 07:37:31 +00001304 Value *And =
1305 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1306 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001307 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner02446fc2010-01-04 07:37:31 +00001308 }
1309 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001310
Chris Lattner02446fc2010-01-04 07:37:31 +00001311 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1312 bool TrueIfSigned = false;
1313 if (LHSI->hasOneUse() &&
1314 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1315 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattnerbb75d332011-02-13 08:07:21 +00001316 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001317 APInt::getOneBitSet(TypeBits,
Chris Lattnerbb75d332011-02-13 08:07:21 +00001318 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001319 Value *And =
1320 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1321 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1322 And, Constant::getNullValue(And->getType()));
1323 }
1324 break;
1325 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001326
Chris Lattner02446fc2010-01-04 07:37:31 +00001327 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001328 case Instruction::AShr: {
1329 // Handle equality comparisons of shift-by-constant.
1330 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1331 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1332 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattner74542aa2011-02-13 07:43:07 +00001333 return Res;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001334 }
1335
1336 // Handle exact shr's.
1337 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1338 if (RHSV.isMinValue())
1339 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1340 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001341 break;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001342 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001343
Chris Lattner02446fc2010-01-04 07:37:31 +00001344 case Instruction::SDiv:
1345 case Instruction::UDiv:
1346 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001347 // Fold this div into the comparison, producing a range check.
1348 // Determine, based on the divide type, what the range is being
1349 // checked. If there is an overflow on the low or high side, remember
Chris Lattner02446fc2010-01-04 07:37:31 +00001350 // it, otherwise compute the range [low, hi) bounding the new value.
1351 // See: InsertRangeTest above for the kinds of replacements possible.
1352 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1353 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1354 DivRHS))
1355 return R;
1356 break;
1357
1358 case Instruction::Add:
1359 // Fold: icmp pred (add X, C1), C2
1360 if (!ICI.isEquality()) {
1361 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1362 if (!LHSC) break;
1363 const APInt &LHSV = LHSC->getValue();
1364
1365 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1366 .subtract(LHSV);
1367
1368 if (ICI.isSigned()) {
1369 if (CR.getLower().isSignBit()) {
1370 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1371 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1372 } else if (CR.getUpper().isSignBit()) {
1373 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1374 ConstantInt::get(ICI.getContext(),CR.getLower()));
1375 }
1376 } else {
1377 if (CR.getLower().isMinValue()) {
1378 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1379 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1380 } else if (CR.getUpper().isMinValue()) {
1381 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1382 ConstantInt::get(ICI.getContext(),CR.getLower()));
1383 }
1384 }
1385 }
1386 break;
1387 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001388
Chris Lattner02446fc2010-01-04 07:37:31 +00001389 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1390 if (ICI.isEquality()) {
1391 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001392
1393 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner02446fc2010-01-04 07:37:31 +00001394 // the second operand is a constant, simplify a bit.
1395 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1396 switch (BO->getOpcode()) {
1397 case Instruction::SRem:
1398 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1399 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1400 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohmane0567812010-04-08 23:03:40 +00001401 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001402 Value *NewRem =
1403 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1404 BO->getName());
1405 return new ICmpInst(ICI.getPredicate(), NewRem,
1406 Constant::getNullValue(BO->getType()));
1407 }
1408 }
1409 break;
1410 case Instruction::Add:
1411 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1412 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1413 if (BO->hasOneUse())
1414 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1415 ConstantExpr::getSub(RHS, BOp1C));
1416 } else if (RHSV == 0) {
1417 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1418 // efficiently invertible, or if the add has just this one use.
1419 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001420
Chris Lattner02446fc2010-01-04 07:37:31 +00001421 if (Value *NegVal = dyn_castNegVal(BOp1))
1422 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner5036ce42011-04-26 20:02:45 +00001423 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner02446fc2010-01-04 07:37:31 +00001424 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner5036ce42011-04-26 20:02:45 +00001425 if (BO->hasOneUse()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001426 Value *Neg = Builder->CreateNeg(BOp1);
1427 Neg->takeName(BO);
1428 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1429 }
1430 }
1431 break;
1432 case Instruction::Xor:
1433 // For the xor case, we can xor two constants together, eliminating
1434 // the explicit xor.
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001435 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1436 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner02446fc2010-01-04 07:37:31 +00001437 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001438 } else if (RHSV == 0) {
1439 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner02446fc2010-01-04 07:37:31 +00001440 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1441 BO->getOperand(1));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001442 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001443 break;
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001444 case Instruction::Sub:
1445 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1446 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1447 if (BO->hasOneUse())
1448 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1449 ConstantExpr::getSub(BOp0C, RHS));
1450 } else if (RHSV == 0) {
1451 // Replace ((sub A, B) != 0) with (A != B)
1452 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1453 BO->getOperand(1));
1454 }
1455 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001456 case Instruction::Or:
1457 // If bits are being or'd in that are not present in the constant we
1458 // are comparing against, then the comparison could never succeed!
Eli Friedman618898e2010-07-29 18:03:33 +00001459 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001460 Constant *NotCI = ConstantExpr::getNot(RHS);
1461 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1462 return ReplaceInstUsesWith(ICI,
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001463 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Chris Lattner02446fc2010-01-04 07:37:31 +00001464 isICMP_NE));
1465 }
1466 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001467
Chris Lattner02446fc2010-01-04 07:37:31 +00001468 case Instruction::And:
1469 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1470 // If bits are being compared against that are and'd out, then the
1471 // comparison can never succeed!
1472 if ((RHSV & ~BOC->getValue()) != 0)
1473 return ReplaceInstUsesWith(ICI,
1474 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1475 isICMP_NE));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001476
Chris Lattner02446fc2010-01-04 07:37:31 +00001477 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1478 if (RHS == BOC && RHSV.isPowerOf2())
1479 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1480 ICmpInst::ICMP_NE, LHSI,
1481 Constant::getNullValue(RHS->getType()));
Benjamin Kramerfc87cdc2011-07-04 20:16:36 +00001482
1483 // Don't perform the following transforms if the AND has multiple uses
1484 if (!BO->hasOneUse())
1485 break;
1486
Chris Lattner02446fc2010-01-04 07:37:31 +00001487 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1488 if (BOC->getValue().isSignBit()) {
1489 Value *X = BO->getOperand(0);
1490 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001491 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001492 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1493 return new ICmpInst(pred, X, Zero);
1494 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001495
Chris Lattner02446fc2010-01-04 07:37:31 +00001496 // ((X & ~7) == 0) --> X < 8
1497 if (RHSV == 0 && isHighOnes(BOC)) {
1498 Value *X = BO->getOperand(0);
1499 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001500 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001501 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1502 return new ICmpInst(pred, X, NegX);
1503 }
1504 }
1505 default: break;
1506 }
1507 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1508 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner03357402010-01-05 18:09:56 +00001509 switch (II->getIntrinsicID()) {
1510 case Intrinsic::bswap:
Chris Lattner02446fc2010-01-04 07:37:31 +00001511 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001512 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00001513 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1514 return &ICI;
Chris Lattner03357402010-01-05 18:09:56 +00001515 case Intrinsic::ctlz:
1516 case Intrinsic::cttz:
1517 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1518 if (RHSV == RHS->getType()->getBitWidth()) {
1519 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001520 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001521 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1522 return &ICI;
1523 }
1524 break;
1525 case Intrinsic::ctpop:
1526 // popcount(A) == 0 -> A == 0 and likewise for !=
1527 if (RHS->isZero()) {
1528 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001529 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001530 ICI.setOperand(1, RHS);
1531 return &ICI;
1532 }
1533 break;
1534 default:
Duncan Sands34727662010-07-12 08:16:59 +00001535 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001536 }
1537 }
1538 }
1539 return 0;
1540}
1541
1542/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1543/// We only handle extending casts so far.
1544///
1545Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1546 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1547 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001548 Type *SrcTy = LHSCIOp->getType();
1549 Type *DestTy = LHSCI->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001550 Value *RHSCIOp;
1551
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001552 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner02446fc2010-01-04 07:37:31 +00001553 // integer type is the same size as the pointer type.
1554 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1555 TD->getPointerSizeInBits() ==
1556 cast<IntegerType>(DestTy)->getBitWidth()) {
1557 Value *RHSOp = 0;
1558 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1559 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1560 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1561 RHSOp = RHSC->getOperand(0);
1562 // If the pointer types don't match, insert a bitcast.
1563 if (LHSCIOp->getType() != RHSOp->getType())
1564 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1565 }
1566
1567 if (RHSOp)
1568 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1569 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001570
Chris Lattner02446fc2010-01-04 07:37:31 +00001571 // The code below only handles extension cast instructions, so far.
1572 // Enforce this.
1573 if (LHSCI->getOpcode() != Instruction::ZExt &&
1574 LHSCI->getOpcode() != Instruction::SExt)
1575 return 0;
1576
1577 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1578 bool isSignedCmp = ICI.isSigned();
1579
1580 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1581 // Not an extension from the same type?
1582 RHSCIOp = CI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001583 if (RHSCIOp->getType() != LHSCIOp->getType())
Chris Lattner02446fc2010-01-04 07:37:31 +00001584 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001585
Chris Lattner02446fc2010-01-04 07:37:31 +00001586 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1587 // and the other is a zext), then we can't handle this.
1588 if (CI->getOpcode() != LHSCI->getOpcode())
1589 return 0;
1590
1591 // Deal with equality cases early.
1592 if (ICI.isEquality())
1593 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1594
1595 // A signed comparison of sign extended values simplifies into a
1596 // signed comparison.
1597 if (isSignedCmp && isSignedExt)
1598 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1599
1600 // The other three cases all fold into an unsigned comparison.
1601 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1602 }
1603
1604 // If we aren't dealing with a constant on the RHS, exit early
1605 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1606 if (!CI)
1607 return 0;
1608
1609 // Compute the constant that would happen if we truncated to SrcTy then
1610 // reextended to DestTy.
1611 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1612 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1613 Res1, DestTy);
1614
1615 // If the re-extended constant didn't change...
1616 if (Res2 == CI) {
1617 // Deal with equality cases early.
1618 if (ICI.isEquality())
1619 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1620
1621 // A signed comparison of sign extended values simplifies into a
1622 // signed comparison.
1623 if (isSignedExt && isSignedCmp)
1624 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1625
1626 // The other three cases all fold into an unsigned comparison.
1627 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1628 }
1629
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001630 // The re-extended constant changed so the constant cannot be represented
Chris Lattner02446fc2010-01-04 07:37:31 +00001631 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands9d32f602011-01-20 13:21:55 +00001632 // All the cases that fold to true or false will have already been handled
1633 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner02446fc2010-01-04 07:37:31 +00001634
Duncan Sands9d32f602011-01-20 13:21:55 +00001635 if (isSignedCmp || !isSignedExt)
1636 return 0;
Chris Lattner02446fc2010-01-04 07:37:31 +00001637
1638 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1639 // should have been folded away previously and not enter in here.
Duncan Sands9d32f602011-01-20 13:21:55 +00001640
1641 // We're performing an unsigned comp with a sign extended value.
1642 // This is true if the input is >= 0. [aka >s -1]
1643 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1644 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner02446fc2010-01-04 07:37:31 +00001645
1646 // Finally, return the value computed.
Duncan Sands9d32f602011-01-20 13:21:55 +00001647 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner02446fc2010-01-04 07:37:31 +00001648 return ReplaceInstUsesWith(ICI, Result);
1649
Duncan Sands9d32f602011-01-20 13:21:55 +00001650 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner02446fc2010-01-04 07:37:31 +00001651 return BinaryOperator::CreateNot(Result);
1652}
1653
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001654/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1655/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001656/// If this is of the form:
1657/// sum = a + b
1658/// if (sum+128 >u 255)
1659/// Then replace it with llvm.sadd.with.overflow.i8.
1660///
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001661static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1662 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001663 InstCombiner &IC) {
Chris Lattner368397b2010-12-19 17:59:02 +00001664 // The transformation we're trying to do here is to transform this into an
1665 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1666 // with a narrower add, and discard the add-with-constant that is part of the
1667 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001668
Chris Lattner368397b2010-12-19 17:59:02 +00001669 // In order to eliminate the add-with-constant, the compare can be its only
1670 // use.
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001671 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattner368397b2010-12-19 17:59:02 +00001672 if (!AddWithCst->hasOneUse()) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001673
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001674 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1675 if (!CI2->getValue().isPowerOf2()) return 0;
1676 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1677 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001678
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001679 // The width of the new add formed is 1 more than the bias.
1680 ++NewWidth;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001681
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001682 // Check to see that CI1 is an all-ones value with NewWidth bits.
1683 if (CI1->getBitWidth() == NewWidth ||
1684 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1685 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001686
Eli Friedman54b92112011-11-28 23:32:19 +00001687 // This is only really a signed overflow check if the inputs have been
1688 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1689 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1690 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1691 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1692 IC.ComputeNumSignBits(B) < NeededSignBits)
1693 return 0;
1694
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001695 // In order to replace the original add with a narrower
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001696 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1697 // and truncates that discard the high bits of the add. Verify that this is
1698 // the case.
1699 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1700 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1701 UI != E; ++UI) {
1702 if (*UI == AddWithCst) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001703
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001704 // Only accept truncates for now. We would really like a nice recursive
1705 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1706 // chain to see which bits of a value are actually demanded. If the
1707 // original add had another add which was then immediately truncated, we
1708 // could still do the transformation.
1709 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1710 if (TI == 0 ||
1711 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1712 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001713
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001714 // If the pattern matches, truncate the inputs to the narrower type and
1715 // use the sadd_with_overflow intrinsic to efficiently compute both the
1716 // result and the overflow bit.
Chris Lattner0a624742010-12-19 18:35:09 +00001717 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001718
Jay Foad5fdd6c82011-07-12 14:06:48 +00001719 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner0a624742010-12-19 18:35:09 +00001720 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001721 NewType);
Chris Lattner0a624742010-12-19 18:35:09 +00001722
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001723 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001724
Chris Lattner0a624742010-12-19 18:35:09 +00001725 // Put the new code above the original add, in case there are any uses of the
1726 // add between the add and the compare.
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001727 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001728
Chris Lattner0a624742010-12-19 18:35:09 +00001729 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1730 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1731 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1732 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1733 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001734
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001735 // The inner add was the result of the narrow add, zero extended to the
1736 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001737 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001738
Chris Lattner0a624742010-12-19 18:35:09 +00001739 // The original icmp gets replaced with the overflow value.
1740 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001741}
Chris Lattner02446fc2010-01-04 07:37:31 +00001742
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001743static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1744 InstCombiner &IC) {
1745 // Don't bother doing this transformation for pointers, don't do it for
1746 // vectors.
1747 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001748
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001749 // If the add is a constant expr, then we don't bother transforming it.
1750 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1751 if (OrigAdd == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001752
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001753 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001754
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001755 // Put the new code above the original add, in case there are any uses of the
1756 // add between the add and the compare.
1757 InstCombiner::BuilderTy *Builder = IC.Builder;
1758 Builder->SetInsertPoint(OrigAdd);
1759
1760 Module *M = I.getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001761 Type *Ty = LHS->getType();
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001762 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001763 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1764 Value *Add = Builder->CreateExtractValue(Call, 0);
1765
1766 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1767
1768 // The original icmp gets replaced with the overflow value.
1769 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1770}
1771
Owen Andersonda1c1222011-01-11 00:36:45 +00001772// DemandedBitsLHSMask - When performing a comparison against a constant,
1773// it is possible that not all the bits in the LHS are demanded. This helper
1774// method computes the mask that IS demanded.
1775static APInt DemandedBitsLHSMask(ICmpInst &I,
1776 unsigned BitWidth, bool isSignCheck) {
1777 if (isSignCheck)
1778 return APInt::getSignBit(BitWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001779
Owen Andersonda1c1222011-01-11 00:36:45 +00001780 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1781 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Andersona33b6252011-01-11 18:26:37 +00001782 const APInt &RHS = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001783
Owen Andersonda1c1222011-01-11 00:36:45 +00001784 switch (I.getPredicate()) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001785 // For a UGT comparison, we don't care about any bits that
Owen Andersonda1c1222011-01-11 00:36:45 +00001786 // correspond to the trailing ones of the comparand. The value of these
1787 // bits doesn't impact the outcome of the comparison, because any value
1788 // greater than the RHS must differ in a bit higher than these due to carry.
1789 case ICmpInst::ICMP_UGT: {
1790 unsigned trailingOnes = RHS.countTrailingOnes();
1791 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1792 return ~lowBitsSet;
1793 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001794
Owen Andersonda1c1222011-01-11 00:36:45 +00001795 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1796 // Any value less than the RHS must differ in a higher bit because of carries.
1797 case ICmpInst::ICMP_ULT: {
1798 unsigned trailingZeros = RHS.countTrailingZeros();
1799 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1800 return ~lowBitsSet;
1801 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001802
Owen Andersonda1c1222011-01-11 00:36:45 +00001803 default:
1804 return APInt::getAllOnesValue(BitWidth);
1805 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001806
Owen Andersonda1c1222011-01-11 00:36:45 +00001807}
Chris Lattner02446fc2010-01-04 07:37:31 +00001808
1809Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1810 bool Changed = false;
Chris Lattner5f670d42010-02-01 19:54:45 +00001811 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001812
Chris Lattner02446fc2010-01-04 07:37:31 +00001813 /// Orders the operands of the compare so that they are listed from most
1814 /// complex to least complex. This puts constants before unary operators,
1815 /// before binary operators.
Chris Lattner5f670d42010-02-01 19:54:45 +00001816 if (getComplexity(Op0) < getComplexity(Op1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001817 I.swapOperands();
Chris Lattner5f670d42010-02-01 19:54:45 +00001818 std::swap(Op0, Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001819 Changed = true;
1820 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001821
Chris Lattner02446fc2010-01-04 07:37:31 +00001822 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1823 return ReplaceInstUsesWith(I, V);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001824
Pete Cooper65a6b572011-12-01 03:58:40 +00001825 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooper165695d2011-12-01 19:13:26 +00001826 // ie, abs(val) != 0 -> val != 0
Pete Cooper65a6b572011-12-01 03:58:40 +00001827 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
1828 {
Pete Cooper165695d2011-12-01 19:13:26 +00001829 Value *Cond, *SelectTrue, *SelectFalse;
1830 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooper65a6b572011-12-01 03:58:40 +00001831 m_Value(SelectFalse)))) {
Pete Cooper165695d2011-12-01 19:13:26 +00001832 if (Value *V = dyn_castNegVal(SelectTrue)) {
1833 if (V == SelectFalse)
1834 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
1835 }
1836 else if (Value *V = dyn_castNegVal(SelectFalse)) {
1837 if (V == SelectTrue)
1838 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooper65a6b572011-12-01 03:58:40 +00001839 }
1840 }
1841 }
1842
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001843 Type *Ty = Op0->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001844
1845 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001846 if (Ty->isIntegerTy(1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001847 switch (I.getPredicate()) {
1848 default: llvm_unreachable("Invalid icmp instruction!");
1849 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
1850 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1851 return BinaryOperator::CreateNot(Xor);
1852 }
1853 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
1854 return BinaryOperator::CreateXor(Op0, Op1);
1855
1856 case ICmpInst::ICMP_UGT:
1857 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
1858 // FALL THROUGH
1859 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
1860 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1861 return BinaryOperator::CreateAnd(Not, Op1);
1862 }
1863 case ICmpInst::ICMP_SGT:
1864 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
1865 // FALL THROUGH
1866 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
1867 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1868 return BinaryOperator::CreateAnd(Not, Op0);
1869 }
1870 case ICmpInst::ICMP_UGE:
1871 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
1872 // FALL THROUGH
1873 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
1874 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1875 return BinaryOperator::CreateOr(Not, Op1);
1876 }
1877 case ICmpInst::ICMP_SGE:
1878 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
1879 // FALL THROUGH
1880 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
1881 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1882 return BinaryOperator::CreateOr(Not, Op0);
1883 }
1884 }
1885 }
1886
1887 unsigned BitWidth = 0;
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001888 if (Ty->isIntOrIntVectorTy())
Chris Lattner02446fc2010-01-04 07:37:31 +00001889 BitWidth = Ty->getScalarSizeInBits();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001890 else if (TD) // Pointers require TD info to get their size.
1891 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001892
Chris Lattner02446fc2010-01-04 07:37:31 +00001893 bool isSignBit = false;
1894
1895 // See if we are doing a comparison with a constant.
1896 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1897 Value *A = 0, *B = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001898
Owen Andersone63dda52010-12-17 18:08:00 +00001899 // Match the following pattern, which is a common idiom when writing
1900 // overflow-safe integer arithmetic function. The source performs an
1901 // addition in wider type, and explicitly checks for overflow using
1902 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
1903 // sadd_with_overflow intrinsic.
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001904 //
1905 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001906 // operations if we worked out the formulas to compute the appropriate
Owen Andersone63dda52010-12-17 18:08:00 +00001907 // magic constants.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001908 //
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001909 // sum = a + b
1910 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Andersone63dda52010-12-17 18:08:00 +00001911 {
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001912 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Andersone63dda52010-12-17 18:08:00 +00001913 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001914 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001915 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001916 return Res;
Owen Andersone63dda52010-12-17 18:08:00 +00001917 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001918
Chris Lattner02446fc2010-01-04 07:37:31 +00001919 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1920 if (I.isEquality() && CI->isZero() &&
1921 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1922 // (icmp cond A B) if cond is equality
1923 return new ICmpInst(I.getPredicate(), A, B);
1924 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001925
Chris Lattner02446fc2010-01-04 07:37:31 +00001926 // If we have an icmp le or icmp ge instruction, turn it into the
1927 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
1928 // them being folded in the code below. The SimplifyICmpInst code has
1929 // already handled the edge cases for us, so we just assert on them.
1930 switch (I.getPredicate()) {
1931 default: break;
1932 case ICmpInst::ICMP_ULE:
1933 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
1934 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1935 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1936 case ICmpInst::ICMP_SLE:
1937 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
1938 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1939 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1940 case ICmpInst::ICMP_UGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001941 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001942 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1943 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1944 case ICmpInst::ICMP_SGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001945 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001946 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1947 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1948 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001949
Chris Lattner02446fc2010-01-04 07:37:31 +00001950 // If this comparison is a normal comparison, it demands all
1951 // bits, if it is a sign bit comparison, it only demands the sign bit.
1952 bool UnusedBit;
1953 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1954 }
1955
1956 // See if we can fold the comparison based on range information we can get
1957 // by checking whether bits are known to be zero or one in the input.
1958 if (BitWidth != 0) {
1959 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1960 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
1961
1962 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersonda1c1222011-01-11 00:36:45 +00001963 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner02446fc2010-01-04 07:37:31 +00001964 Op0KnownZero, Op0KnownOne, 0))
1965 return &I;
1966 if (SimplifyDemandedBits(I.getOperandUse(1),
1967 APInt::getAllOnesValue(BitWidth),
1968 Op1KnownZero, Op1KnownOne, 0))
1969 return &I;
1970
1971 // Given the known and unknown bits, compute a range that the LHS could be
1972 // in. Compute the Min, Max and RHS values based on the known bits. For the
1973 // EQ and NE we use unsigned values.
1974 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
1975 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
1976 if (I.isSigned()) {
1977 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1978 Op0Min, Op0Max);
1979 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1980 Op1Min, Op1Max);
1981 } else {
1982 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
1983 Op0Min, Op0Max);
1984 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
1985 Op1Min, Op1Max);
1986 }
1987
1988 // If Min and Max are known to be the same, then SimplifyDemandedBits
1989 // figured out that the LHS is a constant. Just constant fold this now so
1990 // that code below can assume that Min != Max.
1991 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
1992 return new ICmpInst(I.getPredicate(),
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001993 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001994 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
1995 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00001996 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner02446fc2010-01-04 07:37:31 +00001997
1998 // Based on the range information we know about the LHS, see if we can
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001999 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner02446fc2010-01-04 07:37:31 +00002000 switch (I.getPredicate()) {
2001 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner75d8f592010-11-21 06:44:42 +00002002 case ICmpInst::ICMP_EQ: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002003 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002004 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002005
Chris Lattner75d8f592010-11-21 06:44:42 +00002006 // If all bits are known zero except for one, then we know at most one
2007 // bit is set. If the comparison is against zero, then this is a check
2008 // to see if *that* bit is set.
2009 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2010 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2011 // If the LHS is an AND with the same constant, look through it.
2012 Value *LHS = 0;
2013 ConstantInt *LHSC = 0;
2014 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2015 LHSC->getValue() != Op0KnownZeroInverted)
2016 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002017
Chris Lattner75d8f592010-11-21 06:44:42 +00002018 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattner79b967b2010-11-23 02:42:04 +00002019 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002020 Value *X = 0;
2021 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2022 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002023 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002024 ConstantInt::get(X->getType(), CmpVal));
2025 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002026
Chris Lattner75d8f592010-11-21 06:44:42 +00002027 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattner79b967b2010-11-23 02:42:04 +00002028 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002029 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002030 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002031 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002032 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002033 ConstantInt::get(X->getType(),
2034 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002035 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002036
Chris Lattner02446fc2010-01-04 07:37:31 +00002037 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002038 }
2039 case ICmpInst::ICMP_NE: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002040 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002041 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002042
Chris Lattner75d8f592010-11-21 06:44:42 +00002043 // If all bits are known zero except for one, then we know at most one
2044 // bit is set. If the comparison is against zero, then this is a check
2045 // to see if *that* bit is set.
2046 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2047 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2048 // If the LHS is an AND with the same constant, look through it.
2049 Value *LHS = 0;
2050 ConstantInt *LHSC = 0;
2051 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2052 LHSC->getValue() != Op0KnownZeroInverted)
2053 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002054
Chris Lattner75d8f592010-11-21 06:44:42 +00002055 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattner79b967b2010-11-23 02:42:04 +00002056 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002057 Value *X = 0;
2058 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2059 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002060 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002061 ConstantInt::get(X->getType(), CmpVal));
2062 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002063
Chris Lattner75d8f592010-11-21 06:44:42 +00002064 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattner79b967b2010-11-23 02:42:04 +00002065 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002066 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002067 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002068 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002069 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002070 ConstantInt::get(X->getType(),
2071 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002072 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002073
Chris Lattner02446fc2010-01-04 07:37:31 +00002074 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002075 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002076 case ICmpInst::ICMP_ULT:
2077 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002078 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002079 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002080 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002081 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2082 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2083 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2084 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2085 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2086 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2087
2088 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2089 if (CI->isMinValue(true))
2090 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2091 Constant::getAllOnesValue(Op0->getType()));
2092 }
2093 break;
2094 case ICmpInst::ICMP_UGT:
2095 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002096 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002097 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002098 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002099
2100 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2101 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2102 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2103 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2104 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2105 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2106
2107 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2108 if (CI->isMaxValue(true))
2109 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2110 Constant::getNullValue(Op0->getType()));
2111 }
2112 break;
2113 case ICmpInst::ICMP_SLT:
2114 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002115 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002116 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002117 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002118 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2119 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2120 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2121 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2122 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2123 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2124 }
2125 break;
2126 case ICmpInst::ICMP_SGT:
2127 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002128 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002129 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002130 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002131
2132 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2133 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2134 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2135 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2136 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2137 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2138 }
2139 break;
2140 case ICmpInst::ICMP_SGE:
2141 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2142 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002143 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002144 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002145 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002146 break;
2147 case ICmpInst::ICMP_SLE:
2148 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2149 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002150 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002151 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002152 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002153 break;
2154 case ICmpInst::ICMP_UGE:
2155 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2156 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002157 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002158 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002159 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002160 break;
2161 case ICmpInst::ICMP_ULE:
2162 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2163 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002164 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002165 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002166 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002167 break;
2168 }
2169
2170 // Turn a signed comparison into an unsigned one if both operands
2171 // are known to have the same sign.
2172 if (I.isSigned() &&
2173 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2174 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2175 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2176 }
2177
2178 // Test if the ICmpInst instruction is used exclusively by a select as
2179 // part of a minimum or maximum operation. If so, refrain from doing
2180 // any other folding. This helps out other analyses which understand
2181 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2182 // and CodeGen. And in this case, at least one of the comparison
2183 // operands has at least one user besides the compare (the select),
2184 // which would often largely negate the benefit of folding anyway.
2185 if (I.hasOneUse())
2186 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2187 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2188 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2189 return 0;
2190
2191 // See if we are doing a comparison between a constant and an instruction that
2192 // can be folded into the comparison.
2193 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002194 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2195 // instruction, see if that instruction also has constants so that the
2196 // instruction can be folded into the icmp
Chris Lattner02446fc2010-01-04 07:37:31 +00002197 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2198 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2199 return Res;
2200 }
2201
2202 // Handle icmp with constant (but not simple integer constant) RHS
2203 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2204 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2205 switch (LHSI->getOpcode()) {
2206 case Instruction::GetElementPtr:
2207 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2208 if (RHSC->isNullValue() &&
2209 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2210 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2211 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2212 break;
2213 case Instruction::PHI:
2214 // Only fold icmp into the PHI if the phi and icmp are in the same
2215 // block. If in the same block, we're encouraging jump threading. If
2216 // not, we are just pessimizing the code by making an i1 phi.
2217 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002218 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002219 return NV;
2220 break;
2221 case Instruction::Select: {
2222 // If either operand of the select is a constant, we can fold the
2223 // comparison into the select arms, which will cause one to be
2224 // constant folded and the select turned into a bitwise or.
2225 Value *Op1 = 0, *Op2 = 0;
2226 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2227 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2228 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2229 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2230
2231 // We only want to perform this transformation if it will not lead to
2232 // additional code. This is true if either both sides of the select
2233 // fold to a constant (in which case the icmp is replaced with a select
2234 // which will usually simplify) or this is the only user of the
2235 // select (in which case we are trading a select+icmp for a simpler
2236 // select+icmp).
2237 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2238 if (!Op1)
2239 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2240 RHSC, I.getName());
2241 if (!Op2)
2242 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2243 RHSC, I.getName());
2244 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2245 }
2246 break;
2247 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002248 case Instruction::IntToPtr:
2249 // icmp pred inttoptr(X), null -> icmp pred X, 0
2250 if (RHSC->isNullValue() && TD &&
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002251 TD->getIntPtrType(RHSC->getContext()) ==
Chris Lattner02446fc2010-01-04 07:37:31 +00002252 LHSI->getOperand(0)->getType())
2253 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2254 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2255 break;
2256
2257 case Instruction::Load:
2258 // Try to optimize things like "A[i] > 4" to index computations.
2259 if (GetElementPtrInst *GEP =
2260 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2261 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2262 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2263 !cast<LoadInst>(LHSI)->isVolatile())
2264 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2265 return Res;
2266 }
2267 break;
2268 }
2269 }
2270
2271 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2272 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2273 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2274 return NI;
2275 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2276 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2277 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2278 return NI;
2279
2280 // Test to see if the operands of the icmp are casted versions of other
2281 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2282 // now.
2283 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002284 if (Op0->getType()->isPointerTy() &&
2285 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002286 // We keep moving the cast from the left operand over to the right
2287 // operand, where it can often be eliminated completely.
2288 Op0 = CI->getOperand(0);
2289
2290 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2291 // so eliminate it as well.
2292 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2293 Op1 = CI2->getOperand(0);
2294
2295 // If Op1 is a constant, we can fold the cast into the constant.
2296 if (Op0->getType() != Op1->getType()) {
2297 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2298 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2299 } else {
2300 // Otherwise, cast the RHS right before the icmp
2301 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2302 }
2303 }
2304 return new ICmpInst(I.getPredicate(), Op0, Op1);
2305 }
2306 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002307
Chris Lattner02446fc2010-01-04 07:37:31 +00002308 if (isa<CastInst>(Op0)) {
2309 // Handle the special case of: icmp (cast bool to X), <cst>
2310 // This comes up when you have code like
2311 // int X = A < B;
2312 // if (X) ...
2313 // For generality, we handle any zero-extension of any operand comparison
2314 // with a constant or another cast from the same type.
2315 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2316 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2317 return R;
2318 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002319
Duncan Sandsa7724332011-02-17 07:46:37 +00002320 // Special logic for binary operators.
2321 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2322 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2323 if (BO0 || BO1) {
2324 CmpInst::Predicate Pred = I.getPredicate();
2325 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2326 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2327 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2328 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2329 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2330 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2331 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2332 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2333 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2334
2335 // Analyze the case when either Op0 or Op1 is an add instruction.
2336 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2337 Value *A = 0, *B = 0, *C = 0, *D = 0;
2338 if (BO0 && BO0->getOpcode() == Instruction::Add)
2339 A = BO0->getOperand(0), B = BO0->getOperand(1);
2340 if (BO1 && BO1->getOpcode() == Instruction::Add)
2341 C = BO1->getOperand(0), D = BO1->getOperand(1);
2342
2343 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2344 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2345 return new ICmpInst(Pred, A == Op1 ? B : A,
2346 Constant::getNullValue(Op1->getType()));
2347
2348 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2349 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2350 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2351 C == Op0 ? D : C);
2352
Duncan Sands39a7de72011-02-18 16:25:37 +00002353 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002354 if (A && C && (A == C || A == D || B == C || B == D) &&
2355 NoOp0WrapProblem && NoOp1WrapProblem &&
2356 // Try not to increase register pressure.
2357 BO0->hasOneUse() && BO1->hasOneUse()) {
2358 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2359 Value *Y = (A == C || A == D) ? B : A;
2360 Value *Z = (C == A || C == B) ? D : C;
2361 return new ICmpInst(Pred, Y, Z);
2362 }
2363
2364 // Analyze the case when either Op0 or Op1 is a sub instruction.
2365 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2366 A = 0; B = 0; C = 0; D = 0;
2367 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2368 A = BO0->getOperand(0), B = BO0->getOperand(1);
2369 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2370 C = BO1->getOperand(0), D = BO1->getOperand(1);
2371
Duncan Sands39a7de72011-02-18 16:25:37 +00002372 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2373 if (A == Op1 && NoOp0WrapProblem)
2374 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2375
2376 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2377 if (C == Op0 && NoOp1WrapProblem)
2378 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2379
2380 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002381 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2382 // Try not to increase register pressure.
2383 BO0->hasOneUse() && BO1->hasOneUse())
2384 return new ICmpInst(Pred, A, C);
2385
Duncan Sands39a7de72011-02-18 16:25:37 +00002386 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2387 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2388 // Try not to increase register pressure.
2389 BO0->hasOneUse() && BO1->hasOneUse())
2390 return new ICmpInst(Pred, D, B);
2391
Nick Lewycky9feda172011-03-05 04:28:48 +00002392 BinaryOperator *SRem = NULL;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002393 // icmp (srem X, Y), Y
Nick Lewycky9feda172011-03-05 04:28:48 +00002394 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2395 Op1 == BO0->getOperand(1))
2396 SRem = BO0;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002397 // icmp Y, (srem X, Y)
Nick Lewycky9feda172011-03-05 04:28:48 +00002398 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2399 Op0 == BO1->getOperand(1))
2400 SRem = BO1;
2401 if (SRem) {
2402 // We don't check hasOneUse to avoid increasing register pressure because
2403 // the value we use is the same value this instruction was already using.
2404 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2405 default: break;
2406 case ICmpInst::ICMP_EQ:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002407 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002408 case ICmpInst::ICMP_NE:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002409 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002410 case ICmpInst::ICMP_SGT:
2411 case ICmpInst::ICMP_SGE:
2412 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2413 Constant::getAllOnesValue(SRem->getType()));
2414 case ICmpInst::ICMP_SLT:
2415 case ICmpInst::ICMP_SLE:
2416 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2417 Constant::getNullValue(SRem->getType()));
2418 }
2419 }
2420
Duncan Sandsa7724332011-02-17 07:46:37 +00002421 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2422 BO0->hasOneUse() && BO1->hasOneUse() &&
2423 BO0->getOperand(1) == BO1->getOperand(1)) {
2424 switch (BO0->getOpcode()) {
2425 default: break;
2426 case Instruction::Add:
2427 case Instruction::Sub:
2428 case Instruction::Xor:
2429 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2430 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2431 BO1->getOperand(0));
2432 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2433 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2434 if (CI->getValue().isSignBit()) {
2435 ICmpInst::Predicate Pred = I.isSigned()
2436 ? I.getUnsignedPredicate()
2437 : I.getSignedPredicate();
2438 return new ICmpInst(Pred, BO0->getOperand(0),
2439 BO1->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00002440 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002441
Chris Lattnerc73b24d2011-07-15 06:08:15 +00002442 if (CI->isMaxValue(true)) {
Duncan Sandsa7724332011-02-17 07:46:37 +00002443 ICmpInst::Predicate Pred = I.isSigned()
2444 ? I.getUnsignedPredicate()
2445 : I.getSignedPredicate();
2446 Pred = I.getSwappedPredicate(Pred);
2447 return new ICmpInst(Pred, BO0->getOperand(0),
2448 BO1->getOperand(0));
2449 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002450 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002451 break;
2452 case Instruction::Mul:
2453 if (!I.isEquality())
2454 break;
2455
2456 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2457 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2458 // Mask = -1 >> count-trailing-zeros(Cst).
2459 if (!CI->isZero() && !CI->isOne()) {
2460 const APInt &AP = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002461 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandsa7724332011-02-17 07:46:37 +00002462 APInt::getLowBitsSet(AP.getBitWidth(),
2463 AP.getBitWidth() -
2464 AP.countTrailingZeros()));
2465 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2466 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2467 return new ICmpInst(I.getPredicate(), And1, And2);
2468 }
2469 }
2470 break;
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002471 case Instruction::UDiv:
2472 case Instruction::LShr:
2473 if (I.isSigned())
2474 break;
2475 // fall-through
2476 case Instruction::SDiv:
2477 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002478 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002479 break;
2480 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2481 BO1->getOperand(0));
2482 case Instruction::Shl: {
2483 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2484 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2485 if (!NUW && !NSW)
2486 break;
2487 if (!NSW && I.isSigned())
2488 break;
2489 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2490 BO1->getOperand(0));
2491 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002492 }
2493 }
2494 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002495
Chris Lattner02446fc2010-01-04 07:37:31 +00002496 { Value *A, *B;
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002497 // ~x < ~y --> y < x
2498 // ~x < cst --> ~cst < x
2499 if (match(Op0, m_Not(m_Value(A)))) {
2500 if (match(Op1, m_Not(m_Value(B))))
2501 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner27a98482011-01-15 05:42:47 +00002502 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002503 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2504 }
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002505
2506 // (a+b) <u a --> llvm.uadd.with.overflow.
2507 // (a+b) <u b --> llvm.uadd.with.overflow.
2508 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002509 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002510 (Op1 == A || Op1 == B))
2511 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2512 return R;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002513
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002514 // a >u (a+b) --> llvm.uadd.with.overflow.
2515 // b >u (a+b) --> llvm.uadd.with.overflow.
2516 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2517 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2518 (Op0 == A || Op0 == B))
2519 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2520 return R;
Chris Lattner02446fc2010-01-04 07:37:31 +00002521 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002522
Chris Lattner02446fc2010-01-04 07:37:31 +00002523 if (I.isEquality()) {
2524 Value *A, *B, *C, *D;
Duncan Sands39a7de72011-02-18 16:25:37 +00002525
Chris Lattner02446fc2010-01-04 07:37:31 +00002526 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2527 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2528 Value *OtherVal = A == Op1 ? B : A;
2529 return new ICmpInst(I.getPredicate(), OtherVal,
2530 Constant::getNullValue(A->getType()));
2531 }
2532
2533 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2534 // A^c1 == C^c2 --> A == C^(c1^c2)
2535 ConstantInt *C1, *C2;
2536 if (match(B, m_ConstantInt(C1)) &&
2537 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2538 Constant *NC = ConstantInt::get(I.getContext(),
2539 C1->getValue() ^ C2->getValue());
Benjamin Kramera9390a42011-09-27 20:39:19 +00002540 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner02446fc2010-01-04 07:37:31 +00002541 return new ICmpInst(I.getPredicate(), A, Xor);
2542 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002543
Chris Lattner02446fc2010-01-04 07:37:31 +00002544 // A^B == A^D -> B == D
2545 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2546 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2547 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2548 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2549 }
2550 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002551
Chris Lattner02446fc2010-01-04 07:37:31 +00002552 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2553 (A == Op0 || B == Op0)) {
2554 // A == (A^B) -> B == 0
2555 Value *OtherVal = A == Op0 ? B : A;
2556 return new ICmpInst(I.getPredicate(), OtherVal,
2557 Constant::getNullValue(A->getType()));
2558 }
2559
Chris Lattner02446fc2010-01-04 07:37:31 +00002560 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002561 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner5036ce42011-04-26 20:02:45 +00002562 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002563 Value *X = 0, *Y = 0, *Z = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002564
Chris Lattner02446fc2010-01-04 07:37:31 +00002565 if (A == C) {
2566 X = B; Y = D; Z = A;
2567 } else if (A == D) {
2568 X = B; Y = C; Z = A;
2569 } else if (B == C) {
2570 X = A; Y = D; Z = B;
2571 } else if (B == D) {
2572 X = A; Y = C; Z = B;
2573 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002574
Chris Lattner02446fc2010-01-04 07:37:31 +00002575 if (X) { // Build (X^Y) & Z
Benjamin Kramera9390a42011-09-27 20:39:19 +00002576 Op1 = Builder->CreateXor(X, Y);
2577 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner02446fc2010-01-04 07:37:31 +00002578 I.setOperand(0, Op1);
2579 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2580 return &I;
2581 }
2582 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002583
Chris Lattner325eeb12011-04-26 20:18:20 +00002584 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2585 // "icmp (and X, mask), cst"
2586 uint64_t ShAmt = 0;
2587 ConstantInt *Cst1;
2588 if (Op0->hasOneUse() &&
2589 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2590 m_ConstantInt(ShAmt))))) &&
2591 match(Op1, m_ConstantInt(Cst1)) &&
2592 // Only do this when A has multiple uses. This is most important to do
2593 // when it exposes other optimizations.
2594 !A->hasOneUse()) {
2595 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002596
Chris Lattner325eeb12011-04-26 20:18:20 +00002597 if (ShAmt < ASize) {
2598 APInt MaskV =
2599 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2600 MaskV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002601
Chris Lattner325eeb12011-04-26 20:18:20 +00002602 APInt CmpV = Cst1->getValue().zext(ASize);
2603 CmpV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002604
Chris Lattner325eeb12011-04-26 20:18:20 +00002605 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2606 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2607 }
2608 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002609 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002610
Chris Lattner02446fc2010-01-04 07:37:31 +00002611 {
2612 Value *X; ConstantInt *Cst;
2613 // icmp X+Cst, X
2614 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2615 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2616
2617 // icmp X, X+Cst
2618 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2619 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2620 }
2621 return Changed ? &I : 0;
2622}
2623
2624
2625
2626
2627
2628
2629/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2630///
2631Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2632 Instruction *LHSI,
2633 Constant *RHSC) {
2634 if (!isa<ConstantFP>(RHSC)) return 0;
2635 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002636
Chris Lattner02446fc2010-01-04 07:37:31 +00002637 // Get the width of the mantissa. We don't want to hack on conversions that
2638 // might lose information from the integer, e.g. "i64 -> float"
2639 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2640 if (MantissaWidth == -1) return 0; // Unknown.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002641
Chris Lattner02446fc2010-01-04 07:37:31 +00002642 // Check to see that the input is converted from an integer type that is small
2643 // enough that preserves all bits. TODO: check here for "known" sign bits.
2644 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2645 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002646
Chris Lattner02446fc2010-01-04 07:37:31 +00002647 // If this is a uitofp instruction, we need an extra bit to hold the sign.
2648 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2649 if (LHSUnsigned)
2650 ++InputSize;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002651
Chris Lattner02446fc2010-01-04 07:37:31 +00002652 // If the conversion would lose info, don't hack on this.
2653 if ((int)InputSize > MantissaWidth)
2654 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002655
Chris Lattner02446fc2010-01-04 07:37:31 +00002656 // Otherwise, we can potentially simplify the comparison. We know that it
2657 // will always come through as an integer value and we know the constant is
2658 // not a NAN (it would have been previously simplified).
2659 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002660
Chris Lattner02446fc2010-01-04 07:37:31 +00002661 ICmpInst::Predicate Pred;
2662 switch (I.getPredicate()) {
2663 default: llvm_unreachable("Unexpected predicate!");
2664 case FCmpInst::FCMP_UEQ:
2665 case FCmpInst::FCMP_OEQ:
2666 Pred = ICmpInst::ICMP_EQ;
2667 break;
2668 case FCmpInst::FCMP_UGT:
2669 case FCmpInst::FCMP_OGT:
2670 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2671 break;
2672 case FCmpInst::FCMP_UGE:
2673 case FCmpInst::FCMP_OGE:
2674 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2675 break;
2676 case FCmpInst::FCMP_ULT:
2677 case FCmpInst::FCMP_OLT:
2678 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2679 break;
2680 case FCmpInst::FCMP_ULE:
2681 case FCmpInst::FCMP_OLE:
2682 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2683 break;
2684 case FCmpInst::FCMP_UNE:
2685 case FCmpInst::FCMP_ONE:
2686 Pred = ICmpInst::ICMP_NE;
2687 break;
2688 case FCmpInst::FCMP_ORD:
2689 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2690 case FCmpInst::FCMP_UNO:
2691 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2692 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002693
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002694 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002695
Chris Lattner02446fc2010-01-04 07:37:31 +00002696 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002697
Chris Lattner02446fc2010-01-04 07:37:31 +00002698 // See if the FP constant is too large for the integer. For example,
2699 // comparing an i8 to 300.0.
2700 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002701
Chris Lattner02446fc2010-01-04 07:37:31 +00002702 if (!LHSUnsigned) {
2703 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
2704 // and large values.
2705 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2706 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2707 APFloat::rmNearestTiesToEven);
2708 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
2709 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
2710 Pred == ICmpInst::ICMP_SLE)
2711 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2712 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2713 }
2714 } else {
2715 // If the RHS value is > UnsignedMax, fold the comparison. This handles
2716 // +INF and large values.
2717 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2718 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2719 APFloat::rmNearestTiesToEven);
2720 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
2721 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
2722 Pred == ICmpInst::ICMP_ULE)
2723 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2724 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2725 }
2726 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002727
Chris Lattner02446fc2010-01-04 07:37:31 +00002728 if (!LHSUnsigned) {
2729 // See if the RHS value is < SignedMin.
2730 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2731 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2732 APFloat::rmNearestTiesToEven);
2733 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2734 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2735 Pred == ICmpInst::ICMP_SGE)
2736 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2737 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2738 }
Devang Patela2e0f6b2012-02-13 23:05:18 +00002739 } else {
2740 // See if the RHS value is < UnsignedMin.
2741 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2742 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
2743 APFloat::rmNearestTiesToEven);
2744 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
2745 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
2746 Pred == ICmpInst::ICMP_UGE)
2747 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2748 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2749 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002750 }
2751
2752 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2753 // [0, UMAX], but it may still be fractional. See if it is fractional by
2754 // casting the FP value to the integer value and back, checking for equality.
2755 // Don't do this for zero, because -0.0 is not fractional.
2756 Constant *RHSInt = LHSUnsigned
2757 ? ConstantExpr::getFPToUI(RHSC, IntTy)
2758 : ConstantExpr::getFPToSI(RHSC, IntTy);
2759 if (!RHS.isZero()) {
2760 bool Equal = LHSUnsigned
2761 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2762 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2763 if (!Equal) {
2764 // If we had a comparison against a fractional value, we have to adjust
2765 // the compare predicate and sometimes the value. RHSC is rounded towards
2766 // zero at this point.
2767 switch (Pred) {
2768 default: llvm_unreachable("Unexpected integer comparison!");
2769 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
2770 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2771 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
2772 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2773 case ICmpInst::ICMP_ULE:
2774 // (float)int <= 4.4 --> int <= 4
2775 // (float)int <= -4.4 --> false
2776 if (RHS.isNegative())
2777 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2778 break;
2779 case ICmpInst::ICMP_SLE:
2780 // (float)int <= 4.4 --> int <= 4
2781 // (float)int <= -4.4 --> int < -4
2782 if (RHS.isNegative())
2783 Pred = ICmpInst::ICMP_SLT;
2784 break;
2785 case ICmpInst::ICMP_ULT:
2786 // (float)int < -4.4 --> false
2787 // (float)int < 4.4 --> int <= 4
2788 if (RHS.isNegative())
2789 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2790 Pred = ICmpInst::ICMP_ULE;
2791 break;
2792 case ICmpInst::ICMP_SLT:
2793 // (float)int < -4.4 --> int < -4
2794 // (float)int < 4.4 --> int <= 4
2795 if (!RHS.isNegative())
2796 Pred = ICmpInst::ICMP_SLE;
2797 break;
2798 case ICmpInst::ICMP_UGT:
2799 // (float)int > 4.4 --> int > 4
2800 // (float)int > -4.4 --> true
2801 if (RHS.isNegative())
2802 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2803 break;
2804 case ICmpInst::ICMP_SGT:
2805 // (float)int > 4.4 --> int > 4
2806 // (float)int > -4.4 --> int >= -4
2807 if (RHS.isNegative())
2808 Pred = ICmpInst::ICMP_SGE;
2809 break;
2810 case ICmpInst::ICMP_UGE:
2811 // (float)int >= -4.4 --> true
2812 // (float)int >= 4.4 --> int > 4
2813 if (!RHS.isNegative())
2814 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2815 Pred = ICmpInst::ICMP_UGT;
2816 break;
2817 case ICmpInst::ICMP_SGE:
2818 // (float)int >= -4.4 --> int >= -4
2819 // (float)int >= 4.4 --> int > 4
2820 if (!RHS.isNegative())
2821 Pred = ICmpInst::ICMP_SGT;
2822 break;
2823 }
2824 }
2825 }
2826
2827 // Lower this FP comparison into an appropriate integer version of the
2828 // comparison.
2829 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2830}
2831
2832Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2833 bool Changed = false;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002834
Chris Lattner02446fc2010-01-04 07:37:31 +00002835 /// Orders the operands of the compare so that they are listed from most
2836 /// complex to least complex. This puts constants before unary operators,
2837 /// before binary operators.
2838 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2839 I.swapOperands();
2840 Changed = true;
2841 }
2842
2843 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002844
Chris Lattner02446fc2010-01-04 07:37:31 +00002845 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2846 return ReplaceInstUsesWith(I, V);
2847
2848 // Simplify 'fcmp pred X, X'
2849 if (Op0 == Op1) {
2850 switch (I.getPredicate()) {
2851 default: llvm_unreachable("Unknown predicate!");
2852 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
2853 case FCmpInst::FCMP_ULT: // True if unordered or less than
2854 case FCmpInst::FCMP_UGT: // True if unordered or greater than
2855 case FCmpInst::FCMP_UNE: // True if unordered or not equal
2856 // Canonicalize these to be 'fcmp uno %X, 0.0'.
2857 I.setPredicate(FCmpInst::FCMP_UNO);
2858 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2859 return &I;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002860
Chris Lattner02446fc2010-01-04 07:37:31 +00002861 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
2862 case FCmpInst::FCMP_OEQ: // True if ordered and equal
2863 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
2864 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
2865 // Canonicalize these to be 'fcmp ord %X, 0.0'.
2866 I.setPredicate(FCmpInst::FCMP_ORD);
2867 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2868 return &I;
2869 }
2870 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002871
Chris Lattner02446fc2010-01-04 07:37:31 +00002872 // Handle fcmp with constant RHS
2873 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2874 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2875 switch (LHSI->getOpcode()) {
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002876 case Instruction::FPExt: {
2877 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
2878 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
2879 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
2880 if (!RHSF)
2881 break;
2882
Benjamin Kramer7ebdc372011-03-31 21:35:49 +00002883 // We can't convert a PPC double double.
2884 if (RHSF->getType()->isPPC_FP128Ty())
2885 break;
2886
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002887 const fltSemantics *Sem;
2888 // FIXME: This shouldn't be here.
Dan Gohmance163392011-12-17 00:04:22 +00002889 if (LHSExt->getSrcTy()->isHalfTy())
2890 Sem = &APFloat::IEEEhalf;
2891 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002892 Sem = &APFloat::IEEEsingle;
2893 else if (LHSExt->getSrcTy()->isDoubleTy())
2894 Sem = &APFloat::IEEEdouble;
2895 else if (LHSExt->getSrcTy()->isFP128Ty())
2896 Sem = &APFloat::IEEEquad;
2897 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
2898 Sem = &APFloat::x87DoubleExtended;
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002899 else
2900 break;
2901
2902 bool Lossy;
2903 APFloat F = RHSF->getValueAPF();
2904 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
2905
Jim Grosbachcbf676b2011-09-30 18:45:50 +00002906 // Avoid lossy conversions and denormals. Zero is a special case
2907 // that's OK to convert.
Jim Grosbach68e05fb2011-09-30 19:58:46 +00002908 APFloat Fabs = F;
2909 Fabs.clearSign();
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002910 if (!Lossy &&
Jim Grosbach68e05fb2011-09-30 19:58:46 +00002911 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
2912 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbachcbf676b2011-09-30 18:45:50 +00002913
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002914 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2915 ConstantFP::get(RHSC->getContext(), F));
2916 break;
2917 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002918 case Instruction::PHI:
2919 // Only fold fcmp into the PHI if the phi and fcmp are in the same
2920 // block. If in the same block, we're encouraging jump threading. If
2921 // not, we are just pessimizing the code by making an i1 phi.
2922 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002923 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002924 return NV;
2925 break;
2926 case Instruction::SIToFP:
2927 case Instruction::UIToFP:
2928 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2929 return NV;
2930 break;
2931 case Instruction::Select: {
2932 // If either operand of the select is a constant, we can fold the
2933 // comparison into the select arms, which will cause one to be
2934 // constant folded and the select turned into a bitwise or.
2935 Value *Op1 = 0, *Op2 = 0;
2936 if (LHSI->hasOneUse()) {
2937 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2938 // Fold the known value into the constant operand.
2939 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2940 // Insert a new FCmp of the other select operand.
2941 Op2 = Builder->CreateFCmp(I.getPredicate(),
2942 LHSI->getOperand(2), RHSC, I.getName());
2943 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2944 // Fold the known value into the constant operand.
2945 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
2946 // Insert a new FCmp of the other select operand.
2947 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
2948 RHSC, I.getName());
2949 }
2950 }
2951
2952 if (Op1)
2953 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2954 break;
2955 }
Benjamin Kramer0db50182011-03-31 10:12:15 +00002956 case Instruction::FSub: {
2957 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
2958 Value *Op;
2959 if (match(LHSI, m_FNeg(m_Value(Op))))
2960 return new FCmpInst(I.getSwappedPredicate(), Op,
2961 ConstantExpr::getFNeg(RHSC));
2962 break;
2963 }
Dan Gohman39516a62010-02-24 06:46:09 +00002964 case Instruction::Load:
2965 if (GetElementPtrInst *GEP =
2966 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2967 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2968 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2969 !cast<LoadInst>(LHSI)->isVolatile())
2970 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2971 return Res;
2972 }
2973 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00002974 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002975 }
2976
Benjamin Kramer00e00d62011-03-31 10:46:03 +00002977 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00002978 Value *X, *Y;
2979 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramer00e00d62011-03-31 10:46:03 +00002980 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00002981
Benjamin Kramercd0274c2011-03-31 10:11:58 +00002982 // fcmp (fpext x), (fpext y) -> fcmp x, y
2983 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
2984 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
2985 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
2986 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2987 RHSExt->getOperand(0));
2988
Chris Lattner02446fc2010-01-04 07:37:31 +00002989 return Changed ? &I : 0;
2990}