blob: a4e117e4c4b45c74796e6098f4e5839a95f56fcb [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"
Eli Friedman74703252011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner02446fc2010-01-04 07:37:31 +000016#include "llvm/Analysis/InstructionSimplify.h"
17#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/IntrinsicInst.h"
Chris Lattner02446fc2010-01-04 07:37:31 +000020#include "llvm/Support/ConstantRange.h"
21#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/Support/PatternMatch.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner02446fc2010-01-04 07:37:31 +000024using namespace llvm;
25using namespace PatternMatch;
26
Chris Lattnerb20c0b52011-02-10 05:23:05 +000027static ConstantInt *getOne(Constant *C) {
28 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
29}
30
Chris Lattner02446fc2010-01-04 07:37:31 +000031/// AddOne - Add one to a ConstantInt
32static Constant *AddOne(Constant *C) {
33 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
34}
35/// SubOne - Subtract one from a ConstantInt
Chris Lattnerb20c0b52011-02-10 05:23:05 +000036static Constant *SubOne(Constant *C) {
37 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner02446fc2010-01-04 07:37:31 +000038}
39
40static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
41 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
42}
43
44static bool HasAddOverflow(ConstantInt *Result,
45 ConstantInt *In1, ConstantInt *In2,
46 bool IsSigned) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +000047 if (!IsSigned)
Chris Lattner02446fc2010-01-04 07:37:31 +000048 return Result->getValue().ult(In1->getValue());
Chris Lattnerc73b24d2011-07-15 06:08:15 +000049
50 if (In2->isNegative())
51 return Result->getValue().sgt(In1->getValue());
52 return Result->getValue().slt(In1->getValue());
Chris Lattner02446fc2010-01-04 07:37:31 +000053}
54
55/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
56/// overflowed for this type.
57static bool AddWithOverflow(Constant *&Result, Constant *In1,
58 Constant *In2, bool IsSigned = false) {
59 Result = ConstantExpr::getAdd(In1, In2);
60
Chris Lattnerdb125cf2011-07-18 04:54:35 +000061 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner02446fc2010-01-04 07:37:31 +000062 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
63 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
64 if (HasAddOverflow(ExtractElement(Result, Idx),
65 ExtractElement(In1, Idx),
66 ExtractElement(In2, Idx),
67 IsSigned))
68 return true;
69 }
70 return false;
71 }
72
73 return HasAddOverflow(cast<ConstantInt>(Result),
74 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
75 IsSigned);
76}
77
78static bool HasSubOverflow(ConstantInt *Result,
79 ConstantInt *In1, ConstantInt *In2,
80 bool IsSigned) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +000081 if (!IsSigned)
Chris Lattner02446fc2010-01-04 07:37:31 +000082 return Result->getValue().ugt(In1->getValue());
Jim Grosbach0cc4a952011-09-30 18:09:53 +000083
Chris Lattnerc73b24d2011-07-15 06:08:15 +000084 if (In2->isNegative())
85 return Result->getValue().slt(In1->getValue());
86
87 return Result->getValue().sgt(In1->getValue());
Chris Lattner02446fc2010-01-04 07:37:31 +000088}
89
90/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
91/// overflowed for this type.
92static bool SubWithOverflow(Constant *&Result, Constant *In1,
93 Constant *In2, bool IsSigned = false) {
94 Result = ConstantExpr::getSub(In1, In2);
95
Chris Lattnerdb125cf2011-07-18 04:54:35 +000096 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner02446fc2010-01-04 07:37:31 +000097 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
98 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
99 if (HasSubOverflow(ExtractElement(Result, Idx),
100 ExtractElement(In1, Idx),
101 ExtractElement(In2, Idx),
102 IsSigned))
103 return true;
104 }
105 return false;
106 }
107
108 return HasSubOverflow(cast<ConstantInt>(Result),
109 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
110 IsSigned);
111}
112
113/// isSignBitCheck - Given an exploded icmp instruction, return true if the
114/// comparison only checks the sign bit. If it only checks the sign bit, set
115/// TrueIfSigned if the result of the comparison is true when the input value is
116/// signed.
117static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
118 bool &TrueIfSigned) {
119 switch (pred) {
120 case ICmpInst::ICMP_SLT: // True if LHS s< 0
121 TrueIfSigned = true;
122 return RHS->isZero();
123 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
124 TrueIfSigned = true;
125 return RHS->isAllOnesValue();
126 case ICmpInst::ICMP_SGT: // True if LHS s> -1
127 TrueIfSigned = false;
128 return RHS->isAllOnesValue();
129 case ICmpInst::ICMP_UGT:
130 // True if LHS u> RHS and RHS == high-bit-mask - 1
131 TrueIfSigned = true;
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000132 return RHS->isMaxValue(true);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000133 case ICmpInst::ICMP_UGE:
Chris Lattner02446fc2010-01-04 07:37:31 +0000134 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
135 TrueIfSigned = true;
136 return RHS->getValue().isSignBit();
137 default:
138 return false;
139 }
140}
141
142// isHighOnes - Return true if the constant is of the form 1+0+.
143// This is the same as lowones(~X).
144static bool isHighOnes(const ConstantInt *CI) {
145 return (~CI->getValue() + 1).isPowerOf2();
146}
147
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000148/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner02446fc2010-01-04 07:37:31 +0000149/// set of known zero and one bits, compute the maximum and minimum values that
150/// could have the specified known zero and known one bits, returning them in
151/// min/max.
152static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
153 const APInt& KnownOne,
154 APInt& Min, APInt& Max) {
155 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
156 KnownZero.getBitWidth() == Min.getBitWidth() &&
157 KnownZero.getBitWidth() == Max.getBitWidth() &&
158 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
159 APInt UnknownBits = ~(KnownZero|KnownOne);
160
161 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
162 // bit if it is unknown.
163 Min = KnownOne;
164 Max = KnownOne|UnknownBits;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000165
Chris Lattner02446fc2010-01-04 07:37:31 +0000166 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad7a874dd2010-12-01 08:53:58 +0000167 Min.setBit(Min.getBitWidth()-1);
168 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner02446fc2010-01-04 07:37:31 +0000169 }
170}
171
172// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
173// a set of known zero and one bits, compute the maximum and minimum values that
174// could have the specified known zero and known one bits, returning them in
175// min/max.
176static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
177 const APInt &KnownOne,
178 APInt &Min, APInt &Max) {
179 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
180 KnownZero.getBitWidth() == Min.getBitWidth() &&
181 KnownZero.getBitWidth() == Max.getBitWidth() &&
182 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
183 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000184
Chris Lattner02446fc2010-01-04 07:37:31 +0000185 // The minimum value is when the unknown bits are all zeros.
186 Min = KnownOne;
187 // The maximum value is when the unknown bits are all ones.
188 Max = KnownOne|UnknownBits;
189}
190
191
192
193/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
194/// cmp pred (load (gep GV, ...)), cmpcst
195/// where GV is a global variable with a constant initializer. Try to simplify
196/// this into some simple computation that does not need the load. For example
197/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
198///
199/// If AndCst is non-null, then the loaded value is masked with that constant
200/// before doing the comparison. This handles cases like "A[i]&4 == 0".
201Instruction *InstCombiner::
202FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
203 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000204 // We need TD information to know the pointer size unless this is inbounds.
205 if (!GEP->isInBounds() && TD == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000206
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000207 Constant *Init = GV->getInitializer();
208 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
209 return 0;
210
211 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
212 if (ArrayElementCount > 1024) return 0; // Don't blow up on huge arrays.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000213
Chris Lattner02446fc2010-01-04 07:37:31 +0000214 // There are many forms of this optimization we can handle, for now, just do
215 // the simple index into a single-dimensional array.
216 //
217 // Require: GEP GV, 0, i {{, constant indices}}
218 if (GEP->getNumOperands() < 3 ||
219 !isa<ConstantInt>(GEP->getOperand(1)) ||
220 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
221 isa<Constant>(GEP->getOperand(2)))
222 return 0;
223
224 // Check that indices after the variable are constants and in-range for the
225 // type they index. Collect the indices. This is typically for arrays of
226 // structs.
227 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000228
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000229 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner02446fc2010-01-04 07:37:31 +0000230 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
231 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
232 if (Idx == 0) return 0; // Variable index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000233
Chris Lattner02446fc2010-01-04 07:37:31 +0000234 uint64_t IdxVal = Idx->getZExtValue();
235 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000236
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000237 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner02446fc2010-01-04 07:37:31 +0000238 EltTy = STy->getElementType(IdxVal);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000239 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000240 if (IdxVal >= ATy->getNumElements()) return 0;
241 EltTy = ATy->getElementType();
242 } else {
243 return 0; // Unknown type.
244 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000245
Chris Lattner02446fc2010-01-04 07:37:31 +0000246 LaterIndices.push_back(IdxVal);
247 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000248
Chris Lattner02446fc2010-01-04 07:37:31 +0000249 enum { Overdefined = -3, Undefined = -2 };
250
251 // Variables for our state machines.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000252
Chris Lattner02446fc2010-01-04 07:37:31 +0000253 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
254 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
255 // and 87 is the second (and last) index. FirstTrueElement is -2 when
256 // undefined, otherwise set to the first true element. SecondTrueElement is
257 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
258 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
259
260 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
261 // form "i != 47 & i != 87". Same state transitions as for true elements.
262 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000263
Chris Lattner02446fc2010-01-04 07:37:31 +0000264 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
265 /// define a state machine that triggers for ranges of values that the index
266 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
267 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
268 /// index in the range (inclusive). We use -2 for undefined here because we
269 /// use relative comparisons and don't want 0-1 to match -1.
270 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000271
Chris Lattner02446fc2010-01-04 07:37:31 +0000272 // MagicBitvector - This is a magic bitvector where we set a bit if the
273 // comparison is true for element 'i'. If there are 64 elements or less in
274 // the array, this will fully represent all the comparison results.
275 uint64_t MagicBitvector = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000276
277
Chris Lattner02446fc2010-01-04 07:37:31 +0000278 // Scan the array and see if one of our patterns matches.
279 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000280 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
281 Constant *Elt = Init->getAggregateElement(i);
282 if (Elt == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000283
Chris Lattner02446fc2010-01-04 07:37:31 +0000284 // If this is indexing an array of structures, get the structure element.
285 if (!LaterIndices.empty())
Jay Foadfc6d3a42011-07-13 10:26:04 +0000286 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000287
Chris Lattner02446fc2010-01-04 07:37:31 +0000288 // If the element is masked, handle it.
289 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000290
Chris Lattner02446fc2010-01-04 07:37:31 +0000291 // Find out if the comparison would be true or false for the i'th element.
292 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chad Rosieraab8e282011-12-02 01:26:24 +0000293 CompareRHS, TD, TLI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000294 // If the result is undef for this element, ignore it.
295 if (isa<UndefValue>(C)) {
296 // Extend range state machines to cover this element in case there is an
297 // undef in the middle of the range.
298 if (TrueRangeEnd == (int)i-1)
299 TrueRangeEnd = i;
300 if (FalseRangeEnd == (int)i-1)
301 FalseRangeEnd = i;
302 continue;
303 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000304
Chris Lattner02446fc2010-01-04 07:37:31 +0000305 // If we can't compute the result for any of the elements, we have to give
306 // up evaluating the entire conditional.
307 if (!isa<ConstantInt>(C)) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000308
Chris Lattner02446fc2010-01-04 07:37:31 +0000309 // Otherwise, we know if the comparison is true or false for this element,
310 // update our state machines.
311 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000312
Chris Lattner02446fc2010-01-04 07:37:31 +0000313 // State machine for single/double/range index comparison.
314 if (IsTrueForElt) {
315 // Update the TrueElement state machine.
316 if (FirstTrueElement == Undefined)
317 FirstTrueElement = TrueRangeEnd = i; // First true element.
318 else {
319 // Update double-compare state machine.
320 if (SecondTrueElement == Undefined)
321 SecondTrueElement = i;
322 else
323 SecondTrueElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000324
Chris Lattner02446fc2010-01-04 07:37:31 +0000325 // Update range state machine.
326 if (TrueRangeEnd == (int)i-1)
327 TrueRangeEnd = i;
328 else
329 TrueRangeEnd = Overdefined;
330 }
331 } else {
332 // Update the FalseElement state machine.
333 if (FirstFalseElement == Undefined)
334 FirstFalseElement = FalseRangeEnd = i; // First false element.
335 else {
336 // Update double-compare state machine.
337 if (SecondFalseElement == Undefined)
338 SecondFalseElement = i;
339 else
340 SecondFalseElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000341
Chris Lattner02446fc2010-01-04 07:37:31 +0000342 // Update range state machine.
343 if (FalseRangeEnd == (int)i-1)
344 FalseRangeEnd = i;
345 else
346 FalseRangeEnd = Overdefined;
347 }
348 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000349
350
Chris Lattner02446fc2010-01-04 07:37:31 +0000351 // If this element is in range, update our magic bitvector.
352 if (i < 64 && IsTrueForElt)
353 MagicBitvector |= 1ULL << i;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000354
Chris Lattner02446fc2010-01-04 07:37:31 +0000355 // If all of our states become overdefined, bail out early. Since the
356 // predicate is expensive, only check it every 8 elements. This is only
357 // really useful for really huge arrays.
358 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
359 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
360 FalseRangeEnd == Overdefined)
361 return 0;
362 }
363
364 // Now that we've scanned the entire array, emit our new comparison(s). We
365 // order the state machines in complexity of the generated code.
366 Value *Idx = GEP->getOperand(2);
367
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000368 // If the index is larger than the pointer size of the target, truncate the
369 // index down like the GEP would do implicitly. We don't have to do this for
370 // an inbounds GEP because the index can't be out of range.
371 if (!GEP->isInBounds() &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000372 Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000373 Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000374
Chris Lattner02446fc2010-01-04 07:37:31 +0000375 // If the comparison is only true for one or two elements, emit direct
376 // comparisons.
377 if (SecondTrueElement != Overdefined) {
378 // None true -> false.
379 if (FirstTrueElement == Undefined)
380 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000381
Chris Lattner02446fc2010-01-04 07:37:31 +0000382 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000383
Chris Lattner02446fc2010-01-04 07:37:31 +0000384 // True for one element -> 'i == 47'.
385 if (SecondTrueElement == Undefined)
386 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000387
Chris Lattner02446fc2010-01-04 07:37:31 +0000388 // True for two elements -> 'i == 47 | i == 72'.
389 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
390 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
391 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
392 return BinaryOperator::CreateOr(C1, C2);
393 }
394
395 // If the comparison is only false for one or two elements, emit direct
396 // comparisons.
397 if (SecondFalseElement != Overdefined) {
398 // None false -> true.
399 if (FirstFalseElement == Undefined)
400 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000401
Chris Lattner02446fc2010-01-04 07:37:31 +0000402 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
403
404 // False for one element -> 'i != 47'.
405 if (SecondFalseElement == Undefined)
406 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000407
Chris Lattner02446fc2010-01-04 07:37:31 +0000408 // False for two elements -> 'i != 47 & i != 72'.
409 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
410 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
411 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
412 return BinaryOperator::CreateAnd(C1, C2);
413 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000414
Chris Lattner02446fc2010-01-04 07:37:31 +0000415 // If the comparison can be replaced with a range comparison for the elements
416 // where it is true, emit the range check.
417 if (TrueRangeEnd != Overdefined) {
418 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000419
Chris Lattner02446fc2010-01-04 07:37:31 +0000420 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
421 if (FirstTrueElement) {
422 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
423 Idx = Builder->CreateAdd(Idx, Offs);
424 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000425
Chris Lattner02446fc2010-01-04 07:37:31 +0000426 Value *End = ConstantInt::get(Idx->getType(),
427 TrueRangeEnd-FirstTrueElement+1);
428 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
429 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000430
Chris Lattner02446fc2010-01-04 07:37:31 +0000431 // False range check.
432 if (FalseRangeEnd != Overdefined) {
433 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
434 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
435 if (FirstFalseElement) {
436 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
437 Idx = Builder->CreateAdd(Idx, Offs);
438 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000439
Chris Lattner02446fc2010-01-04 07:37:31 +0000440 Value *End = ConstantInt::get(Idx->getType(),
441 FalseRangeEnd-FirstFalseElement);
442 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
443 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000444
445
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000446 // If a magic bitvector captures the entire comparison state
Chris Lattner02446fc2010-01-04 07:37:31 +0000447 // of this load, replace it with computation that does:
448 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000449 {
450 Type *Ty = 0;
451
452 // Look for an appropriate type:
453 // - The type of Idx if the magic fits
454 // - The smallest fitting legal type if we have a DataLayout
455 // - Default to i32
456 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
457 Ty = Idx->getType();
458 else if (TD)
459 Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
460 else if (ArrayElementCount <= 32)
Chris Lattner02446fc2010-01-04 07:37:31 +0000461 Ty = Type::getInt32Ty(Init->getContext());
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000462
463 if (Ty != 0) {
464 Value *V = Builder->CreateIntCast(Idx, Ty, false);
465 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
466 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
467 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
468 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000469 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000470
Chris Lattner02446fc2010-01-04 07:37:31 +0000471 return 0;
472}
473
474
475/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
476/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
477/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
478/// be complex, and scales are involved. The above expression would also be
479/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
480/// This later form is less amenable to optimization though, and we are allowed
481/// to generate the first by knowing that pointer arithmetic doesn't overflow.
482///
483/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000484///
Eli Friedman107ffd52011-05-18 23:11:30 +0000485static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000486 DataLayout &TD = *IC.getDataLayout();
Chris Lattner02446fc2010-01-04 07:37:31 +0000487 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000488
Chris Lattner02446fc2010-01-04 07:37:31 +0000489 // Check to see if this gep only has a single variable index. If so, and if
490 // any constant indices are a multiple of its scale, then we can compute this
491 // in terms of the scale of the variable index. For example, if the GEP
492 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
493 // because the expression will cross zero at the same point.
494 unsigned i, e = GEP->getNumOperands();
495 int64_t Offset = 0;
496 for (i = 1; i != e; ++i, ++GTI) {
497 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
498 // Compute the aggregate offset of constant indices.
499 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000500
Chris Lattner02446fc2010-01-04 07:37:31 +0000501 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000502 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000503 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
504 } else {
505 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
506 Offset += Size*CI->getSExtValue();
507 }
508 } else {
509 // Found our variable index.
510 break;
511 }
512 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000513
Chris Lattner02446fc2010-01-04 07:37:31 +0000514 // If there are no variable indices, we must have a constant offset, just
515 // evaluate it the general way.
516 if (i == e) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000517
Chris Lattner02446fc2010-01-04 07:37:31 +0000518 Value *VariableIdx = GEP->getOperand(i);
519 // Determine the scale factor of the variable element. For example, this is
520 // 4 if the variable index is into an array of i32.
521 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000522
Chris Lattner02446fc2010-01-04 07:37:31 +0000523 // Verify that there are no other variable indices. If so, emit the hard way.
524 for (++i, ++GTI; i != e; ++i, ++GTI) {
525 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
526 if (!CI) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000527
Chris Lattner02446fc2010-01-04 07:37:31 +0000528 // Compute the aggregate offset of constant indices.
529 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000530
Chris Lattner02446fc2010-01-04 07:37:31 +0000531 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000532 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000533 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
534 } else {
535 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
536 Offset += Size*CI->getSExtValue();
537 }
538 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000539
Chris Lattner02446fc2010-01-04 07:37:31 +0000540 // Okay, we know we have a single variable index, which must be a
541 // pointer/array/vector index. If there is no offset, life is simple, return
542 // the index.
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000543 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattner02446fc2010-01-04 07:37:31 +0000544 if (Offset == 0) {
545 // Cast to intptrty in case a truncation occurs. If an extension is needed,
546 // we don't need to bother extending: the extension won't affect where the
547 // computation crosses zero.
Eli Friedman107ffd52011-05-18 23:11:30 +0000548 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000549 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Eli Friedman107ffd52011-05-18 23:11:30 +0000550 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
551 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000552 return VariableIdx;
553 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000554
Chris Lattner02446fc2010-01-04 07:37:31 +0000555 // Otherwise, there is an index. The computation we will do will be modulo
556 // the pointer size, so get it.
557 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000558
Chris Lattner02446fc2010-01-04 07:37:31 +0000559 Offset &= PtrSizeMask;
560 VariableScale &= PtrSizeMask;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000561
Chris Lattner02446fc2010-01-04 07:37:31 +0000562 // To do this transformation, any constant index must be a multiple of the
563 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
564 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
565 // multiple of the variable scale.
566 int64_t NewOffs = Offset / (int64_t)VariableScale;
567 if (Offset != NewOffs*(int64_t)VariableScale)
568 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000569
Chris Lattner02446fc2010-01-04 07:37:31 +0000570 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000571 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner02446fc2010-01-04 07:37:31 +0000572 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman107ffd52011-05-18 23:11:30 +0000573 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
574 true /*Signed*/);
Chris Lattner02446fc2010-01-04 07:37:31 +0000575 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman107ffd52011-05-18 23:11:30 +0000576 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner02446fc2010-01-04 07:37:31 +0000577}
578
579/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
580/// else. At this point we know that the GEP is on the LHS of the comparison.
581Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
582 ICmpInst::Predicate Cond,
583 Instruction &I) {
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000584 // Don't transform signed compares of GEPs into index compares. Even if the
585 // GEP is inbounds, the final add of the base pointer can have signed overflow
586 // and would change the result of the icmp.
587 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramera42d5c42012-02-21 13:40:06 +0000588 // the maximum signed value for the pointer type.
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000589 if (ICmpInst::isSigned(Cond))
590 return 0;
591
Chris Lattner02446fc2010-01-04 07:37:31 +0000592 // Look through bitcasts.
593 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
594 RHS = BCI->getOperand(0);
595
596 Value *PtrBase = GEPLHS->getOperand(0);
597 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
598 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
599 // This transformation (ignoring the base and scales) is valid because we
600 // know pointers can't overflow since the gep is inbounds. See if we can
601 // output an optimized form.
Eli Friedman107ffd52011-05-18 23:11:30 +0000602 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000603
Chris Lattner02446fc2010-01-04 07:37:31 +0000604 // If not, synthesize the offset the hard way.
605 if (Offset == 0)
606 Offset = EmitGEPOffset(GEPLHS);
607 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
608 Constant::getNullValue(Offset->getType()));
609 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
610 // If the base pointers are different, but the indices are the same, just
611 // compare the base pointer.
612 if (PtrBase != GEPRHS->getOperand(0)) {
613 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
614 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
615 GEPRHS->getOperand(0)->getType();
616 if (IndicesTheSame)
617 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
618 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
619 IndicesTheSame = false;
620 break;
621 }
622
623 // If all indices are the same, just compare the base pointers.
624 if (IndicesTheSame)
625 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
626 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
627
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000628 // If we're comparing GEPs with two base pointers that only differ in type
629 // and both GEPs have only constant indices or just one use, then fold
630 // the compare with the adjusted indices.
Benjamin Kramer6ad48f42012-02-20 18:45:10 +0000631 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000632 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
633 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
634 PtrBase->stripPointerCasts() ==
635 GEPRHS->getOperand(0)->stripPointerCasts()) {
636 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
637 EmitGEPOffset(GEPLHS),
638 EmitGEPOffset(GEPRHS));
639 return ReplaceInstUsesWith(I, Cmp);
640 }
641
Chris Lattner02446fc2010-01-04 07:37:31 +0000642 // Otherwise, the base pointers are different and the indices are
643 // different, bail out.
644 return 0;
645 }
646
647 // If one of the GEPs has all zero indices, recurse.
648 bool AllZeros = true;
649 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
650 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
651 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
652 AllZeros = false;
653 break;
654 }
655 if (AllZeros)
656 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
657 ICmpInst::getSwappedPredicate(Cond), I);
658
659 // If the other GEP has all zero indices, recurse.
660 AllZeros = true;
661 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
662 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
663 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
664 AllZeros = false;
665 break;
666 }
667 if (AllZeros)
668 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
669
Stuart Hastings67f071e2011-05-14 05:55:10 +0000670 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner02446fc2010-01-04 07:37:31 +0000671 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
672 // If the GEPs only differ by one index, compare it.
673 unsigned NumDifferences = 0; // Keep track of # differences.
674 unsigned DiffOperand = 0; // The operand that differs.
675 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
676 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
677 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
678 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
679 // Irreconcilable differences.
680 NumDifferences = 2;
681 break;
682 } else {
683 if (NumDifferences++) break;
684 DiffOperand = i;
685 }
686 }
687
688 if (NumDifferences == 0) // SAME GEP?
689 return ReplaceInstUsesWith(I, // No comparison is needed here.
690 ConstantInt::get(Type::getInt1Ty(I.getContext()),
691 ICmpInst::isTrueWhenEqual(Cond)));
692
Stuart Hastings67f071e2011-05-14 05:55:10 +0000693 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000694 Value *LHSV = GEPLHS->getOperand(DiffOperand);
695 Value *RHSV = GEPRHS->getOperand(DiffOperand);
696 // Make sure we do a signed comparison here.
697 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
698 }
699 }
700
701 // Only lower this if the icmp is the only user of the GEP or if we expect
702 // the result to fold to a constant!
703 if (TD &&
Stuart Hastings67f071e2011-05-14 05:55:10 +0000704 GEPsInBounds &&
Chris Lattner02446fc2010-01-04 07:37:31 +0000705 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
706 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
707 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
708 Value *L = EmitGEPOffset(GEPLHS);
709 Value *R = EmitGEPOffset(GEPRHS);
710 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
711 }
712 }
713 return 0;
714}
715
716/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
717Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
718 Value *X, ConstantInt *CI,
719 ICmpInst::Predicate Pred,
720 Value *TheAdd) {
721 // If we have X+0, exit early (simplifying logic below) and let it get folded
722 // elsewhere. icmp X+0, X -> icmp X, X
723 if (CI->isZero()) {
724 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
725 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
726 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000727
Chris Lattner02446fc2010-01-04 07:37:31 +0000728 // (X+4) == X -> false.
729 if (Pred == ICmpInst::ICMP_EQ)
730 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
731
732 // (X+4) != X -> true.
733 if (Pred == ICmpInst::ICMP_NE)
734 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
735
Chris Lattner02446fc2010-01-04 07:37:31 +0000736 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000737 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner02446fc2010-01-04 07:37:31 +0000738 // operators.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000739
Chris Lattner9aa1e242010-01-08 17:48:19 +0000740 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner02446fc2010-01-04 07:37:31 +0000741 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
742 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
743 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000744 Value *R =
Chris Lattner9aa1e242010-01-08 17:48:19 +0000745 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000746 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
747 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000748
Chris Lattner02446fc2010-01-04 07:37:31 +0000749 // (X+1) >u X --> X <u (0-1) --> X != 255
750 // (X+2) >u X --> X <u (0-2) --> X <u 254
751 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandsa7724332011-02-17 07:46:37 +0000752 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000753 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000754
Chris Lattner02446fc2010-01-04 07:37:31 +0000755 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
756 ConstantInt *SMax = ConstantInt::get(X->getContext(),
757 APInt::getSignedMaxValue(BitWidth));
758
759 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
760 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
761 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
762 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
763 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
764 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandsa7724332011-02-17 07:46:37 +0000765 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000766 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000767
Chris Lattner02446fc2010-01-04 07:37:31 +0000768 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
769 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
770 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
771 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
772 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
773 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000774
Chris Lattner02446fc2010-01-04 07:37:31 +0000775 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
776 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
777 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
778}
779
780/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
781/// and CmpRHS are both known to be integer constants.
782Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
783 ConstantInt *DivRHS) {
784 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
785 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000786
787 // FIXME: If the operand types don't match the type of the divide
Chris Lattner02446fc2010-01-04 07:37:31 +0000788 // then don't attempt this transform. The code below doesn't have the
789 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000790 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner02446fc2010-01-04 07:37:31 +0000791 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000792 // (x /u C1) <u C2. Simply casting the operands and result won't
793 // work. :( The if statement below tests that condition and bails
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000794 // if it finds it.
Chris Lattner02446fc2010-01-04 07:37:31 +0000795 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
796 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
797 return 0;
798 if (DivRHS->isZero())
799 return 0; // The ProdOV computation fails on divide by zero.
800 if (DivIsSigned && DivRHS->isAllOnesValue())
801 return 0; // The overflow computation also screws up here
Chris Lattnerbb75d332011-02-13 08:07:21 +0000802 if (DivRHS->isOne()) {
803 // This eliminates some funny cases with INT_MIN.
804 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
805 return &ICI;
806 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000807
808 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000809 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
810 // C2 (CI). By solving for X we can turn this into a range check
811 // instead of computing a divide.
Chris Lattner02446fc2010-01-04 07:37:31 +0000812 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
813
814 // Determine if the product overflows by seeing if the product is
815 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000816 // as in the LHS instruction that we're folding.
Chris Lattner02446fc2010-01-04 07:37:31 +0000817 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
818 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
819
820 // Get the ICmp opcode
821 ICmpInst::Predicate Pred = ICI.getPredicate();
822
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000823 /// If the division is known to be exact, then there is no remainder from the
824 /// divide, so the covered range size is unit, otherwise it is the divisor.
825 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000826
Chris Lattner02446fc2010-01-04 07:37:31 +0000827 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000828 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner02446fc2010-01-04 07:37:31 +0000829 // Compute this interval based on the constants involved and the signedness of
830 // the compare/divide. This computes a half-open interval, keeping track of
831 // whether either value in the interval overflows. After analysis each
832 // overflow variable is set to 0 if it's corresponding bound variable is valid
833 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
834 int LoOverflow = 0, HiOverflow = 0;
835 Constant *LoBound = 0, *HiBound = 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000836
Chris Lattner02446fc2010-01-04 07:37:31 +0000837 if (!DivIsSigned) { // udiv
838 // e.g. X/5 op 3 --> [15, 20)
839 LoBound = Prod;
840 HiOverflow = LoOverflow = ProdOV;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000841 if (!HiOverflow) {
842 // If this is not an exact divide, then many values in the range collapse
843 // to the same result value.
844 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
845 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000846
Chris Lattner02446fc2010-01-04 07:37:31 +0000847 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
848 if (CmpRHSV == 0) { // (X / pos) op 0
849 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000850 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
851 HiBound = RangeSize;
Chris Lattner02446fc2010-01-04 07:37:31 +0000852 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
853 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
854 HiOverflow = LoOverflow = ProdOV;
855 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000856 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000857 } else { // (X / pos) op neg
858 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
859 HiBound = AddOne(Prod);
860 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
861 if (!LoOverflow) {
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000862 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000863 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000864 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000865 }
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000866 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000867 if (DivI->isExact())
868 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000869 if (CmpRHSV == 0) { // (X / neg) op 0
870 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000871 LoBound = AddOne(RangeSize);
872 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000873 if (HiBound == DivRHS) { // -INTMIN = INTMIN
874 HiOverflow = 1; // [INTMIN+1, overflow)
875 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
876 }
877 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
878 // e.g. X/-5 op 3 --> [-19, -14)
879 HiBound = AddOne(Prod);
880 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
881 if (!LoOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000882 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner02446fc2010-01-04 07:37:31 +0000883 } else { // (X / neg) op neg
884 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
885 LoOverflow = HiOverflow = ProdOV;
886 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000887 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000888 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000889
Chris Lattner02446fc2010-01-04 07:37:31 +0000890 // Dividing by a negative swaps the condition. LT <-> GT
891 Pred = ICmpInst::getSwappedPredicate(Pred);
892 }
893
894 Value *X = DivI->getOperand(0);
895 switch (Pred) {
896 default: llvm_unreachable("Unhandled icmp opcode!");
897 case ICmpInst::ICMP_EQ:
898 if (LoOverflow && HiOverflow)
899 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000900 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000901 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
902 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000903 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000904 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
905 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000906 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
907 DivIsSigned, true));
Chris Lattner02446fc2010-01-04 07:37:31 +0000908 case ICmpInst::ICMP_NE:
909 if (LoOverflow && HiOverflow)
910 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000911 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000912 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
913 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000914 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000915 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
916 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000917 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
918 DivIsSigned, false));
Chris Lattner02446fc2010-01-04 07:37:31 +0000919 case ICmpInst::ICMP_ULT:
920 case ICmpInst::ICMP_SLT:
921 if (LoOverflow == +1) // Low bound is greater than input range.
922 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
923 if (LoOverflow == -1) // Low bound is less than input range.
924 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
925 return new ICmpInst(Pred, X, LoBound);
926 case ICmpInst::ICMP_UGT:
927 case ICmpInst::ICMP_SGT:
928 if (HiOverflow == +1) // High bound greater than input range.
929 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000930 if (HiOverflow == -1) // High bound less than input range.
Chris Lattner02446fc2010-01-04 07:37:31 +0000931 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
932 if (Pred == ICmpInst::ICMP_UGT)
933 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000934 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner02446fc2010-01-04 07:37:31 +0000935 }
936}
937
Chris Lattner74542aa2011-02-13 07:43:07 +0000938/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
939Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
940 ConstantInt *ShAmt) {
Chris Lattner74542aa2011-02-13 07:43:07 +0000941 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000942
Chris Lattner74542aa2011-02-13 07:43:07 +0000943 // Check that the shift amount is in range. If not, don't perform
944 // undefined shifts. When the shift is visited it will be
945 // simplified.
946 uint32_t TypeBits = CmpRHSV.getBitWidth();
947 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnerbb75d332011-02-13 08:07:21 +0000948 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattner74542aa2011-02-13 07:43:07 +0000949 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000950
Chris Lattnerbb75d332011-02-13 08:07:21 +0000951 if (!ICI.isEquality()) {
952 // If we have an unsigned comparison and an ashr, we can't simplify this.
953 // Similarly for signed comparisons with lshr.
954 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
955 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000956
Eli Friedmana831a9b2011-05-25 23:26:20 +0000957 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
958 // by a power of 2. Since we already have logic to simplify these,
959 // transform to div and then simplify the resultant comparison.
Chris Lattnerbb75d332011-02-13 08:07:21 +0000960 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedmana831a9b2011-05-25 23:26:20 +0000961 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattnerbb75d332011-02-13 08:07:21 +0000962 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000963
Chris Lattnerbb75d332011-02-13 08:07:21 +0000964 // Revisit the shift (to delete it).
965 Worklist.Add(Shr);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000966
Chris Lattnerbb75d332011-02-13 08:07:21 +0000967 Constant *DivCst =
968 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000969
Chris Lattnerbb75d332011-02-13 08:07:21 +0000970 Value *Tmp =
971 Shr->getOpcode() == Instruction::AShr ?
972 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
973 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000974
Chris Lattnerbb75d332011-02-13 08:07:21 +0000975 ICI.setOperand(0, Tmp);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000976
Chris Lattnerbb75d332011-02-13 08:07:21 +0000977 // If the builder folded the binop, just return it.
978 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
979 if (TheDiv == 0)
980 return &ICI;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000981
Chris Lattnerbb75d332011-02-13 08:07:21 +0000982 // Otherwise, fold this div/compare.
983 assert(TheDiv->getOpcode() == Instruction::SDiv ||
984 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000985
Chris Lattnerbb75d332011-02-13 08:07:21 +0000986 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
987 assert(Res && "This div/cst should have folded!");
988 return Res;
989 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000990
991
Chris Lattner74542aa2011-02-13 07:43:07 +0000992 // If we are comparing against bits always shifted out, the
993 // comparison cannot succeed.
994 APInt Comp = CmpRHSV << ShAmtVal;
995 ConstantInt *ShiftedCmpRHS = ConstantInt::get(ICI.getContext(), Comp);
996 if (Shr->getOpcode() == Instruction::LShr)
997 Comp = Comp.lshr(ShAmtVal);
998 else
999 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001000
Chris Lattner74542aa2011-02-13 07:43:07 +00001001 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1002 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1003 Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1004 IsICMP_NE);
1005 return ReplaceInstUsesWith(ICI, Cst);
1006 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001007
Chris Lattner74542aa2011-02-13 07:43:07 +00001008 // Otherwise, check to see if the bits shifted out are known to be zero.
1009 // If so, we can compare against the unshifted value:
1010 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattnere5116f82011-02-13 18:30:09 +00001011 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattner74542aa2011-02-13 07:43:07 +00001012 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001013
Chris Lattner74542aa2011-02-13 07:43:07 +00001014 if (Shr->hasOneUse()) {
1015 // Otherwise strength reduce the shift into an and.
1016 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1017 Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001018
Chris Lattner74542aa2011-02-13 07:43:07 +00001019 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1020 Mask, Shr->getName()+".mask");
1021 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1022 }
1023 return 0;
1024}
1025
Chris Lattner02446fc2010-01-04 07:37:31 +00001026
1027/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1028///
1029Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1030 Instruction *LHSI,
1031 ConstantInt *RHS) {
1032 const APInt &RHSV = RHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001033
Chris Lattner02446fc2010-01-04 07:37:31 +00001034 switch (LHSI->getOpcode()) {
1035 case Instruction::Trunc:
1036 if (ICI.isEquality() && LHSI->hasOneUse()) {
1037 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1038 // of the high bits truncated out of x are known.
1039 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1040 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner02446fc2010-01-04 07:37:31 +00001041 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001042 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001043
Chris Lattner02446fc2010-01-04 07:37:31 +00001044 // If all the high bits are known, we can do this xform.
1045 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1046 // Pull in the high bits from known-ones set.
Jay Foad40f8f622010-12-07 08:25:19 +00001047 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedman5b6dfee2012-05-11 01:32:59 +00001048 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner02446fc2010-01-04 07:37:31 +00001049 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1050 ConstantInt::get(ICI.getContext(), NewRHS));
1051 }
1052 }
1053 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001054
Chris Lattner02446fc2010-01-04 07:37:31 +00001055 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
1056 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1057 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1058 // fold the xor.
1059 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1060 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1061 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001062
Chris Lattner02446fc2010-01-04 07:37:31 +00001063 // If the sign bit of the XorCST is not set, there is no change to
1064 // the operation, just stop using the Xor.
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001065 if (!XorCST->isNegative()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001066 ICI.setOperand(0, CompareVal);
1067 Worklist.Add(LHSI);
1068 return &ICI;
1069 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001070
Chris Lattner02446fc2010-01-04 07:37:31 +00001071 // Was the old condition true if the operand is positive?
1072 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001073
Chris Lattner02446fc2010-01-04 07:37:31 +00001074 // If so, the new one isn't.
1075 isTrueIfPositive ^= true;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001076
Chris Lattner02446fc2010-01-04 07:37:31 +00001077 if (isTrueIfPositive)
1078 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1079 SubOne(RHS));
1080 else
1081 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1082 AddOne(RHS));
1083 }
1084
1085 if (LHSI->hasOneUse()) {
1086 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1087 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1088 const APInt &SignBit = XorCST->getValue();
1089 ICmpInst::Predicate Pred = ICI.isSigned()
1090 ? ICI.getUnsignedPredicate()
1091 : ICI.getSignedPredicate();
1092 return new ICmpInst(Pred, LHSI->getOperand(0),
1093 ConstantInt::get(ICI.getContext(),
1094 RHSV ^ SignBit));
1095 }
1096
1097 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001098 if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001099 const APInt &NotSignBit = XorCST->getValue();
1100 ICmpInst::Predicate Pred = ICI.isSigned()
1101 ? ICI.getUnsignedPredicate()
1102 : ICI.getSignedPredicate();
1103 Pred = ICI.getSwappedPredicate(Pred);
1104 return new ICmpInst(Pred, LHSI->getOperand(0),
1105 ConstantInt::get(ICI.getContext(),
1106 RHSV ^ NotSignBit));
1107 }
1108 }
1109 }
1110 break;
1111 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
1112 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1113 LHSI->getOperand(0)->hasOneUse()) {
1114 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001115
Chris Lattner02446fc2010-01-04 07:37:31 +00001116 // If the LHS is an AND of a truncating cast, we can widen the
1117 // and/compare to be the input width without changing the value
1118 // produced, eliminating a cast.
1119 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1120 // We can do this transformation if either the AND constant does not
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001121 // have its sign bit set or if it is an equality comparison.
Chris Lattner02446fc2010-01-04 07:37:31 +00001122 // Extending a relational comparison when we're checking the sign
1123 // bit would not work.
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001124 if (ICI.isEquality() ||
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001125 (!AndCST->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001126 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001127 Builder->CreateAnd(Cast->getOperand(0),
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001128 ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1129 NewAnd->takeName(LHSI);
Chris Lattner02446fc2010-01-04 07:37:31 +00001130 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001131 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001132 }
1133 }
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001134
1135 // If the LHS is an AND of a zext, and we have an equality compare, we can
1136 // shrink the and/compare to the smaller type, eliminating the cast.
1137 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001138 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001139 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1140 // should fold the icmp to true/false in that case.
1141 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1142 Value *NewAnd =
1143 Builder->CreateAnd(Cast->getOperand(0),
1144 ConstantExpr::getTrunc(AndCST, Ty));
1145 NewAnd->takeName(LHSI);
1146 return new ICmpInst(ICI.getPredicate(), NewAnd,
1147 ConstantExpr::getTrunc(RHS, Ty));
1148 }
1149 }
1150
Chris Lattner02446fc2010-01-04 07:37:31 +00001151 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1152 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1153 // happens a LOT in code produced by the C front-end, for bitfield
1154 // access.
1155 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1156 if (Shift && !Shift->isShift())
1157 Shift = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001158
Chris Lattner02446fc2010-01-04 07:37:31 +00001159 ConstantInt *ShAmt;
1160 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001161 Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
1162 Type *AndTy = AndCST->getType(); // Type of the and.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001163
Chris Lattner02446fc2010-01-04 07:37:31 +00001164 // We can fold this as long as we can't shift unknown bits
1165 // into the mask. This can only happen with signed shift
1166 // rights, as they sign-extend.
1167 if (ShAmt) {
1168 bool CanFold = Shift->isLogicalShift();
1169 if (!CanFold) {
1170 // To test for the bad case of the signed shr, see if any
1171 // of the bits shifted in could be tested after the mask.
1172 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1173 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001174
Chris Lattner02446fc2010-01-04 07:37:31 +00001175 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001176 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
Chris Lattner02446fc2010-01-04 07:37:31 +00001177 AndCST->getValue()) == 0)
1178 CanFold = true;
1179 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001180
Chris Lattner02446fc2010-01-04 07:37:31 +00001181 if (CanFold) {
1182 Constant *NewCst;
1183 if (Shift->getOpcode() == Instruction::Shl)
1184 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1185 else
1186 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001187
Chris Lattner02446fc2010-01-04 07:37:31 +00001188 // Check to see if we are shifting out any of the bits being
1189 // compared.
1190 if (ConstantExpr::get(Shift->getOpcode(),
1191 NewCst, ShAmt) != RHS) {
1192 // If we shifted bits out, the fold is not going to work out.
1193 // As a special case, check to see if this means that the
1194 // result is always true or false now.
1195 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1196 return ReplaceInstUsesWith(ICI,
1197 ConstantInt::getFalse(ICI.getContext()));
1198 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1199 return ReplaceInstUsesWith(ICI,
1200 ConstantInt::getTrue(ICI.getContext()));
1201 } else {
1202 ICI.setOperand(1, NewCst);
1203 Constant *NewAndCST;
1204 if (Shift->getOpcode() == Instruction::Shl)
1205 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1206 else
1207 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1208 LHSI->setOperand(1, NewAndCST);
1209 LHSI->setOperand(0, Shift->getOperand(0));
1210 Worklist.Add(Shift); // Shift is dead.
1211 return &ICI;
1212 }
1213 }
1214 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001215
Chris Lattner02446fc2010-01-04 07:37:31 +00001216 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1217 // preferable because it allows the C<<Y expression to be hoisted out
1218 // of a loop if Y is invariant and X is not.
1219 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1220 ICI.isEquality() && !Shift->isArithmeticShift() &&
1221 !isa<Constant>(Shift->getOperand(0))) {
1222 // Compute C << Y.
1223 Value *NS;
1224 if (Shift->getOpcode() == Instruction::LShr) {
Benjamin Kramera9390a42011-09-27 20:39:19 +00001225 NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001226 } else {
1227 // Insert a logical shift.
Benjamin Kramera9390a42011-09-27 20:39:19 +00001228 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001229 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001230
Chris Lattner02446fc2010-01-04 07:37:31 +00001231 // Compute X & (C << Y).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001232 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001233 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001234
Chris Lattner02446fc2010-01-04 07:37:31 +00001235 ICI.setOperand(0, NewAnd);
1236 return &ICI;
1237 }
Paul Redmond6da2e222012-12-19 19:47:13 +00001238
1239 // Replace ((X & AndCST) > RHSV) with ((X & AndCST) != 0), if any
1240 // bit set in (X & AndCST) will produce a result greater than RHSV.
1241 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1242 unsigned NTZ = AndCST->getValue().countTrailingZeros();
1243 if ((NTZ < AndCST->getBitWidth()) &&
1244 APInt::getOneBitSet(AndCST->getBitWidth(), NTZ).ugt(RHSV))
1245 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1246 Constant::getNullValue(RHS->getType()));
1247 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001248 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001249
Chris Lattner02446fc2010-01-04 07:37:31 +00001250 // Try to optimize things like "A[i]&42 == 0" to index computations.
1251 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1252 if (GetElementPtrInst *GEP =
1253 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1254 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1255 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1256 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1257 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1258 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1259 return Res;
1260 }
1261 }
1262 break;
1263
1264 case Instruction::Or: {
1265 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1266 break;
1267 Value *P, *Q;
1268 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1269 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1270 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner02446fc2010-01-04 07:37:31 +00001271 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1272 Constant::getNullValue(P->getType()));
1273 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1274 Constant::getNullValue(Q->getType()));
1275 Instruction *Op;
1276 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1277 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1278 else
1279 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1280 return Op;
1281 }
1282 break;
1283 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001284
Chris Lattner02446fc2010-01-04 07:37:31 +00001285 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
1286 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1287 if (!ShAmt) break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001288
Chris Lattner02446fc2010-01-04 07:37:31 +00001289 uint32_t TypeBits = RHSV.getBitWidth();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001290
Chris Lattner02446fc2010-01-04 07:37:31 +00001291 // Check that the shift amount is in range. If not, don't perform
1292 // undefined shifts. When the shift is visited it will be
1293 // simplified.
1294 if (ShAmt->uge(TypeBits))
1295 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001296
Chris Lattner02446fc2010-01-04 07:37:31 +00001297 if (ICI.isEquality()) {
1298 // If we are comparing against bits always shifted out, the
1299 // comparison cannot succeed.
1300 Constant *Comp =
1301 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1302 ShAmt);
1303 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1304 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1305 Constant *Cst =
1306 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
1307 return ReplaceInstUsesWith(ICI, Cst);
1308 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001309
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001310 // If the shift is NUW, then it is just shifting out zeros, no need for an
1311 // AND.
1312 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1313 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1314 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001315
Chris Lattner02446fc2010-01-04 07:37:31 +00001316 if (LHSI->hasOneUse()) {
1317 // Otherwise strength reduce the shift into an and.
1318 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1319 Constant *Mask =
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001320 ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
Chris Lattner02446fc2010-01-04 07:37:31 +00001321 TypeBits-ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001322
Chris Lattner02446fc2010-01-04 07:37:31 +00001323 Value *And =
1324 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1325 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001326 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner02446fc2010-01-04 07:37:31 +00001327 }
1328 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001329
Chris Lattner02446fc2010-01-04 07:37:31 +00001330 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1331 bool TrueIfSigned = false;
1332 if (LHSI->hasOneUse() &&
1333 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1334 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattnerbb75d332011-02-13 08:07:21 +00001335 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001336 APInt::getOneBitSet(TypeBits,
Chris Lattnerbb75d332011-02-13 08:07:21 +00001337 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001338 Value *And =
1339 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1340 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1341 And, Constant::getNullValue(And->getType()));
1342 }
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001343
1344 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaisonbdd2d982013-03-13 14:40:37 +00001345 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1346 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001347 // This enables to get rid of the shift in favor of a trunc which can be
1348 // free on the target. It has the additional benefit of comparing to a
1349 // smaller constant, which will be target friendly.
1350 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaisonbdd2d982013-03-13 14:40:37 +00001351 if (LHSI->hasOneUse() &&
1352 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001353 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1354 Constant *NCI = ConstantExpr::getTrunc(
1355 ConstantExpr::getAShr(RHS,
1356 ConstantInt::get(RHS->getType(), Amt)),
1357 NTy);
1358 return new ICmpInst(ICI.getPredicate(),
1359 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaisonad079b22013-02-15 15:18:17 +00001360 NCI);
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001361 }
1362
Chris Lattner02446fc2010-01-04 07:37:31 +00001363 break;
1364 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001365
Chris Lattner02446fc2010-01-04 07:37:31 +00001366 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001367 case Instruction::AShr: {
1368 // Handle equality comparisons of shift-by-constant.
1369 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1370 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1371 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattner74542aa2011-02-13 07:43:07 +00001372 return Res;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001373 }
1374
1375 // Handle exact shr's.
1376 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1377 if (RHSV.isMinValue())
1378 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1379 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001380 break;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001381 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001382
Chris Lattner02446fc2010-01-04 07:37:31 +00001383 case Instruction::SDiv:
1384 case Instruction::UDiv:
1385 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001386 // Fold this div into the comparison, producing a range check.
1387 // Determine, based on the divide type, what the range is being
1388 // checked. If there is an overflow on the low or high side, remember
Chris Lattner02446fc2010-01-04 07:37:31 +00001389 // it, otherwise compute the range [low, hi) bounding the new value.
1390 // See: InsertRangeTest above for the kinds of replacements possible.
1391 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1392 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1393 DivRHS))
1394 return R;
1395 break;
1396
1397 case Instruction::Add:
1398 // Fold: icmp pred (add X, C1), C2
1399 if (!ICI.isEquality()) {
1400 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1401 if (!LHSC) break;
1402 const APInt &LHSV = LHSC->getValue();
1403
1404 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1405 .subtract(LHSV);
1406
1407 if (ICI.isSigned()) {
1408 if (CR.getLower().isSignBit()) {
1409 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1410 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1411 } else if (CR.getUpper().isSignBit()) {
1412 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1413 ConstantInt::get(ICI.getContext(),CR.getLower()));
1414 }
1415 } else {
1416 if (CR.getLower().isMinValue()) {
1417 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1418 ConstantInt::get(ICI.getContext(),CR.getUpper()));
1419 } else if (CR.getUpper().isMinValue()) {
1420 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1421 ConstantInt::get(ICI.getContext(),CR.getLower()));
1422 }
1423 }
1424 }
1425 break;
1426 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001427
Chris Lattner02446fc2010-01-04 07:37:31 +00001428 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1429 if (ICI.isEquality()) {
1430 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001431
1432 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner02446fc2010-01-04 07:37:31 +00001433 // the second operand is a constant, simplify a bit.
1434 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1435 switch (BO->getOpcode()) {
1436 case Instruction::SRem:
1437 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1438 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1439 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohmane0567812010-04-08 23:03:40 +00001440 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001441 Value *NewRem =
1442 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1443 BO->getName());
1444 return new ICmpInst(ICI.getPredicate(), NewRem,
1445 Constant::getNullValue(BO->getType()));
1446 }
1447 }
1448 break;
1449 case Instruction::Add:
1450 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1451 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1452 if (BO->hasOneUse())
1453 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1454 ConstantExpr::getSub(RHS, BOp1C));
1455 } else if (RHSV == 0) {
1456 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1457 // efficiently invertible, or if the add has just this one use.
1458 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001459
Chris Lattner02446fc2010-01-04 07:37:31 +00001460 if (Value *NegVal = dyn_castNegVal(BOp1))
1461 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner5036ce42011-04-26 20:02:45 +00001462 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner02446fc2010-01-04 07:37:31 +00001463 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner5036ce42011-04-26 20:02:45 +00001464 if (BO->hasOneUse()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001465 Value *Neg = Builder->CreateNeg(BOp1);
1466 Neg->takeName(BO);
1467 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1468 }
1469 }
1470 break;
1471 case Instruction::Xor:
1472 // For the xor case, we can xor two constants together, eliminating
1473 // the explicit xor.
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001474 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1475 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner02446fc2010-01-04 07:37:31 +00001476 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001477 } else if (RHSV == 0) {
1478 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner02446fc2010-01-04 07:37:31 +00001479 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1480 BO->getOperand(1));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001481 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001482 break;
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001483 case Instruction::Sub:
1484 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1485 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1486 if (BO->hasOneUse())
1487 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1488 ConstantExpr::getSub(BOp0C, RHS));
1489 } else if (RHSV == 0) {
1490 // Replace ((sub A, B) != 0) with (A != B)
1491 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1492 BO->getOperand(1));
1493 }
1494 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001495 case Instruction::Or:
1496 // If bits are being or'd in that are not present in the constant we
1497 // are comparing against, then the comparison could never succeed!
Eli Friedman618898e2010-07-29 18:03:33 +00001498 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001499 Constant *NotCI = ConstantExpr::getNot(RHS);
1500 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1501 return ReplaceInstUsesWith(ICI,
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001502 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Chris Lattner02446fc2010-01-04 07:37:31 +00001503 isICMP_NE));
1504 }
1505 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001506
Chris Lattner02446fc2010-01-04 07:37:31 +00001507 case Instruction::And:
1508 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1509 // If bits are being compared against that are and'd out, then the
1510 // comparison can never succeed!
1511 if ((RHSV & ~BOC->getValue()) != 0)
1512 return ReplaceInstUsesWith(ICI,
1513 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
1514 isICMP_NE));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001515
Chris Lattner02446fc2010-01-04 07:37:31 +00001516 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1517 if (RHS == BOC && RHSV.isPowerOf2())
1518 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1519 ICmpInst::ICMP_NE, LHSI,
1520 Constant::getNullValue(RHS->getType()));
Benjamin Kramerfc87cdc2011-07-04 20:16:36 +00001521
1522 // Don't perform the following transforms if the AND has multiple uses
1523 if (!BO->hasOneUse())
1524 break;
1525
Chris Lattner02446fc2010-01-04 07:37:31 +00001526 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1527 if (BOC->getValue().isSignBit()) {
1528 Value *X = BO->getOperand(0);
1529 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001530 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001531 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1532 return new ICmpInst(pred, X, Zero);
1533 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001534
Chris Lattner02446fc2010-01-04 07:37:31 +00001535 // ((X & ~7) == 0) --> X < 8
1536 if (RHSV == 0 && isHighOnes(BOC)) {
1537 Value *X = BO->getOperand(0);
1538 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001539 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001540 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1541 return new ICmpInst(pred, X, NegX);
1542 }
1543 }
1544 default: break;
1545 }
1546 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1547 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner03357402010-01-05 18:09:56 +00001548 switch (II->getIntrinsicID()) {
1549 case Intrinsic::bswap:
Chris Lattner02446fc2010-01-04 07:37:31 +00001550 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001551 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00001552 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
1553 return &ICI;
Chris Lattner03357402010-01-05 18:09:56 +00001554 case Intrinsic::ctlz:
1555 case Intrinsic::cttz:
1556 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1557 if (RHSV == RHS->getType()->getBitWidth()) {
1558 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001559 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001560 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1561 return &ICI;
1562 }
1563 break;
1564 case Intrinsic::ctpop:
1565 // popcount(A) == 0 -> A == 0 and likewise for !=
1566 if (RHS->isZero()) {
1567 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001568 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001569 ICI.setOperand(1, RHS);
1570 return &ICI;
1571 }
1572 break;
1573 default:
Duncan Sands34727662010-07-12 08:16:59 +00001574 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001575 }
1576 }
1577 }
1578 return 0;
1579}
1580
1581/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1582/// We only handle extending casts so far.
1583///
1584Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1585 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1586 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001587 Type *SrcTy = LHSCIOp->getType();
1588 Type *DestTy = LHSCI->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001589 Value *RHSCIOp;
1590
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001591 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner02446fc2010-01-04 07:37:31 +00001592 // integer type is the same size as the pointer type.
1593 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +00001594 TD->getPointerSizeInBits() ==
Chris Lattner02446fc2010-01-04 07:37:31 +00001595 cast<IntegerType>(DestTy)->getBitWidth()) {
1596 Value *RHSOp = 0;
1597 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1598 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1599 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1600 RHSOp = RHSC->getOperand(0);
1601 // If the pointer types don't match, insert a bitcast.
1602 if (LHSCIOp->getType() != RHSOp->getType())
1603 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1604 }
1605
1606 if (RHSOp)
1607 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1608 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001609
Chris Lattner02446fc2010-01-04 07:37:31 +00001610 // The code below only handles extension cast instructions, so far.
1611 // Enforce this.
1612 if (LHSCI->getOpcode() != Instruction::ZExt &&
1613 LHSCI->getOpcode() != Instruction::SExt)
1614 return 0;
1615
1616 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1617 bool isSignedCmp = ICI.isSigned();
1618
1619 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1620 // Not an extension from the same type?
1621 RHSCIOp = CI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001622 if (RHSCIOp->getType() != LHSCIOp->getType())
Chris Lattner02446fc2010-01-04 07:37:31 +00001623 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001624
Chris Lattner02446fc2010-01-04 07:37:31 +00001625 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1626 // and the other is a zext), then we can't handle this.
1627 if (CI->getOpcode() != LHSCI->getOpcode())
1628 return 0;
1629
1630 // Deal with equality cases early.
1631 if (ICI.isEquality())
1632 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1633
1634 // A signed comparison of sign extended values simplifies into a
1635 // signed comparison.
1636 if (isSignedCmp && isSignedExt)
1637 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1638
1639 // The other three cases all fold into an unsigned comparison.
1640 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1641 }
1642
1643 // If we aren't dealing with a constant on the RHS, exit early
1644 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1645 if (!CI)
1646 return 0;
1647
1648 // Compute the constant that would happen if we truncated to SrcTy then
1649 // reextended to DestTy.
1650 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1651 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1652 Res1, DestTy);
1653
1654 // If the re-extended constant didn't change...
1655 if (Res2 == CI) {
1656 // Deal with equality cases early.
1657 if (ICI.isEquality())
1658 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1659
1660 // A signed comparison of sign extended values simplifies into a
1661 // signed comparison.
1662 if (isSignedExt && isSignedCmp)
1663 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1664
1665 // The other three cases all fold into an unsigned comparison.
1666 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1667 }
1668
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001669 // The re-extended constant changed so the constant cannot be represented
Chris Lattner02446fc2010-01-04 07:37:31 +00001670 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands9d32f602011-01-20 13:21:55 +00001671 // All the cases that fold to true or false will have already been handled
1672 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner02446fc2010-01-04 07:37:31 +00001673
Duncan Sands9d32f602011-01-20 13:21:55 +00001674 if (isSignedCmp || !isSignedExt)
1675 return 0;
Chris Lattner02446fc2010-01-04 07:37:31 +00001676
1677 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1678 // should have been folded away previously and not enter in here.
Duncan Sands9d32f602011-01-20 13:21:55 +00001679
1680 // We're performing an unsigned comp with a sign extended value.
1681 // This is true if the input is >= 0. [aka >s -1]
1682 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1683 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner02446fc2010-01-04 07:37:31 +00001684
1685 // Finally, return the value computed.
Duncan Sands9d32f602011-01-20 13:21:55 +00001686 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner02446fc2010-01-04 07:37:31 +00001687 return ReplaceInstUsesWith(ICI, Result);
1688
Duncan Sands9d32f602011-01-20 13:21:55 +00001689 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner02446fc2010-01-04 07:37:31 +00001690 return BinaryOperator::CreateNot(Result);
1691}
1692
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001693/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1694/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001695/// If this is of the form:
1696/// sum = a + b
1697/// if (sum+128 >u 255)
1698/// Then replace it with llvm.sadd.with.overflow.i8.
1699///
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001700static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1701 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001702 InstCombiner &IC) {
Chris Lattner368397b2010-12-19 17:59:02 +00001703 // The transformation we're trying to do here is to transform this into an
1704 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1705 // with a narrower add, and discard the add-with-constant that is part of the
1706 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001707
Chris Lattner368397b2010-12-19 17:59:02 +00001708 // In order to eliminate the add-with-constant, the compare can be its only
1709 // use.
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001710 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattner368397b2010-12-19 17:59:02 +00001711 if (!AddWithCst->hasOneUse()) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001712
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001713 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1714 if (!CI2->getValue().isPowerOf2()) return 0;
1715 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1716 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001717
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001718 // The width of the new add formed is 1 more than the bias.
1719 ++NewWidth;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001720
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001721 // Check to see that CI1 is an all-ones value with NewWidth bits.
1722 if (CI1->getBitWidth() == NewWidth ||
1723 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1724 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001725
Eli Friedman54b92112011-11-28 23:32:19 +00001726 // This is only really a signed overflow check if the inputs have been
1727 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1728 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1729 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1730 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1731 IC.ComputeNumSignBits(B) < NeededSignBits)
1732 return 0;
1733
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001734 // In order to replace the original add with a narrower
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001735 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1736 // and truncates that discard the high bits of the add. Verify that this is
1737 // the case.
1738 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1739 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1740 UI != E; ++UI) {
1741 if (*UI == AddWithCst) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001742
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001743 // Only accept truncates for now. We would really like a nice recursive
1744 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1745 // chain to see which bits of a value are actually demanded. If the
1746 // original add had another add which was then immediately truncated, we
1747 // could still do the transformation.
1748 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1749 if (TI == 0 ||
1750 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1751 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001752
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001753 // If the pattern matches, truncate the inputs to the narrower type and
1754 // use the sadd_with_overflow intrinsic to efficiently compute both the
1755 // result and the overflow bit.
Chris Lattner0a624742010-12-19 18:35:09 +00001756 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001757
Jay Foad5fdd6c82011-07-12 14:06:48 +00001758 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner0a624742010-12-19 18:35:09 +00001759 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001760 NewType);
Chris Lattner0a624742010-12-19 18:35:09 +00001761
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001762 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001763
Chris Lattner0a624742010-12-19 18:35:09 +00001764 // Put the new code above the original add, in case there are any uses of the
1765 // add between the add and the compare.
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001766 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001767
Chris Lattner0a624742010-12-19 18:35:09 +00001768 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1769 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1770 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1771 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1772 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001773
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001774 // The inner add was the result of the narrow add, zero extended to the
1775 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001776 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001777
Chris Lattner0a624742010-12-19 18:35:09 +00001778 // The original icmp gets replaced with the overflow value.
1779 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001780}
Chris Lattner02446fc2010-01-04 07:37:31 +00001781
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001782static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1783 InstCombiner &IC) {
1784 // Don't bother doing this transformation for pointers, don't do it for
1785 // vectors.
1786 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001787
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001788 // If the add is a constant expr, then we don't bother transforming it.
1789 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1790 if (OrigAdd == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001791
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001792 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001793
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001794 // Put the new code above the original add, in case there are any uses of the
1795 // add between the add and the compare.
1796 InstCombiner::BuilderTy *Builder = IC.Builder;
1797 Builder->SetInsertPoint(OrigAdd);
1798
1799 Module *M = I.getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001800 Type *Ty = LHS->getType();
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001801 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001802 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1803 Value *Add = Builder->CreateExtractValue(Call, 0);
1804
1805 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1806
1807 // The original icmp gets replaced with the overflow value.
1808 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1809}
1810
Owen Andersonda1c1222011-01-11 00:36:45 +00001811// DemandedBitsLHSMask - When performing a comparison against a constant,
1812// it is possible that not all the bits in the LHS are demanded. This helper
1813// method computes the mask that IS demanded.
1814static APInt DemandedBitsLHSMask(ICmpInst &I,
1815 unsigned BitWidth, bool isSignCheck) {
1816 if (isSignCheck)
1817 return APInt::getSignBit(BitWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001818
Owen Andersonda1c1222011-01-11 00:36:45 +00001819 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
1820 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Andersona33b6252011-01-11 18:26:37 +00001821 const APInt &RHS = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001822
Owen Andersonda1c1222011-01-11 00:36:45 +00001823 switch (I.getPredicate()) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001824 // For a UGT comparison, we don't care about any bits that
Owen Andersonda1c1222011-01-11 00:36:45 +00001825 // correspond to the trailing ones of the comparand. The value of these
1826 // bits doesn't impact the outcome of the comparison, because any value
1827 // greater than the RHS must differ in a bit higher than these due to carry.
1828 case ICmpInst::ICMP_UGT: {
1829 unsigned trailingOnes = RHS.countTrailingOnes();
1830 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
1831 return ~lowBitsSet;
1832 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001833
Owen Andersonda1c1222011-01-11 00:36:45 +00001834 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
1835 // Any value less than the RHS must differ in a higher bit because of carries.
1836 case ICmpInst::ICMP_ULT: {
1837 unsigned trailingZeros = RHS.countTrailingZeros();
1838 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
1839 return ~lowBitsSet;
1840 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001841
Owen Andersonda1c1222011-01-11 00:36:45 +00001842 default:
1843 return APInt::getAllOnesValue(BitWidth);
1844 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001845
Owen Andersonda1c1222011-01-11 00:36:45 +00001846}
Chris Lattner02446fc2010-01-04 07:37:31 +00001847
1848Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
1849 bool Changed = false;
Chris Lattner5f670d42010-02-01 19:54:45 +00001850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001851
Chris Lattner02446fc2010-01-04 07:37:31 +00001852 /// Orders the operands of the compare so that they are listed from most
1853 /// complex to least complex. This puts constants before unary operators,
1854 /// before binary operators.
Chris Lattner5f670d42010-02-01 19:54:45 +00001855 if (getComplexity(Op0) < getComplexity(Op1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001856 I.swapOperands();
Chris Lattner5f670d42010-02-01 19:54:45 +00001857 std::swap(Op0, Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00001858 Changed = true;
1859 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001860
Chris Lattner02446fc2010-01-04 07:37:31 +00001861 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
1862 return ReplaceInstUsesWith(I, V);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001863
Pete Cooper65a6b572011-12-01 03:58:40 +00001864 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooper165695d2011-12-01 19:13:26 +00001865 // ie, abs(val) != 0 -> val != 0
Pete Cooper65a6b572011-12-01 03:58:40 +00001866 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
1867 {
Pete Cooper165695d2011-12-01 19:13:26 +00001868 Value *Cond, *SelectTrue, *SelectFalse;
1869 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooper65a6b572011-12-01 03:58:40 +00001870 m_Value(SelectFalse)))) {
Pete Cooper165695d2011-12-01 19:13:26 +00001871 if (Value *V = dyn_castNegVal(SelectTrue)) {
1872 if (V == SelectFalse)
1873 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
1874 }
1875 else if (Value *V = dyn_castNegVal(SelectFalse)) {
1876 if (V == SelectTrue)
1877 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooper65a6b572011-12-01 03:58:40 +00001878 }
1879 }
1880 }
1881
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001882 Type *Ty = Op0->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001883
1884 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001885 if (Ty->isIntegerTy(1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001886 switch (I.getPredicate()) {
1887 default: llvm_unreachable("Invalid icmp instruction!");
1888 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
1889 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
1890 return BinaryOperator::CreateNot(Xor);
1891 }
1892 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
1893 return BinaryOperator::CreateXor(Op0, Op1);
1894
1895 case ICmpInst::ICMP_UGT:
1896 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
1897 // FALL THROUGH
1898 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
1899 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1900 return BinaryOperator::CreateAnd(Not, Op1);
1901 }
1902 case ICmpInst::ICMP_SGT:
1903 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
1904 // FALL THROUGH
1905 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
1906 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1907 return BinaryOperator::CreateAnd(Not, Op0);
1908 }
1909 case ICmpInst::ICMP_UGE:
1910 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
1911 // FALL THROUGH
1912 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
1913 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
1914 return BinaryOperator::CreateOr(Not, Op1);
1915 }
1916 case ICmpInst::ICMP_SGE:
1917 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
1918 // FALL THROUGH
1919 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
1920 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
1921 return BinaryOperator::CreateOr(Not, Op0);
1922 }
1923 }
1924 }
1925
1926 unsigned BitWidth = 0;
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001927 if (Ty->isIntOrIntVectorTy())
Chris Lattner02446fc2010-01-04 07:37:31 +00001928 BitWidth = Ty->getScalarSizeInBits();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001929 else if (TD) // Pointers require TD info to get their size.
1930 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001931
Chris Lattner02446fc2010-01-04 07:37:31 +00001932 bool isSignBit = false;
1933
1934 // See if we are doing a comparison with a constant.
1935 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1936 Value *A = 0, *B = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001937
Owen Andersone63dda52010-12-17 18:08:00 +00001938 // Match the following pattern, which is a common idiom when writing
1939 // overflow-safe integer arithmetic function. The source performs an
1940 // addition in wider type, and explicitly checks for overflow using
1941 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
1942 // sadd_with_overflow intrinsic.
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001943 //
1944 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001945 // operations if we worked out the formulas to compute the appropriate
Owen Andersone63dda52010-12-17 18:08:00 +00001946 // magic constants.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001947 //
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001948 // sum = a + b
1949 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Andersone63dda52010-12-17 18:08:00 +00001950 {
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001951 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Andersone63dda52010-12-17 18:08:00 +00001952 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001953 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001954 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001955 return Res;
Owen Andersone63dda52010-12-17 18:08:00 +00001956 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001957
Chris Lattner02446fc2010-01-04 07:37:31 +00001958 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
1959 if (I.isEquality() && CI->isZero() &&
1960 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
1961 // (icmp cond A B) if cond is equality
1962 return new ICmpInst(I.getPredicate(), A, B);
1963 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001964
Chris Lattner02446fc2010-01-04 07:37:31 +00001965 // If we have an icmp le or icmp ge instruction, turn it into the
1966 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
1967 // them being folded in the code below. The SimplifyICmpInst code has
1968 // already handled the edge cases for us, so we just assert on them.
1969 switch (I.getPredicate()) {
1970 default: break;
1971 case ICmpInst::ICMP_ULE:
1972 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
1973 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
1974 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1975 case ICmpInst::ICMP_SLE:
1976 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
1977 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
1978 ConstantInt::get(CI->getContext(), CI->getValue()+1));
1979 case ICmpInst::ICMP_UGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001980 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001981 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
1982 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1983 case ICmpInst::ICMP_SGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00001984 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00001985 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
1986 ConstantInt::get(CI->getContext(), CI->getValue()-1));
1987 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001988
Chris Lattner02446fc2010-01-04 07:37:31 +00001989 // If this comparison is a normal comparison, it demands all
1990 // bits, if it is a sign bit comparison, it only demands the sign bit.
1991 bool UnusedBit;
1992 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
1993 }
1994
1995 // See if we can fold the comparison based on range information we can get
1996 // by checking whether bits are known to be zero or one in the input.
1997 if (BitWidth != 0) {
1998 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
1999 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2000
2001 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersonda1c1222011-01-11 00:36:45 +00002002 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner02446fc2010-01-04 07:37:31 +00002003 Op0KnownZero, Op0KnownOne, 0))
2004 return &I;
2005 if (SimplifyDemandedBits(I.getOperandUse(1),
2006 APInt::getAllOnesValue(BitWidth),
2007 Op1KnownZero, Op1KnownOne, 0))
2008 return &I;
2009
2010 // Given the known and unknown bits, compute a range that the LHS could be
2011 // in. Compute the Min, Max and RHS values based on the known bits. For the
2012 // EQ and NE we use unsigned values.
2013 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2014 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2015 if (I.isSigned()) {
2016 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2017 Op0Min, Op0Max);
2018 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2019 Op1Min, Op1Max);
2020 } else {
2021 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2022 Op0Min, Op0Max);
2023 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2024 Op1Min, Op1Max);
2025 }
2026
2027 // If Min and Max are known to be the same, then SimplifyDemandedBits
2028 // figured out that the LHS is a constant. Just constant fold this now so
2029 // that code below can assume that Min != Max.
2030 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2031 return new ICmpInst(I.getPredicate(),
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002032 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00002033 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2034 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002035 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner02446fc2010-01-04 07:37:31 +00002036
2037 // Based on the range information we know about the LHS, see if we can
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002038 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner02446fc2010-01-04 07:37:31 +00002039 switch (I.getPredicate()) {
2040 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner75d8f592010-11-21 06:44:42 +00002041 case ICmpInst::ICMP_EQ: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002042 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002043 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002044
Chris Lattner75d8f592010-11-21 06:44:42 +00002045 // If all bits are known zero except for one, then we know at most one
2046 // bit is set. If the comparison is against zero, then this is a check
2047 // to see if *that* bit is set.
2048 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2049 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2050 // If the LHS is an AND with the same constant, look through it.
2051 Value *LHS = 0;
2052 ConstantInt *LHSC = 0;
2053 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2054 LHSC->getValue() != Op0KnownZeroInverted)
2055 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002056
Chris Lattner75d8f592010-11-21 06:44:42 +00002057 // 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 +00002058 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002059 Value *X = 0;
2060 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2061 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002062 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002063 ConstantInt::get(X->getType(), CmpVal));
2064 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002065
Chris Lattner75d8f592010-11-21 06:44:42 +00002066 // 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 +00002067 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002068 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002069 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002070 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002071 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002072 ConstantInt::get(X->getType(),
2073 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002074 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002075
Chris Lattner02446fc2010-01-04 07:37:31 +00002076 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002077 }
2078 case ICmpInst::ICMP_NE: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002079 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002080 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002081
Chris Lattner75d8f592010-11-21 06:44:42 +00002082 // If all bits are known zero except for one, then we know at most one
2083 // bit is set. If the comparison is against zero, then this is a check
2084 // to see if *that* bit is set.
2085 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2086 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2087 // If the LHS is an AND with the same constant, look through it.
2088 Value *LHS = 0;
2089 ConstantInt *LHSC = 0;
2090 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2091 LHSC->getValue() != Op0KnownZeroInverted)
2092 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002093
Chris Lattner75d8f592010-11-21 06:44:42 +00002094 // 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 +00002095 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002096 Value *X = 0;
2097 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2098 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002099 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002100 ConstantInt::get(X->getType(), CmpVal));
2101 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002102
Chris Lattner75d8f592010-11-21 06:44:42 +00002103 // 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 +00002104 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002105 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002106 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002107 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002108 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002109 ConstantInt::get(X->getType(),
2110 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002111 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002112
Chris Lattner02446fc2010-01-04 07:37:31 +00002113 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002114 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002115 case ICmpInst::ICMP_ULT:
2116 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002117 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002118 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002119 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002120 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2121 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2122 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2123 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2124 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2125 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2126
2127 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2128 if (CI->isMinValue(true))
2129 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2130 Constant::getAllOnesValue(Op0->getType()));
2131 }
2132 break;
2133 case ICmpInst::ICMP_UGT:
2134 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002135 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002136 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002137 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002138
2139 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2140 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2141 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2142 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2143 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2144 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2145
2146 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2147 if (CI->isMaxValue(true))
2148 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2149 Constant::getNullValue(Op0->getType()));
2150 }
2151 break;
2152 case ICmpInst::ICMP_SLT:
2153 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002154 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002155 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002156 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002157 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2158 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2159 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2160 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2161 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2162 ConstantInt::get(CI->getContext(), CI->getValue()-1));
2163 }
2164 break;
2165 case ICmpInst::ICMP_SGT:
2166 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002167 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002168 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002169 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002170
2171 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2172 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2173 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2174 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2175 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2176 ConstantInt::get(CI->getContext(), CI->getValue()+1));
2177 }
2178 break;
2179 case ICmpInst::ICMP_SGE:
2180 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2181 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002182 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002183 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002184 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002185 break;
2186 case ICmpInst::ICMP_SLE:
2187 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2188 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002189 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002190 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002191 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002192 break;
2193 case ICmpInst::ICMP_UGE:
2194 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2195 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002196 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002197 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002198 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002199 break;
2200 case ICmpInst::ICMP_ULE:
2201 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2202 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002203 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002204 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002205 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002206 break;
2207 }
2208
2209 // Turn a signed comparison into an unsigned one if both operands
2210 // are known to have the same sign.
2211 if (I.isSigned() &&
2212 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2213 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2214 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2215 }
2216
2217 // Test if the ICmpInst instruction is used exclusively by a select as
2218 // part of a minimum or maximum operation. If so, refrain from doing
2219 // any other folding. This helps out other analyses which understand
2220 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2221 // and CodeGen. And in this case, at least one of the comparison
2222 // operands has at least one user besides the compare (the select),
2223 // which would often largely negate the benefit of folding anyway.
2224 if (I.hasOneUse())
2225 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2226 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2227 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2228 return 0;
2229
2230 // See if we are doing a comparison between a constant and an instruction that
2231 // can be folded into the comparison.
2232 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002233 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2234 // instruction, see if that instruction also has constants so that the
2235 // instruction can be folded into the icmp
Chris Lattner02446fc2010-01-04 07:37:31 +00002236 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2237 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2238 return Res;
2239 }
2240
2241 // Handle icmp with constant (but not simple integer constant) RHS
2242 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2243 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2244 switch (LHSI->getOpcode()) {
2245 case Instruction::GetElementPtr:
2246 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2247 if (RHSC->isNullValue() &&
2248 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2249 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2250 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2251 break;
2252 case Instruction::PHI:
2253 // Only fold icmp into the PHI if the phi and icmp are in the same
2254 // block. If in the same block, we're encouraging jump threading. If
2255 // not, we are just pessimizing the code by making an i1 phi.
2256 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002257 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002258 return NV;
2259 break;
2260 case Instruction::Select: {
2261 // If either operand of the select is a constant, we can fold the
2262 // comparison into the select arms, which will cause one to be
2263 // constant folded and the select turned into a bitwise or.
2264 Value *Op1 = 0, *Op2 = 0;
2265 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2266 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2267 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2268 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2269
2270 // We only want to perform this transformation if it will not lead to
2271 // additional code. This is true if either both sides of the select
2272 // fold to a constant (in which case the icmp is replaced with a select
2273 // which will usually simplify) or this is the only user of the
2274 // select (in which case we are trading a select+icmp for a simpler
2275 // select+icmp).
2276 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2277 if (!Op1)
2278 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2279 RHSC, I.getName());
2280 if (!Op2)
2281 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2282 RHSC, I.getName());
2283 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2284 }
2285 break;
2286 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002287 case Instruction::IntToPtr:
2288 // icmp pred inttoptr(X), null -> icmp pred X, 0
2289 if (RHSC->isNullValue() && TD &&
Chandler Carruthece6c6b2012-11-01 08:07:29 +00002290 TD->getIntPtrType(RHSC->getContext()) ==
Chris Lattner02446fc2010-01-04 07:37:31 +00002291 LHSI->getOperand(0)->getType())
2292 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2293 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2294 break;
2295
2296 case Instruction::Load:
2297 // Try to optimize things like "A[i] > 4" to index computations.
2298 if (GetElementPtrInst *GEP =
2299 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2300 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2301 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2302 !cast<LoadInst>(LHSI)->isVolatile())
2303 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2304 return Res;
2305 }
2306 break;
2307 }
2308 }
2309
2310 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2311 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2312 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2313 return NI;
2314 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2315 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2316 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2317 return NI;
2318
2319 // Test to see if the operands of the icmp are casted versions of other
2320 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2321 // now.
2322 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002323 if (Op0->getType()->isPointerTy() &&
2324 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002325 // We keep moving the cast from the left operand over to the right
2326 // operand, where it can often be eliminated completely.
2327 Op0 = CI->getOperand(0);
2328
2329 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2330 // so eliminate it as well.
2331 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2332 Op1 = CI2->getOperand(0);
2333
2334 // If Op1 is a constant, we can fold the cast into the constant.
2335 if (Op0->getType() != Op1->getType()) {
2336 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2337 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2338 } else {
2339 // Otherwise, cast the RHS right before the icmp
2340 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2341 }
2342 }
2343 return new ICmpInst(I.getPredicate(), Op0, Op1);
2344 }
2345 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002346
Chris Lattner02446fc2010-01-04 07:37:31 +00002347 if (isa<CastInst>(Op0)) {
2348 // Handle the special case of: icmp (cast bool to X), <cst>
2349 // This comes up when you have code like
2350 // int X = A < B;
2351 // if (X) ...
2352 // For generality, we handle any zero-extension of any operand comparison
2353 // with a constant or another cast from the same type.
2354 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2355 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2356 return R;
2357 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002358
Duncan Sandsa7724332011-02-17 07:46:37 +00002359 // Special logic for binary operators.
2360 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2361 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2362 if (BO0 || BO1) {
2363 CmpInst::Predicate Pred = I.getPredicate();
2364 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2365 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2366 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2367 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2368 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2369 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2370 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2371 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2372 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2373
2374 // Analyze the case when either Op0 or Op1 is an add instruction.
2375 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2376 Value *A = 0, *B = 0, *C = 0, *D = 0;
2377 if (BO0 && BO0->getOpcode() == Instruction::Add)
2378 A = BO0->getOperand(0), B = BO0->getOperand(1);
2379 if (BO1 && BO1->getOpcode() == Instruction::Add)
2380 C = BO1->getOperand(0), D = BO1->getOperand(1);
2381
2382 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2383 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2384 return new ICmpInst(Pred, A == Op1 ? B : A,
2385 Constant::getNullValue(Op1->getType()));
2386
2387 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2388 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2389 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2390 C == Op0 ? D : C);
2391
Duncan Sands39a7de72011-02-18 16:25:37 +00002392 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002393 if (A && C && (A == C || A == D || B == C || B == D) &&
2394 NoOp0WrapProblem && NoOp1WrapProblem &&
2395 // Try not to increase register pressure.
2396 BO0->hasOneUse() && BO1->hasOneUse()) {
2397 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsafe45392012-11-16 18:55:49 +00002398 Value *Y, *Z;
2399 if (A == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002400 // C + B == C + D -> B == D
Duncan Sandsafe45392012-11-16 18:55:49 +00002401 Y = B;
2402 Z = D;
2403 } else if (A == D) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002404 // D + B == C + D -> B == C
Duncan Sandsafe45392012-11-16 18:55:49 +00002405 Y = B;
2406 Z = C;
2407 } else if (B == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002408 // A + C == C + D -> A == D
Duncan Sandsafe45392012-11-16 18:55:49 +00002409 Y = A;
2410 Z = D;
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002411 } else {
2412 assert(B == D);
2413 // A + D == C + D -> A == C
Duncan Sandsafe45392012-11-16 18:55:49 +00002414 Y = A;
2415 Z = C;
2416 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002417 return new ICmpInst(Pred, Y, Z);
2418 }
2419
2420 // Analyze the case when either Op0 or Op1 is a sub instruction.
2421 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2422 A = 0; B = 0; C = 0; D = 0;
2423 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2424 A = BO0->getOperand(0), B = BO0->getOperand(1);
2425 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2426 C = BO1->getOperand(0), D = BO1->getOperand(1);
2427
Duncan Sands39a7de72011-02-18 16:25:37 +00002428 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2429 if (A == Op1 && NoOp0WrapProblem)
2430 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2431
2432 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2433 if (C == Op0 && NoOp1WrapProblem)
2434 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2435
2436 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002437 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2438 // Try not to increase register pressure.
2439 BO0->hasOneUse() && BO1->hasOneUse())
2440 return new ICmpInst(Pred, A, C);
2441
Duncan Sands39a7de72011-02-18 16:25:37 +00002442 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2443 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2444 // Try not to increase register pressure.
2445 BO0->hasOneUse() && BO1->hasOneUse())
2446 return new ICmpInst(Pred, D, B);
2447
Nick Lewycky9feda172011-03-05 04:28:48 +00002448 BinaryOperator *SRem = NULL;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002449 // icmp (srem X, Y), Y
Nick Lewycky9feda172011-03-05 04:28:48 +00002450 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2451 Op1 == BO0->getOperand(1))
2452 SRem = BO0;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002453 // icmp Y, (srem X, Y)
Nick Lewycky9feda172011-03-05 04:28:48 +00002454 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2455 Op0 == BO1->getOperand(1))
2456 SRem = BO1;
2457 if (SRem) {
2458 // We don't check hasOneUse to avoid increasing register pressure because
2459 // the value we use is the same value this instruction was already using.
2460 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2461 default: break;
2462 case ICmpInst::ICMP_EQ:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002463 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002464 case ICmpInst::ICMP_NE:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002465 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002466 case ICmpInst::ICMP_SGT:
2467 case ICmpInst::ICMP_SGE:
2468 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2469 Constant::getAllOnesValue(SRem->getType()));
2470 case ICmpInst::ICMP_SLT:
2471 case ICmpInst::ICMP_SLE:
2472 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2473 Constant::getNullValue(SRem->getType()));
2474 }
2475 }
2476
Duncan Sandsa7724332011-02-17 07:46:37 +00002477 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2478 BO0->hasOneUse() && BO1->hasOneUse() &&
2479 BO0->getOperand(1) == BO1->getOperand(1)) {
2480 switch (BO0->getOpcode()) {
2481 default: break;
2482 case Instruction::Add:
2483 case Instruction::Sub:
2484 case Instruction::Xor:
2485 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2486 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2487 BO1->getOperand(0));
2488 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2489 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2490 if (CI->getValue().isSignBit()) {
2491 ICmpInst::Predicate Pred = I.isSigned()
2492 ? I.getUnsignedPredicate()
2493 : I.getSignedPredicate();
2494 return new ICmpInst(Pred, BO0->getOperand(0),
2495 BO1->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00002496 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002497
Chris Lattnerc73b24d2011-07-15 06:08:15 +00002498 if (CI->isMaxValue(true)) {
Duncan Sandsa7724332011-02-17 07:46:37 +00002499 ICmpInst::Predicate Pred = I.isSigned()
2500 ? I.getUnsignedPredicate()
2501 : I.getSignedPredicate();
2502 Pred = I.getSwappedPredicate(Pred);
2503 return new ICmpInst(Pred, BO0->getOperand(0),
2504 BO1->getOperand(0));
2505 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002506 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002507 break;
2508 case Instruction::Mul:
2509 if (!I.isEquality())
2510 break;
2511
2512 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2513 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2514 // Mask = -1 >> count-trailing-zeros(Cst).
2515 if (!CI->isZero() && !CI->isOne()) {
2516 const APInt &AP = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002517 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandsa7724332011-02-17 07:46:37 +00002518 APInt::getLowBitsSet(AP.getBitWidth(),
2519 AP.getBitWidth() -
2520 AP.countTrailingZeros()));
2521 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2522 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2523 return new ICmpInst(I.getPredicate(), And1, And2);
2524 }
2525 }
2526 break;
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002527 case Instruction::UDiv:
2528 case Instruction::LShr:
2529 if (I.isSigned())
2530 break;
2531 // fall-through
2532 case Instruction::SDiv:
2533 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002534 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002535 break;
2536 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2537 BO1->getOperand(0));
2538 case Instruction::Shl: {
2539 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2540 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2541 if (!NUW && !NSW)
2542 break;
2543 if (!NSW && I.isSigned())
2544 break;
2545 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2546 BO1->getOperand(0));
2547 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002548 }
2549 }
2550 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002551
Chris Lattner02446fc2010-01-04 07:37:31 +00002552 { Value *A, *B;
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002553 // ~x < ~y --> y < x
2554 // ~x < cst --> ~cst < x
2555 if (match(Op0, m_Not(m_Value(A)))) {
2556 if (match(Op1, m_Not(m_Value(B))))
2557 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner27a98482011-01-15 05:42:47 +00002558 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002559 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2560 }
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002561
2562 // (a+b) <u a --> llvm.uadd.with.overflow.
2563 // (a+b) <u b --> llvm.uadd.with.overflow.
2564 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002565 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002566 (Op1 == A || Op1 == B))
2567 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2568 return R;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002569
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002570 // a >u (a+b) --> llvm.uadd.with.overflow.
2571 // b >u (a+b) --> llvm.uadd.with.overflow.
2572 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2573 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2574 (Op0 == A || Op0 == B))
2575 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2576 return R;
Chris Lattner02446fc2010-01-04 07:37:31 +00002577 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002578
Chris Lattner02446fc2010-01-04 07:37:31 +00002579 if (I.isEquality()) {
2580 Value *A, *B, *C, *D;
Duncan Sands39a7de72011-02-18 16:25:37 +00002581
Chris Lattner02446fc2010-01-04 07:37:31 +00002582 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2583 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2584 Value *OtherVal = A == Op1 ? B : A;
2585 return new ICmpInst(I.getPredicate(), OtherVal,
2586 Constant::getNullValue(A->getType()));
2587 }
2588
2589 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2590 // A^c1 == C^c2 --> A == C^(c1^c2)
2591 ConstantInt *C1, *C2;
2592 if (match(B, m_ConstantInt(C1)) &&
2593 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2594 Constant *NC = ConstantInt::get(I.getContext(),
2595 C1->getValue() ^ C2->getValue());
Benjamin Kramera9390a42011-09-27 20:39:19 +00002596 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner02446fc2010-01-04 07:37:31 +00002597 return new ICmpInst(I.getPredicate(), A, Xor);
2598 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002599
Chris Lattner02446fc2010-01-04 07:37:31 +00002600 // A^B == A^D -> B == D
2601 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2602 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2603 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2604 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2605 }
2606 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002607
Chris Lattner02446fc2010-01-04 07:37:31 +00002608 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2609 (A == Op0 || B == Op0)) {
2610 // A == (A^B) -> B == 0
2611 Value *OtherVal = A == Op0 ? B : A;
2612 return new ICmpInst(I.getPredicate(), OtherVal,
2613 Constant::getNullValue(A->getType()));
2614 }
2615
Chris Lattner02446fc2010-01-04 07:37:31 +00002616 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002617 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner5036ce42011-04-26 20:02:45 +00002618 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002619 Value *X = 0, *Y = 0, *Z = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002620
Chris Lattner02446fc2010-01-04 07:37:31 +00002621 if (A == C) {
2622 X = B; Y = D; Z = A;
2623 } else if (A == D) {
2624 X = B; Y = C; Z = A;
2625 } else if (B == C) {
2626 X = A; Y = D; Z = B;
2627 } else if (B == D) {
2628 X = A; Y = C; Z = B;
2629 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002630
Chris Lattner02446fc2010-01-04 07:37:31 +00002631 if (X) { // Build (X^Y) & Z
Benjamin Kramera9390a42011-09-27 20:39:19 +00002632 Op1 = Builder->CreateXor(X, Y);
2633 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner02446fc2010-01-04 07:37:31 +00002634 I.setOperand(0, Op1);
2635 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2636 return &I;
2637 }
2638 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002639
Benjamin Kramer66821d92012-06-10 20:35:00 +00002640 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002641 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer66821d92012-06-10 20:35:00 +00002642 ConstantInt *Cst1;
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002643 if ((Op0->hasOneUse() &&
2644 match(Op0, m_ZExt(m_Value(A))) &&
2645 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2646 (Op1->hasOneUse() &&
2647 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2648 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer66821d92012-06-10 20:35:00 +00002649 APInt Pow2 = Cst1->getValue() + 1;
2650 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2651 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2652 return new ICmpInst(I.getPredicate(), A,
2653 Builder->CreateTrunc(B, A->getType()));
2654 }
2655
Chris Lattner325eeb12011-04-26 20:18:20 +00002656 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2657 // "icmp (and X, mask), cst"
2658 uint64_t ShAmt = 0;
Chris Lattner325eeb12011-04-26 20:18:20 +00002659 if (Op0->hasOneUse() &&
2660 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2661 m_ConstantInt(ShAmt))))) &&
2662 match(Op1, m_ConstantInt(Cst1)) &&
2663 // Only do this when A has multiple uses. This is most important to do
2664 // when it exposes other optimizations.
2665 !A->hasOneUse()) {
2666 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002667
Chris Lattner325eeb12011-04-26 20:18:20 +00002668 if (ShAmt < ASize) {
2669 APInt MaskV =
2670 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2671 MaskV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002672
Chris Lattner325eeb12011-04-26 20:18:20 +00002673 APInt CmpV = Cst1->getValue().zext(ASize);
2674 CmpV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002675
Chris Lattner325eeb12011-04-26 20:18:20 +00002676 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2677 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2678 }
2679 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002680 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002681
Chris Lattner02446fc2010-01-04 07:37:31 +00002682 {
2683 Value *X; ConstantInt *Cst;
2684 // icmp X+Cst, X
2685 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2686 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2687
2688 // icmp X, X+Cst
2689 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2690 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2691 }
2692 return Changed ? &I : 0;
2693}
2694
2695
2696
2697
2698
2699
2700/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2701///
2702Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2703 Instruction *LHSI,
2704 Constant *RHSC) {
2705 if (!isa<ConstantFP>(RHSC)) return 0;
2706 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002707
Chris Lattner02446fc2010-01-04 07:37:31 +00002708 // Get the width of the mantissa. We don't want to hack on conversions that
2709 // might lose information from the integer, e.g. "i64 -> float"
2710 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2711 if (MantissaWidth == -1) return 0; // Unknown.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002712
Chris Lattner02446fc2010-01-04 07:37:31 +00002713 // Check to see that the input is converted from an integer type that is small
2714 // enough that preserves all bits. TODO: check here for "known" sign bits.
2715 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2716 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002717
Chris Lattner02446fc2010-01-04 07:37:31 +00002718 // If this is a uitofp instruction, we need an extra bit to hold the sign.
2719 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2720 if (LHSUnsigned)
2721 ++InputSize;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002722
Chris Lattner02446fc2010-01-04 07:37:31 +00002723 // If the conversion would lose info, don't hack on this.
2724 if ((int)InputSize > MantissaWidth)
2725 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002726
Chris Lattner02446fc2010-01-04 07:37:31 +00002727 // Otherwise, we can potentially simplify the comparison. We know that it
2728 // will always come through as an integer value and we know the constant is
2729 // not a NAN (it would have been previously simplified).
2730 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002731
Chris Lattner02446fc2010-01-04 07:37:31 +00002732 ICmpInst::Predicate Pred;
2733 switch (I.getPredicate()) {
2734 default: llvm_unreachable("Unexpected predicate!");
2735 case FCmpInst::FCMP_UEQ:
2736 case FCmpInst::FCMP_OEQ:
2737 Pred = ICmpInst::ICMP_EQ;
2738 break;
2739 case FCmpInst::FCMP_UGT:
2740 case FCmpInst::FCMP_OGT:
2741 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2742 break;
2743 case FCmpInst::FCMP_UGE:
2744 case FCmpInst::FCMP_OGE:
2745 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2746 break;
2747 case FCmpInst::FCMP_ULT:
2748 case FCmpInst::FCMP_OLT:
2749 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2750 break;
2751 case FCmpInst::FCMP_ULE:
2752 case FCmpInst::FCMP_OLE:
2753 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
2754 break;
2755 case FCmpInst::FCMP_UNE:
2756 case FCmpInst::FCMP_ONE:
2757 Pred = ICmpInst::ICMP_NE;
2758 break;
2759 case FCmpInst::FCMP_ORD:
2760 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2761 case FCmpInst::FCMP_UNO:
2762 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2763 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002764
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002765 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002766
Chris Lattner02446fc2010-01-04 07:37:31 +00002767 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002768
Chris Lattner02446fc2010-01-04 07:37:31 +00002769 // See if the FP constant is too large for the integer. For example,
2770 // comparing an i8 to 300.0.
2771 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002772
Chris Lattner02446fc2010-01-04 07:37:31 +00002773 if (!LHSUnsigned) {
2774 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
2775 // and large values.
2776 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
2777 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
2778 APFloat::rmNearestTiesToEven);
2779 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
2780 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
2781 Pred == ICmpInst::ICMP_SLE)
2782 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2783 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2784 }
2785 } else {
2786 // If the RHS value is > UnsignedMax, fold the comparison. This handles
2787 // +INF and large values.
2788 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
2789 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
2790 APFloat::rmNearestTiesToEven);
2791 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
2792 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
2793 Pred == ICmpInst::ICMP_ULE)
2794 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2795 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2796 }
2797 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002798
Chris Lattner02446fc2010-01-04 07:37:31 +00002799 if (!LHSUnsigned) {
2800 // See if the RHS value is < SignedMin.
2801 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2802 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
2803 APFloat::rmNearestTiesToEven);
2804 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
2805 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
2806 Pred == ICmpInst::ICMP_SGE)
2807 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2808 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2809 }
Devang Patela2e0f6b2012-02-13 23:05:18 +00002810 } else {
2811 // See if the RHS value is < UnsignedMin.
2812 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
2813 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
2814 APFloat::rmNearestTiesToEven);
2815 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
2816 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
2817 Pred == ICmpInst::ICMP_UGE)
2818 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2819 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2820 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002821 }
2822
2823 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
2824 // [0, UMAX], but it may still be fractional. See if it is fractional by
2825 // casting the FP value to the integer value and back, checking for equality.
2826 // Don't do this for zero, because -0.0 is not fractional.
2827 Constant *RHSInt = LHSUnsigned
2828 ? ConstantExpr::getFPToUI(RHSC, IntTy)
2829 : ConstantExpr::getFPToSI(RHSC, IntTy);
2830 if (!RHS.isZero()) {
2831 bool Equal = LHSUnsigned
2832 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
2833 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
2834 if (!Equal) {
2835 // If we had a comparison against a fractional value, we have to adjust
2836 // the compare predicate and sometimes the value. RHSC is rounded towards
2837 // zero at this point.
2838 switch (Pred) {
2839 default: llvm_unreachable("Unexpected integer comparison!");
2840 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
2841 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2842 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
2843 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2844 case ICmpInst::ICMP_ULE:
2845 // (float)int <= 4.4 --> int <= 4
2846 // (float)int <= -4.4 --> false
2847 if (RHS.isNegative())
2848 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2849 break;
2850 case ICmpInst::ICMP_SLE:
2851 // (float)int <= 4.4 --> int <= 4
2852 // (float)int <= -4.4 --> int < -4
2853 if (RHS.isNegative())
2854 Pred = ICmpInst::ICMP_SLT;
2855 break;
2856 case ICmpInst::ICMP_ULT:
2857 // (float)int < -4.4 --> false
2858 // (float)int < 4.4 --> int <= 4
2859 if (RHS.isNegative())
2860 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
2861 Pred = ICmpInst::ICMP_ULE;
2862 break;
2863 case ICmpInst::ICMP_SLT:
2864 // (float)int < -4.4 --> int < -4
2865 // (float)int < 4.4 --> int <= 4
2866 if (!RHS.isNegative())
2867 Pred = ICmpInst::ICMP_SLE;
2868 break;
2869 case ICmpInst::ICMP_UGT:
2870 // (float)int > 4.4 --> int > 4
2871 // (float)int > -4.4 --> true
2872 if (RHS.isNegative())
2873 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2874 break;
2875 case ICmpInst::ICMP_SGT:
2876 // (float)int > 4.4 --> int > 4
2877 // (float)int > -4.4 --> int >= -4
2878 if (RHS.isNegative())
2879 Pred = ICmpInst::ICMP_SGE;
2880 break;
2881 case ICmpInst::ICMP_UGE:
2882 // (float)int >= -4.4 --> true
2883 // (float)int >= 4.4 --> int > 4
Bob Wilsonf12c95a2012-08-07 22:35:16 +00002884 if (RHS.isNegative())
Chris Lattner02446fc2010-01-04 07:37:31 +00002885 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
2886 Pred = ICmpInst::ICMP_UGT;
2887 break;
2888 case ICmpInst::ICMP_SGE:
2889 // (float)int >= -4.4 --> int >= -4
2890 // (float)int >= 4.4 --> int > 4
2891 if (!RHS.isNegative())
2892 Pred = ICmpInst::ICMP_SGT;
2893 break;
2894 }
2895 }
2896 }
2897
2898 // Lower this FP comparison into an appropriate integer version of the
2899 // comparison.
2900 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
2901}
2902
2903Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
2904 bool Changed = false;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002905
Chris Lattner02446fc2010-01-04 07:37:31 +00002906 /// Orders the operands of the compare so that they are listed from most
2907 /// complex to least complex. This puts constants before unary operators,
2908 /// before binary operators.
2909 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
2910 I.swapOperands();
2911 Changed = true;
2912 }
2913
2914 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002915
Chris Lattner02446fc2010-01-04 07:37:31 +00002916 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
2917 return ReplaceInstUsesWith(I, V);
2918
2919 // Simplify 'fcmp pred X, X'
2920 if (Op0 == Op1) {
2921 switch (I.getPredicate()) {
2922 default: llvm_unreachable("Unknown predicate!");
2923 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
2924 case FCmpInst::FCMP_ULT: // True if unordered or less than
2925 case FCmpInst::FCMP_UGT: // True if unordered or greater than
2926 case FCmpInst::FCMP_UNE: // True if unordered or not equal
2927 // Canonicalize these to be 'fcmp uno %X, 0.0'.
2928 I.setPredicate(FCmpInst::FCMP_UNO);
2929 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2930 return &I;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002931
Chris Lattner02446fc2010-01-04 07:37:31 +00002932 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
2933 case FCmpInst::FCMP_OEQ: // True if ordered and equal
2934 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
2935 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
2936 // Canonicalize these to be 'fcmp ord %X, 0.0'.
2937 I.setPredicate(FCmpInst::FCMP_ORD);
2938 I.setOperand(1, Constant::getNullValue(Op0->getType()));
2939 return &I;
2940 }
2941 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002942
Chris Lattner02446fc2010-01-04 07:37:31 +00002943 // Handle fcmp with constant RHS
2944 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2945 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2946 switch (LHSI->getOpcode()) {
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002947 case Instruction::FPExt: {
2948 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
2949 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
2950 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
2951 if (!RHSF)
2952 break;
2953
2954 const fltSemantics *Sem;
2955 // FIXME: This shouldn't be here.
Dan Gohmance163392011-12-17 00:04:22 +00002956 if (LHSExt->getSrcTy()->isHalfTy())
2957 Sem = &APFloat::IEEEhalf;
2958 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002959 Sem = &APFloat::IEEEsingle;
2960 else if (LHSExt->getSrcTy()->isDoubleTy())
2961 Sem = &APFloat::IEEEdouble;
2962 else if (LHSExt->getSrcTy()->isFP128Ty())
2963 Sem = &APFloat::IEEEquad;
2964 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
2965 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand3467b9f2012-10-30 12:33:18 +00002966 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
2967 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002968 else
2969 break;
2970
2971 bool Lossy;
2972 APFloat F = RHSF->getValueAPF();
2973 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
2974
Jim Grosbachcbf676b2011-09-30 18:45:50 +00002975 // Avoid lossy conversions and denormals. Zero is a special case
2976 // that's OK to convert.
Jim Grosbach68e05fb2011-09-30 19:58:46 +00002977 APFloat Fabs = F;
2978 Fabs.clearSign();
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002979 if (!Lossy &&
Jim Grosbach68e05fb2011-09-30 19:58:46 +00002980 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
2981 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbachcbf676b2011-09-30 18:45:50 +00002982
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00002983 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
2984 ConstantFP::get(RHSC->getContext(), F));
2985 break;
2986 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002987 case Instruction::PHI:
2988 // Only fold fcmp into the PHI if the phi and fcmp are in the same
2989 // block. If in the same block, we're encouraging jump threading. If
2990 // not, we are just pessimizing the code by making an i1 phi.
2991 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002992 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002993 return NV;
2994 break;
2995 case Instruction::SIToFP:
2996 case Instruction::UIToFP:
2997 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
2998 return NV;
2999 break;
3000 case Instruction::Select: {
3001 // If either operand of the select is a constant, we can fold the
3002 // comparison into the select arms, which will cause one to be
3003 // constant folded and the select turned into a bitwise or.
3004 Value *Op1 = 0, *Op2 = 0;
3005 if (LHSI->hasOneUse()) {
3006 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3007 // Fold the known value into the constant operand.
3008 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3009 // Insert a new FCmp of the other select operand.
3010 Op2 = Builder->CreateFCmp(I.getPredicate(),
3011 LHSI->getOperand(2), RHSC, I.getName());
3012 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3013 // Fold the known value into the constant operand.
3014 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3015 // Insert a new FCmp of the other select operand.
3016 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3017 RHSC, I.getName());
3018 }
3019 }
3020
3021 if (Op1)
3022 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3023 break;
3024 }
Benjamin Kramer0db50182011-03-31 10:12:15 +00003025 case Instruction::FSub: {
3026 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3027 Value *Op;
3028 if (match(LHSI, m_FNeg(m_Value(Op))))
3029 return new FCmpInst(I.getSwappedPredicate(), Op,
3030 ConstantExpr::getFNeg(RHSC));
3031 break;
3032 }
Dan Gohman39516a62010-02-24 06:46:09 +00003033 case Instruction::Load:
3034 if (GetElementPtrInst *GEP =
3035 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3036 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3037 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3038 !cast<LoadInst>(LHSI)->isVolatile())
3039 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3040 return Res;
3041 }
3042 break;
Benjamin Kramer00abcd32012-08-18 20:06:47 +00003043 case Instruction::Call: {
3044 CallInst *CI = cast<CallInst>(LHSI);
3045 LibFunc::Func Func;
3046 // Various optimization for fabs compared with zero.
Benjamin Kramera4b57172012-08-18 22:04:34 +00003047 if (RHSC->isNullValue() && CI->getCalledFunction() &&
Benjamin Kramer00abcd32012-08-18 20:06:47 +00003048 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3049 TLI->has(Func)) {
3050 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3051 Func == LibFunc::fabsl) {
3052 switch (I.getPredicate()) {
3053 default: break;
3054 // fabs(x) < 0 --> false
3055 case FCmpInst::FCMP_OLT:
3056 return ReplaceInstUsesWith(I, Builder->getFalse());
3057 // fabs(x) > 0 --> x != 0
3058 case FCmpInst::FCMP_OGT:
3059 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3060 RHSC);
3061 // fabs(x) <= 0 --> x == 0
3062 case FCmpInst::FCMP_OLE:
3063 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3064 RHSC);
3065 // fabs(x) >= 0 --> !isnan(x)
3066 case FCmpInst::FCMP_OGE:
3067 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3068 RHSC);
3069 // fabs(x) == 0 --> x == 0
3070 // fabs(x) != 0 --> x != 0
3071 case FCmpInst::FCMP_OEQ:
3072 case FCmpInst::FCMP_UEQ:
3073 case FCmpInst::FCMP_ONE:
3074 case FCmpInst::FCMP_UNE:
3075 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3076 RHSC);
3077 }
3078 }
3079 }
3080 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003081 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003082 }
3083
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003084 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003085 Value *X, *Y;
3086 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003087 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003088
Benjamin Kramercd0274c2011-03-31 10:11:58 +00003089 // fcmp (fpext x), (fpext y) -> fcmp x, y
3090 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3091 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3092 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3093 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3094 RHSExt->getOperand(0));
3095
Chris Lattner02446fc2010-01-04 07:37:31 +00003096 return Changed ? &I : 0;
3097}