blob: 8ac0e3fd4704131e1496db63cc242d68dbf26e34 [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
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +0000142/// Returns true if the exploded icmp can be expressed as a signed comparison
143/// to zero and updates the predicate accordingly.
144/// The signedness of the comparison is preserved.
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000145static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
146 if (!ICmpInst::isSigned(pred))
147 return false;
148
149 if (RHS->isZero())
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +0000150 return ICmpInst::isRelational(pred);
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000151
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +0000152 if (RHS->isOne()) {
153 if (pred == ICmpInst::ICMP_SLT) {
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000154 pred = ICmpInst::ICMP_SLE;
155 return true;
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000156 }
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +0000157 } else if (RHS->isAllOnesValue()) {
158 if (pred == ICmpInst::ICMP_SGT) {
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000159 pred = ICmpInst::ICMP_SGE;
160 return true;
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000161 }
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +0000162 }
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +0000163
164 return false;
165}
166
Chris Lattner02446fc2010-01-04 07:37:31 +0000167// isHighOnes - Return true if the constant is of the form 1+0+.
168// This is the same as lowones(~X).
169static bool isHighOnes(const ConstantInt *CI) {
170 return (~CI->getValue() + 1).isPowerOf2();
171}
172
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000173/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner02446fc2010-01-04 07:37:31 +0000174/// set of known zero and one bits, compute the maximum and minimum values that
175/// could have the specified known zero and known one bits, returning them in
176/// min/max.
177static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
178 const APInt& KnownOne,
179 APInt& Min, APInt& Max) {
180 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
181 KnownZero.getBitWidth() == Min.getBitWidth() &&
182 KnownZero.getBitWidth() == Max.getBitWidth() &&
183 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
184 APInt UnknownBits = ~(KnownZero|KnownOne);
185
186 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
187 // bit if it is unknown.
188 Min = KnownOne;
189 Max = KnownOne|UnknownBits;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000190
Chris Lattner02446fc2010-01-04 07:37:31 +0000191 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad7a874dd2010-12-01 08:53:58 +0000192 Min.setBit(Min.getBitWidth()-1);
193 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner02446fc2010-01-04 07:37:31 +0000194 }
195}
196
197// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
198// a set of known zero and one bits, compute the maximum and minimum values that
199// could have the specified known zero and known one bits, returning them in
200// min/max.
201static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
202 const APInt &KnownOne,
203 APInt &Min, APInt &Max) {
204 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
205 KnownZero.getBitWidth() == Min.getBitWidth() &&
206 KnownZero.getBitWidth() == Max.getBitWidth() &&
207 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
208 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000209
Chris Lattner02446fc2010-01-04 07:37:31 +0000210 // The minimum value is when the unknown bits are all zeros.
211 Min = KnownOne;
212 // The maximum value is when the unknown bits are all ones.
213 Max = KnownOne|UnknownBits;
214}
215
216
217
218/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
219/// cmp pred (load (gep GV, ...)), cmpcst
220/// where GV is a global variable with a constant initializer. Try to simplify
221/// this into some simple computation that does not need the load. For example
222/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
223///
224/// If AndCst is non-null, then the loaded value is masked with that constant
225/// before doing the comparison. This handles cases like "A[i]&4 == 0".
226Instruction *InstCombiner::
227FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
228 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000229 // We need TD information to know the pointer size unless this is inbounds.
230 if (!GEP->isInBounds() && TD == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000231
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000232 Constant *Init = GV->getInitializer();
233 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
234 return 0;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000235
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000236 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
237 if (ArrayElementCount > 1024) return 0; // Don't blow up on huge arrays.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000238
Chris Lattner02446fc2010-01-04 07:37:31 +0000239 // There are many forms of this optimization we can handle, for now, just do
240 // the simple index into a single-dimensional array.
241 //
242 // Require: GEP GV, 0, i {{, constant indices}}
243 if (GEP->getNumOperands() < 3 ||
244 !isa<ConstantInt>(GEP->getOperand(1)) ||
245 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
246 isa<Constant>(GEP->getOperand(2)))
247 return 0;
248
249 // Check that indices after the variable are constants and in-range for the
250 // type they index. Collect the indices. This is typically for arrays of
251 // structs.
252 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000253
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000254 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner02446fc2010-01-04 07:37:31 +0000255 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
256 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
257 if (Idx == 0) return 0; // Variable index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000258
Chris Lattner02446fc2010-01-04 07:37:31 +0000259 uint64_t IdxVal = Idx->getZExtValue();
260 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000261
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000262 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner02446fc2010-01-04 07:37:31 +0000263 EltTy = STy->getElementType(IdxVal);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000264 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000265 if (IdxVal >= ATy->getNumElements()) return 0;
266 EltTy = ATy->getElementType();
267 } else {
268 return 0; // Unknown type.
269 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000270
Chris Lattner02446fc2010-01-04 07:37:31 +0000271 LaterIndices.push_back(IdxVal);
272 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000273
Chris Lattner02446fc2010-01-04 07:37:31 +0000274 enum { Overdefined = -3, Undefined = -2 };
275
276 // Variables for our state machines.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000277
Chris Lattner02446fc2010-01-04 07:37:31 +0000278 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
279 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
280 // and 87 is the second (and last) index. FirstTrueElement is -2 when
281 // undefined, otherwise set to the first true element. SecondTrueElement is
282 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
283 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
284
285 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
286 // form "i != 47 & i != 87". Same state transitions as for true elements.
287 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000288
Chris Lattner02446fc2010-01-04 07:37:31 +0000289 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
290 /// define a state machine that triggers for ranges of values that the index
291 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
292 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
293 /// index in the range (inclusive). We use -2 for undefined here because we
294 /// use relative comparisons and don't want 0-1 to match -1.
295 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000296
Chris Lattner02446fc2010-01-04 07:37:31 +0000297 // MagicBitvector - This is a magic bitvector where we set a bit if the
298 // comparison is true for element 'i'. If there are 64 elements or less in
299 // the array, this will fully represent all the comparison results.
300 uint64_t MagicBitvector = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000301
302
Chris Lattner02446fc2010-01-04 07:37:31 +0000303 // Scan the array and see if one of our patterns matches.
304 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerc8d75c72012-01-31 02:55:06 +0000305 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
306 Constant *Elt = Init->getAggregateElement(i);
307 if (Elt == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000308
Chris Lattner02446fc2010-01-04 07:37:31 +0000309 // If this is indexing an array of structures, get the structure element.
310 if (!LaterIndices.empty())
Jay Foadfc6d3a42011-07-13 10:26:04 +0000311 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000312
Chris Lattner02446fc2010-01-04 07:37:31 +0000313 // If the element is masked, handle it.
314 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000315
Chris Lattner02446fc2010-01-04 07:37:31 +0000316 // Find out if the comparison would be true or false for the i'th element.
317 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chad Rosieraab8e282011-12-02 01:26:24 +0000318 CompareRHS, TD, TLI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000319 // If the result is undef for this element, ignore it.
320 if (isa<UndefValue>(C)) {
321 // Extend range state machines to cover this element in case there is an
322 // undef in the middle of the range.
323 if (TrueRangeEnd == (int)i-1)
324 TrueRangeEnd = i;
325 if (FalseRangeEnd == (int)i-1)
326 FalseRangeEnd = i;
327 continue;
328 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000329
Chris Lattner02446fc2010-01-04 07:37:31 +0000330 // If we can't compute the result for any of the elements, we have to give
331 // up evaluating the entire conditional.
332 if (!isa<ConstantInt>(C)) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000333
Chris Lattner02446fc2010-01-04 07:37:31 +0000334 // Otherwise, we know if the comparison is true or false for this element,
335 // update our state machines.
336 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000337
Chris Lattner02446fc2010-01-04 07:37:31 +0000338 // State machine for single/double/range index comparison.
339 if (IsTrueForElt) {
340 // Update the TrueElement state machine.
341 if (FirstTrueElement == Undefined)
342 FirstTrueElement = TrueRangeEnd = i; // First true element.
343 else {
344 // Update double-compare state machine.
345 if (SecondTrueElement == Undefined)
346 SecondTrueElement = i;
347 else
348 SecondTrueElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000349
Chris Lattner02446fc2010-01-04 07:37:31 +0000350 // Update range state machine.
351 if (TrueRangeEnd == (int)i-1)
352 TrueRangeEnd = i;
353 else
354 TrueRangeEnd = Overdefined;
355 }
356 } else {
357 // Update the FalseElement state machine.
358 if (FirstFalseElement == Undefined)
359 FirstFalseElement = FalseRangeEnd = i; // First false element.
360 else {
361 // Update double-compare state machine.
362 if (SecondFalseElement == Undefined)
363 SecondFalseElement = i;
364 else
365 SecondFalseElement = Overdefined;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000366
Chris Lattner02446fc2010-01-04 07:37:31 +0000367 // Update range state machine.
368 if (FalseRangeEnd == (int)i-1)
369 FalseRangeEnd = i;
370 else
371 FalseRangeEnd = Overdefined;
372 }
373 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000374
375
Chris Lattner02446fc2010-01-04 07:37:31 +0000376 // If this element is in range, update our magic bitvector.
377 if (i < 64 && IsTrueForElt)
378 MagicBitvector |= 1ULL << i;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000379
Chris Lattner02446fc2010-01-04 07:37:31 +0000380 // If all of our states become overdefined, bail out early. Since the
381 // predicate is expensive, only check it every 8 elements. This is only
382 // really useful for really huge arrays.
383 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
384 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
385 FalseRangeEnd == Overdefined)
386 return 0;
387 }
388
389 // Now that we've scanned the entire array, emit our new comparison(s). We
390 // order the state machines in complexity of the generated code.
391 Value *Idx = GEP->getOperand(2);
392
Chris Lattnerd7f5a582010-01-04 18:57:15 +0000393 // If the index is larger than the pointer size of the target, truncate the
394 // index down like the GEP would do implicitly. We don't have to do this for
395 // an inbounds GEP because the index can't be out of range.
396 if (!GEP->isInBounds() &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000397 Idx->getType()->getPrimitiveSizeInBits() > TD->getPointerSizeInBits())
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000398 Idx = Builder->CreateTrunc(Idx, TD->getIntPtrType(Idx->getContext()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000399
Chris Lattner02446fc2010-01-04 07:37:31 +0000400 // If the comparison is only true for one or two elements, emit direct
401 // comparisons.
402 if (SecondTrueElement != Overdefined) {
403 // None true -> false.
404 if (FirstTrueElement == Undefined)
Jakub Staszak3facc432013-06-06 20:18:46 +0000405 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000406
Chris Lattner02446fc2010-01-04 07:37:31 +0000407 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000408
Chris Lattner02446fc2010-01-04 07:37:31 +0000409 // True for one element -> 'i == 47'.
410 if (SecondTrueElement == Undefined)
411 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000412
Chris Lattner02446fc2010-01-04 07:37:31 +0000413 // True for two elements -> 'i == 47 | i == 72'.
414 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
415 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
416 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
417 return BinaryOperator::CreateOr(C1, C2);
418 }
419
420 // If the comparison is only false for one or two elements, emit direct
421 // comparisons.
422 if (SecondFalseElement != Overdefined) {
423 // None false -> true.
424 if (FirstFalseElement == Undefined)
Jakub Staszak3facc432013-06-06 20:18:46 +0000425 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000426
Chris Lattner02446fc2010-01-04 07:37:31 +0000427 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
428
429 // False for one element -> 'i != 47'.
430 if (SecondFalseElement == Undefined)
431 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000432
Chris Lattner02446fc2010-01-04 07:37:31 +0000433 // False for two elements -> 'i != 47 & i != 72'.
434 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
435 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
436 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
437 return BinaryOperator::CreateAnd(C1, C2);
438 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000439
Chris Lattner02446fc2010-01-04 07:37:31 +0000440 // If the comparison can be replaced with a range comparison for the elements
441 // where it is true, emit the range check.
442 if (TrueRangeEnd != Overdefined) {
443 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000444
Chris Lattner02446fc2010-01-04 07:37:31 +0000445 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
446 if (FirstTrueElement) {
447 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
448 Idx = Builder->CreateAdd(Idx, Offs);
449 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000450
Chris Lattner02446fc2010-01-04 07:37:31 +0000451 Value *End = ConstantInt::get(Idx->getType(),
452 TrueRangeEnd-FirstTrueElement+1);
453 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
454 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000455
Chris Lattner02446fc2010-01-04 07:37:31 +0000456 // False range check.
457 if (FalseRangeEnd != Overdefined) {
458 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
459 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
460 if (FirstFalseElement) {
461 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
462 Idx = Builder->CreateAdd(Idx, Offs);
463 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000464
Chris Lattner02446fc2010-01-04 07:37:31 +0000465 Value *End = ConstantInt::get(Idx->getType(),
466 FalseRangeEnd-FirstFalseElement);
467 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
468 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000469
470
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000471 // If a magic bitvector captures the entire comparison state
Chris Lattner02446fc2010-01-04 07:37:31 +0000472 // of this load, replace it with computation that does:
473 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000474 {
475 Type *Ty = 0;
476
477 // Look for an appropriate type:
478 // - The type of Idx if the magic fits
479 // - The smallest fitting legal type if we have a DataLayout
480 // - Default to i32
481 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
482 Ty = Idx->getType();
483 else if (TD)
484 Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
485 else if (ArrayElementCount <= 32)
Chris Lattner02446fc2010-01-04 07:37:31 +0000486 Ty = Type::getInt32Ty(Init->getContext());
Arnaud A. de Grandmaison2be921a2013-03-22 08:25:01 +0000487
488 if (Ty != 0) {
489 Value *V = Builder->CreateIntCast(Idx, Ty, false);
490 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
491 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
492 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
493 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000494 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000495
Chris Lattner02446fc2010-01-04 07:37:31 +0000496 return 0;
497}
498
499
500/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
501/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
502/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
503/// be complex, and scales are involved. The above expression would also be
504/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
505/// This later form is less amenable to optimization though, and we are allowed
506/// to generate the first by knowing that pointer arithmetic doesn't overflow.
507///
508/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000509///
Eli Friedman107ffd52011-05-18 23:11:30 +0000510static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000511 DataLayout &TD = *IC.getDataLayout();
Chris Lattner02446fc2010-01-04 07:37:31 +0000512 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000513
Chris Lattner02446fc2010-01-04 07:37:31 +0000514 // Check to see if this gep only has a single variable index. If so, and if
515 // any constant indices are a multiple of its scale, then we can compute this
516 // in terms of the scale of the variable index. For example, if the GEP
517 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
518 // because the expression will cross zero at the same point.
519 unsigned i, e = GEP->getNumOperands();
520 int64_t Offset = 0;
521 for (i = 1; i != e; ++i, ++GTI) {
522 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
523 // Compute the aggregate offset of constant indices.
524 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000525
Chris Lattner02446fc2010-01-04 07:37:31 +0000526 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000527 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000528 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
529 } else {
530 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
531 Offset += Size*CI->getSExtValue();
532 }
533 } else {
534 // Found our variable index.
535 break;
536 }
537 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000538
Chris Lattner02446fc2010-01-04 07:37:31 +0000539 // If there are no variable indices, we must have a constant offset, just
540 // evaluate it the general way.
541 if (i == e) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000542
Chris Lattner02446fc2010-01-04 07:37:31 +0000543 Value *VariableIdx = GEP->getOperand(i);
544 // Determine the scale factor of the variable element. For example, this is
545 // 4 if the variable index is into an array of i32.
546 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000547
Chris Lattner02446fc2010-01-04 07:37:31 +0000548 // Verify that there are no other variable indices. If so, emit the hard way.
549 for (++i, ++GTI; i != e; ++i, ++GTI) {
550 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
551 if (!CI) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000552
Chris Lattner02446fc2010-01-04 07:37:31 +0000553 // Compute the aggregate offset of constant indices.
554 if (CI->isZero()) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000555
Chris Lattner02446fc2010-01-04 07:37:31 +0000556 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000557 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000558 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
559 } else {
560 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
561 Offset += Size*CI->getSExtValue();
562 }
563 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000564
Chris Lattner02446fc2010-01-04 07:37:31 +0000565 // Okay, we know we have a single variable index, which must be a
566 // pointer/array/vector index. If there is no offset, life is simple, return
567 // the index.
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000568 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattner02446fc2010-01-04 07:37:31 +0000569 if (Offset == 0) {
570 // Cast to intptrty in case a truncation occurs. If an extension is needed,
571 // we don't need to bother extending: the extension won't affect where the
572 // computation crosses zero.
Eli Friedman107ffd52011-05-18 23:11:30 +0000573 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000574 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Eli Friedman107ffd52011-05-18 23:11:30 +0000575 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
576 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000577 return VariableIdx;
578 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000579
Chris Lattner02446fc2010-01-04 07:37:31 +0000580 // Otherwise, there is an index. The computation we will do will be modulo
581 // the pointer size, so get it.
582 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000583
Chris Lattner02446fc2010-01-04 07:37:31 +0000584 Offset &= PtrSizeMask;
585 VariableScale &= PtrSizeMask;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000586
Chris Lattner02446fc2010-01-04 07:37:31 +0000587 // To do this transformation, any constant index must be a multiple of the
588 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
589 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
590 // multiple of the variable scale.
591 int64_t NewOffs = Offset / (int64_t)VariableScale;
592 if (Offset != NewOffs*(int64_t)VariableScale)
593 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000594
Chris Lattner02446fc2010-01-04 07:37:31 +0000595 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000596 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner02446fc2010-01-04 07:37:31 +0000597 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman107ffd52011-05-18 23:11:30 +0000598 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
599 true /*Signed*/);
Chris Lattner02446fc2010-01-04 07:37:31 +0000600 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman107ffd52011-05-18 23:11:30 +0000601 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner02446fc2010-01-04 07:37:31 +0000602}
603
604/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
605/// else. At this point we know that the GEP is on the LHS of the comparison.
606Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
607 ICmpInst::Predicate Cond,
608 Instruction &I) {
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000609 // Don't transform signed compares of GEPs into index compares. Even if the
610 // GEP is inbounds, the final add of the base pointer can have signed overflow
611 // and would change the result of the icmp.
612 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramera42d5c42012-02-21 13:40:06 +0000613 // the maximum signed value for the pointer type.
Benjamin Kramer8294eb52012-02-21 13:31:09 +0000614 if (ICmpInst::isSigned(Cond))
615 return 0;
616
Chris Lattner02446fc2010-01-04 07:37:31 +0000617 // Look through bitcasts.
618 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
619 RHS = BCI->getOperand(0);
620
621 Value *PtrBase = GEPLHS->getOperand(0);
622 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
623 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
624 // This transformation (ignoring the base and scales) is valid because we
625 // know pointers can't overflow since the gep is inbounds. See if we can
626 // output an optimized form.
Eli Friedman107ffd52011-05-18 23:11:30 +0000627 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000628
Chris Lattner02446fc2010-01-04 07:37:31 +0000629 // If not, synthesize the offset the hard way.
630 if (Offset == 0)
631 Offset = EmitGEPOffset(GEPLHS);
632 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
633 Constant::getNullValue(Offset->getType()));
634 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
635 // If the base pointers are different, but the indices are the same, just
636 // compare the base pointer.
637 if (PtrBase != GEPRHS->getOperand(0)) {
638 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
639 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
640 GEPRHS->getOperand(0)->getType();
641 if (IndicesTheSame)
642 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
643 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
644 IndicesTheSame = false;
645 break;
646 }
647
648 // If all indices are the same, just compare the base pointers.
649 if (IndicesTheSame)
David Majnemerc22a4ee2013-06-29 10:28:04 +0000650 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +0000651
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000652 // If we're comparing GEPs with two base pointers that only differ in type
653 // and both GEPs have only constant indices or just one use, then fold
654 // the compare with the adjusted indices.
Benjamin Kramer6ad48f42012-02-20 18:45:10 +0000655 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer9bb40852012-02-20 15:07:47 +0000656 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
657 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
658 PtrBase->stripPointerCasts() ==
659 GEPRHS->getOperand(0)->stripPointerCasts()) {
660 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
661 EmitGEPOffset(GEPLHS),
662 EmitGEPOffset(GEPRHS));
663 return ReplaceInstUsesWith(I, Cmp);
664 }
665
Chris Lattner02446fc2010-01-04 07:37:31 +0000666 // Otherwise, the base pointers are different and the indices are
667 // different, bail out.
668 return 0;
669 }
670
671 // If one of the GEPs has all zero indices, recurse.
672 bool AllZeros = true;
673 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
674 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
675 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
676 AllZeros = false;
677 break;
678 }
679 if (AllZeros)
680 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemerdf703252013-06-29 09:45:35 +0000681 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner02446fc2010-01-04 07:37:31 +0000682
683 // If the other GEP has all zero indices, recurse.
684 AllZeros = true;
685 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
686 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
687 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
688 AllZeros = false;
689 break;
690 }
691 if (AllZeros)
692 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
693
Stuart Hastings67f071e2011-05-14 05:55:10 +0000694 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner02446fc2010-01-04 07:37:31 +0000695 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
696 // If the GEPs only differ by one index, compare it.
697 unsigned NumDifferences = 0; // Keep track of # differences.
698 unsigned DiffOperand = 0; // The operand that differs.
699 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
700 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
701 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
702 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
703 // Irreconcilable differences.
704 NumDifferences = 2;
705 break;
706 } else {
707 if (NumDifferences++) break;
708 DiffOperand = i;
709 }
710 }
711
Rafael Espindola7de80e02013-06-06 17:03:05 +0000712 if (NumDifferences == 0) // SAME GEP?
713 return ReplaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszak3facc432013-06-06 20:18:46 +0000714 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner02446fc2010-01-04 07:37:31 +0000715
Stuart Hastings67f071e2011-05-14 05:55:10 +0000716 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000717 Value *LHSV = GEPLHS->getOperand(DiffOperand);
718 Value *RHSV = GEPRHS->getOperand(DiffOperand);
719 // Make sure we do a signed comparison here.
720 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
721 }
722 }
723
724 // Only lower this if the icmp is the only user of the GEP or if we expect
725 // the result to fold to a constant!
726 if (TD &&
Stuart Hastings67f071e2011-05-14 05:55:10 +0000727 GEPsInBounds &&
Chris Lattner02446fc2010-01-04 07:37:31 +0000728 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
729 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
730 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
731 Value *L = EmitGEPOffset(GEPLHS);
732 Value *R = EmitGEPOffset(GEPRHS);
733 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
734 }
735 }
736 return 0;
737}
738
739/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
740Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
741 Value *X, ConstantInt *CI,
742 ICmpInst::Predicate Pred,
743 Value *TheAdd) {
744 // If we have X+0, exit early (simplifying logic below) and let it get folded
745 // elsewhere. icmp X+0, X -> icmp X, X
746 if (CI->isZero()) {
747 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
748 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
749 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000750
Chris Lattner02446fc2010-01-04 07:37:31 +0000751 // (X+4) == X -> false.
752 if (Pred == ICmpInst::ICMP_EQ)
Jakub Staszak3facc432013-06-06 20:18:46 +0000753 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +0000754
755 // (X+4) != X -> true.
756 if (Pred == ICmpInst::ICMP_NE)
Jakub Staszak3facc432013-06-06 20:18:46 +0000757 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +0000758
Chris Lattner02446fc2010-01-04 07:37:31 +0000759 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000760 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner02446fc2010-01-04 07:37:31 +0000761 // operators.
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000762
Chris Lattner9aa1e242010-01-08 17:48:19 +0000763 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner02446fc2010-01-04 07:37:31 +0000764 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
765 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
766 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000767 Value *R =
Chris Lattner9aa1e242010-01-08 17:48:19 +0000768 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner02446fc2010-01-04 07:37:31 +0000769 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
770 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000771
Chris Lattner02446fc2010-01-04 07:37:31 +0000772 // (X+1) >u X --> X <u (0-1) --> X != 255
773 // (X+2) >u X --> X <u (0-2) --> X <u 254
774 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandsa7724332011-02-17 07:46:37 +0000775 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000776 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000777
Chris Lattner02446fc2010-01-04 07:37:31 +0000778 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
779 ConstantInt *SMax = ConstantInt::get(X->getContext(),
780 APInt::getSignedMaxValue(BitWidth));
781
782 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
783 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
784 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
785 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
786 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
787 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandsa7724332011-02-17 07:46:37 +0000788 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner02446fc2010-01-04 07:37:31 +0000789 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000790
Chris Lattner02446fc2010-01-04 07:37:31 +0000791 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
792 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
793 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
794 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
795 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
796 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000797
Chris Lattner02446fc2010-01-04 07:37:31 +0000798 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszak3facc432013-06-06 20:18:46 +0000799 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner02446fc2010-01-04 07:37:31 +0000800 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
801}
802
803/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
804/// and CmpRHS are both known to be integer constants.
805Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
806 ConstantInt *DivRHS) {
807 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
808 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000809
810 // FIXME: If the operand types don't match the type of the divide
Chris Lattner02446fc2010-01-04 07:37:31 +0000811 // then don't attempt this transform. The code below doesn't have the
812 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000813 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner02446fc2010-01-04 07:37:31 +0000814 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000815 // (x /u C1) <u C2. Simply casting the operands and result won't
816 // work. :( The if statement below tests that condition and bails
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000817 // if it finds it.
Chris Lattner02446fc2010-01-04 07:37:31 +0000818 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
819 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
820 return 0;
821 if (DivRHS->isZero())
822 return 0; // The ProdOV computation fails on divide by zero.
823 if (DivIsSigned && DivRHS->isAllOnesValue())
824 return 0; // The overflow computation also screws up here
Chris Lattnerbb75d332011-02-13 08:07:21 +0000825 if (DivRHS->isOne()) {
826 // This eliminates some funny cases with INT_MIN.
827 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
828 return &ICI;
829 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000830
831 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000832 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
833 // C2 (CI). By solving for X we can turn this into a range check
834 // instead of computing a divide.
Chris Lattner02446fc2010-01-04 07:37:31 +0000835 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
836
837 // Determine if the product overflows by seeing if the product is
838 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000839 // as in the LHS instruction that we're folding.
Chris Lattner02446fc2010-01-04 07:37:31 +0000840 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
841 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
842
843 // Get the ICmp opcode
844 ICmpInst::Predicate Pred = ICI.getPredicate();
845
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000846 /// If the division is known to be exact, then there is no remainder from the
847 /// divide, so the covered range size is unit, otherwise it is the divisor.
848 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000849
Chris Lattner02446fc2010-01-04 07:37:31 +0000850 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000851 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner02446fc2010-01-04 07:37:31 +0000852 // Compute this interval based on the constants involved and the signedness of
853 // the compare/divide. This computes a half-open interval, keeping track of
854 // whether either value in the interval overflows. After analysis each
855 // overflow variable is set to 0 if it's corresponding bound variable is valid
856 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
857 int LoOverflow = 0, HiOverflow = 0;
858 Constant *LoBound = 0, *HiBound = 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000859
Chris Lattner02446fc2010-01-04 07:37:31 +0000860 if (!DivIsSigned) { // udiv
861 // e.g. X/5 op 3 --> [15, 20)
862 LoBound = Prod;
863 HiOverflow = LoOverflow = ProdOV;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000864 if (!HiOverflow) {
865 // If this is not an exact divide, then many values in the range collapse
866 // to the same result value.
867 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
868 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000869
Chris Lattner02446fc2010-01-04 07:37:31 +0000870 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
871 if (CmpRHSV == 0) { // (X / pos) op 0
872 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000873 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
874 HiBound = RangeSize;
Chris Lattner02446fc2010-01-04 07:37:31 +0000875 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
876 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
877 HiOverflow = LoOverflow = ProdOV;
878 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000879 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000880 } else { // (X / pos) op neg
881 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
882 HiBound = AddOne(Prod);
883 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
884 if (!LoOverflow) {
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000885 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000886 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000887 }
Chris Lattner02446fc2010-01-04 07:37:31 +0000888 }
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000889 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000890 if (DivI->isExact())
891 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000892 if (CmpRHSV == 0) { // (X / neg) op 0
893 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000894 LoBound = AddOne(RangeSize);
895 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner02446fc2010-01-04 07:37:31 +0000896 if (HiBound == DivRHS) { // -INTMIN = INTMIN
897 HiOverflow = 1; // [INTMIN+1, overflow)
898 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
899 }
900 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
901 // e.g. X/-5 op 3 --> [-19, -14)
902 HiBound = AddOne(Prod);
903 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
904 if (!LoOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000905 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner02446fc2010-01-04 07:37:31 +0000906 } else { // (X / neg) op neg
907 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
908 LoOverflow = HiOverflow = ProdOV;
909 if (!HiOverflow)
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000910 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner02446fc2010-01-04 07:37:31 +0000911 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000912
Chris Lattner02446fc2010-01-04 07:37:31 +0000913 // Dividing by a negative swaps the condition. LT <-> GT
914 Pred = ICmpInst::getSwappedPredicate(Pred);
915 }
916
917 Value *X = DivI->getOperand(0);
918 switch (Pred) {
919 default: llvm_unreachable("Unhandled icmp opcode!");
920 case ICmpInst::ICMP_EQ:
921 if (LoOverflow && HiOverflow)
Jakub Staszak3facc432013-06-06 20:18:46 +0000922 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000923 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000924 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
925 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000926 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000927 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
928 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000929 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
930 DivIsSigned, true));
Chris Lattner02446fc2010-01-04 07:37:31 +0000931 case ICmpInst::ICMP_NE:
932 if (LoOverflow && HiOverflow)
Jakub Staszak3facc432013-06-06 20:18:46 +0000933 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000934 if (HiOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000935 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
936 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000937 if (LoOverflow)
Chris Lattner02446fc2010-01-04 07:37:31 +0000938 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
939 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000940 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
941 DivIsSigned, false));
Chris Lattner02446fc2010-01-04 07:37:31 +0000942 case ICmpInst::ICMP_ULT:
943 case ICmpInst::ICMP_SLT:
944 if (LoOverflow == +1) // Low bound is greater than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000945 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +0000946 if (LoOverflow == -1) // Low bound is less than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000947 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +0000948 return new ICmpInst(Pred, X, LoBound);
949 case ICmpInst::ICMP_UGT:
950 case ICmpInst::ICMP_SGT:
951 if (HiOverflow == +1) // High bound greater than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000952 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000953 if (HiOverflow == -1) // High bound less than input range.
Jakub Staszak3facc432013-06-06 20:18:46 +0000954 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +0000955 if (Pred == ICmpInst::ICMP_UGT)
956 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattnerb20c0b52011-02-10 05:23:05 +0000957 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner02446fc2010-01-04 07:37:31 +0000958 }
959}
960
Chris Lattner74542aa2011-02-13 07:43:07 +0000961/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
962Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
963 ConstantInt *ShAmt) {
Chris Lattner74542aa2011-02-13 07:43:07 +0000964 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000965
Chris Lattner74542aa2011-02-13 07:43:07 +0000966 // Check that the shift amount is in range. If not, don't perform
967 // undefined shifts. When the shift is visited it will be
968 // simplified.
969 uint32_t TypeBits = CmpRHSV.getBitWidth();
970 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnerbb75d332011-02-13 08:07:21 +0000971 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Chris Lattner74542aa2011-02-13 07:43:07 +0000972 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000973
Chris Lattnerbb75d332011-02-13 08:07:21 +0000974 if (!ICI.isEquality()) {
975 // If we have an unsigned comparison and an ashr, we can't simplify this.
976 // Similarly for signed comparisons with lshr.
977 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
978 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000979
Eli Friedmana831a9b2011-05-25 23:26:20 +0000980 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
981 // by a power of 2. Since we already have logic to simplify these,
982 // transform to div and then simplify the resultant comparison.
Chris Lattnerbb75d332011-02-13 08:07:21 +0000983 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedmana831a9b2011-05-25 23:26:20 +0000984 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Chris Lattnerbb75d332011-02-13 08:07:21 +0000985 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000986
Chris Lattnerbb75d332011-02-13 08:07:21 +0000987 // Revisit the shift (to delete it).
988 Worklist.Add(Shr);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000989
Chris Lattnerbb75d332011-02-13 08:07:21 +0000990 Constant *DivCst =
991 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000992
Chris Lattnerbb75d332011-02-13 08:07:21 +0000993 Value *Tmp =
994 Shr->getOpcode() == Instruction::AShr ?
995 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
996 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000997
Chris Lattnerbb75d332011-02-13 08:07:21 +0000998 ICI.setOperand(0, Tmp);
Jim Grosbach0cc4a952011-09-30 18:09:53 +0000999
Chris Lattnerbb75d332011-02-13 08:07:21 +00001000 // If the builder folded the binop, just return it.
1001 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1002 if (TheDiv == 0)
1003 return &ICI;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001004
Chris Lattnerbb75d332011-02-13 08:07:21 +00001005 // Otherwise, fold this div/compare.
1006 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1007 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001008
Chris Lattnerbb75d332011-02-13 08:07:21 +00001009 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1010 assert(Res && "This div/cst should have folded!");
1011 return Res;
1012 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001013
1014
Chris Lattner74542aa2011-02-13 07:43:07 +00001015 // If we are comparing against bits always shifted out, the
1016 // comparison cannot succeed.
1017 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszak3facc432013-06-06 20:18:46 +00001018 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattner74542aa2011-02-13 07:43:07 +00001019 if (Shr->getOpcode() == Instruction::LShr)
1020 Comp = Comp.lshr(ShAmtVal);
1021 else
1022 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001023
Chris Lattner74542aa2011-02-13 07:43:07 +00001024 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1025 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszak3facc432013-06-06 20:18:46 +00001026 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner74542aa2011-02-13 07:43:07 +00001027 return ReplaceInstUsesWith(ICI, Cst);
1028 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001029
Chris Lattner74542aa2011-02-13 07:43:07 +00001030 // Otherwise, check to see if the bits shifted out are known to be zero.
1031 // If so, we can compare against the unshifted value:
1032 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattnere5116f82011-02-13 18:30:09 +00001033 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattner74542aa2011-02-13 07:43:07 +00001034 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001035
Chris Lattner74542aa2011-02-13 07:43:07 +00001036 if (Shr->hasOneUse()) {
1037 // Otherwise strength reduce the shift into an and.
1038 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszak3facc432013-06-06 20:18:46 +00001039 Constant *Mask = Builder->getInt(Val);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001040
Chris Lattner74542aa2011-02-13 07:43:07 +00001041 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1042 Mask, Shr->getName()+".mask");
1043 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1044 }
1045 return 0;
1046}
1047
Chris Lattner02446fc2010-01-04 07:37:31 +00001048
1049/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1050///
1051Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1052 Instruction *LHSI,
1053 ConstantInt *RHS) {
1054 const APInt &RHSV = RHS->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001055
Chris Lattner02446fc2010-01-04 07:37:31 +00001056 switch (LHSI->getOpcode()) {
1057 case Instruction::Trunc:
1058 if (ICI.isEquality() && LHSI->hasOneUse()) {
1059 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1060 // of the high bits truncated out of x are known.
1061 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1062 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner02446fc2010-01-04 07:37:31 +00001063 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001064 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001065
Chris Lattner02446fc2010-01-04 07:37:31 +00001066 // If all the high bits are known, we can do this xform.
1067 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1068 // Pull in the high bits from known-ones set.
Jay Foad40f8f622010-12-07 08:25:19 +00001069 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedman5b6dfee2012-05-11 01:32:59 +00001070 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner02446fc2010-01-04 07:37:31 +00001071 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001072 Builder->getInt(NewRHS));
Chris Lattner02446fc2010-01-04 07:37:31 +00001073 }
1074 }
1075 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001076
Chris Lattner02446fc2010-01-04 07:37:31 +00001077 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
1078 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1079 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1080 // fold the xor.
1081 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1082 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1083 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001084
Chris Lattner02446fc2010-01-04 07:37:31 +00001085 // If the sign bit of the XorCST is not set, there is no change to
1086 // the operation, just stop using the Xor.
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001087 if (!XorCST->isNegative()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001088 ICI.setOperand(0, CompareVal);
1089 Worklist.Add(LHSI);
1090 return &ICI;
1091 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001092
Chris Lattner02446fc2010-01-04 07:37:31 +00001093 // Was the old condition true if the operand is positive?
1094 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001095
Chris Lattner02446fc2010-01-04 07:37:31 +00001096 // If so, the new one isn't.
1097 isTrueIfPositive ^= true;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001098
Chris Lattner02446fc2010-01-04 07:37:31 +00001099 if (isTrueIfPositive)
1100 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1101 SubOne(RHS));
1102 else
1103 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1104 AddOne(RHS));
1105 }
1106
1107 if (LHSI->hasOneUse()) {
1108 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1109 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1110 const APInt &SignBit = XorCST->getValue();
1111 ICmpInst::Predicate Pred = ICI.isSigned()
1112 ? ICI.getUnsignedPredicate()
1113 : ICI.getSignedPredicate();
1114 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001115 Builder->getInt(RHSV ^ SignBit));
Chris Lattner02446fc2010-01-04 07:37:31 +00001116 }
1117
1118 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001119 if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001120 const APInt &NotSignBit = XorCST->getValue();
1121 ICmpInst::Predicate Pred = ICI.isSigned()
1122 ? ICI.getUnsignedPredicate()
1123 : ICI.getSignedPredicate();
1124 Pred = ICI.getSwappedPredicate(Pred);
1125 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001126 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner02446fc2010-01-04 07:37:31 +00001127 }
1128 }
David Majnemerfecf0d72013-07-09 09:20:58 +00001129
1130 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1131 // iff -C is a power of 2
1132 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
1133 XorCST->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1134 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCST);
1135
1136 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1137 // iff -C is a power of 2
1138 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
1139 XorCST->getValue() == -RHSV && RHSV.isPowerOf2())
1140 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCST);
Chris Lattner02446fc2010-01-04 07:37:31 +00001141 }
1142 break;
1143 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
1144 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1145 LHSI->getOperand(0)->hasOneUse()) {
1146 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001147
Chris Lattner02446fc2010-01-04 07:37:31 +00001148 // If the LHS is an AND of a truncating cast, we can widen the
1149 // and/compare to be the input width without changing the value
1150 // produced, eliminating a cast.
1151 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1152 // We can do this transformation if either the AND constant does not
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001153 // have its sign bit set or if it is an equality comparison.
Chris Lattner02446fc2010-01-04 07:37:31 +00001154 // Extending a relational comparison when we're checking the sign
1155 // bit would not work.
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001156 if (ICI.isEquality() ||
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001157 (!AndCST->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001158 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001159 Builder->CreateAnd(Cast->getOperand(0),
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001160 ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1161 NewAnd->takeName(LHSI);
Chris Lattner02446fc2010-01-04 07:37:31 +00001162 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer7e7c9cc2011-06-12 22:47:53 +00001163 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001164 }
1165 }
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001166
1167 // If the LHS is an AND of a zext, and we have an equality compare, we can
1168 // shrink the and/compare to the smaller type, eliminating the cast.
1169 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001170 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramerffd0ae62011-06-12 22:48:00 +00001171 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1172 // should fold the icmp to true/false in that case.
1173 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1174 Value *NewAnd =
1175 Builder->CreateAnd(Cast->getOperand(0),
1176 ConstantExpr::getTrunc(AndCST, Ty));
1177 NewAnd->takeName(LHSI);
1178 return new ICmpInst(ICI.getPredicate(), NewAnd,
1179 ConstantExpr::getTrunc(RHS, Ty));
1180 }
1181 }
1182
Chris Lattner02446fc2010-01-04 07:37:31 +00001183 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1184 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1185 // happens a LOT in code produced by the C front-end, for bitfield
1186 // access.
1187 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1188 if (Shift && !Shift->isShift())
1189 Shift = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001190
Chris Lattner02446fc2010-01-04 07:37:31 +00001191 ConstantInt *ShAmt;
1192 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001193 Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
1194 Type *AndTy = AndCST->getType(); // Type of the and.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001195
Chris Lattner02446fc2010-01-04 07:37:31 +00001196 // We can fold this as long as we can't shift unknown bits
1197 // into the mask. This can only happen with signed shift
1198 // rights, as they sign-extend.
1199 if (ShAmt) {
1200 bool CanFold = Shift->isLogicalShift();
1201 if (!CanFold) {
1202 // To test for the bad case of the signed shr, see if any
1203 // of the bits shifted in could be tested after the mask.
1204 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1205 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001206
Chris Lattner02446fc2010-01-04 07:37:31 +00001207 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001208 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
Chris Lattner02446fc2010-01-04 07:37:31 +00001209 AndCST->getValue()) == 0)
1210 CanFold = true;
1211 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001212
Chris Lattner02446fc2010-01-04 07:37:31 +00001213 if (CanFold) {
1214 Constant *NewCst;
1215 if (Shift->getOpcode() == Instruction::Shl)
1216 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1217 else
1218 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001219
Chris Lattner02446fc2010-01-04 07:37:31 +00001220 // Check to see if we are shifting out any of the bits being
1221 // compared.
1222 if (ConstantExpr::get(Shift->getOpcode(),
1223 NewCst, ShAmt) != RHS) {
1224 // If we shifted bits out, the fold is not going to work out.
1225 // As a special case, check to see if this means that the
1226 // result is always true or false now.
1227 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Jakub Staszak3facc432013-06-06 20:18:46 +00001228 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00001229 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Jakub Staszak3facc432013-06-06 20:18:46 +00001230 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00001231 } else {
1232 ICI.setOperand(1, NewCst);
1233 Constant *NewAndCST;
1234 if (Shift->getOpcode() == Instruction::Shl)
1235 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1236 else
1237 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1238 LHSI->setOperand(1, NewAndCST);
1239 LHSI->setOperand(0, Shift->getOperand(0));
1240 Worklist.Add(Shift); // Shift is dead.
1241 return &ICI;
1242 }
1243 }
1244 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001245
Chris Lattner02446fc2010-01-04 07:37:31 +00001246 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1247 // preferable because it allows the C<<Y expression to be hoisted out
1248 // of a loop if Y is invariant and X is not.
1249 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1250 ICI.isEquality() && !Shift->isArithmeticShift() &&
1251 !isa<Constant>(Shift->getOperand(0))) {
1252 // Compute C << Y.
1253 Value *NS;
1254 if (Shift->getOpcode() == Instruction::LShr) {
Benjamin Kramera9390a42011-09-27 20:39:19 +00001255 NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001256 } else {
1257 // Insert a logical shift.
Benjamin Kramera9390a42011-09-27 20:39:19 +00001258 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001259 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001260
Chris Lattner02446fc2010-01-04 07:37:31 +00001261 // Compute X & (C << Y).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001262 Value *NewAnd =
Chris Lattner02446fc2010-01-04 07:37:31 +00001263 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001264
Chris Lattner02446fc2010-01-04 07:37:31 +00001265 ICI.setOperand(0, NewAnd);
1266 return &ICI;
1267 }
Paul Redmond6da2e222012-12-19 19:47:13 +00001268
1269 // Replace ((X & AndCST) > RHSV) with ((X & AndCST) != 0), if any
1270 // bit set in (X & AndCST) will produce a result greater than RHSV.
1271 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1272 unsigned NTZ = AndCST->getValue().countTrailingZeros();
1273 if ((NTZ < AndCST->getBitWidth()) &&
1274 APInt::getOneBitSet(AndCST->getBitWidth(), NTZ).ugt(RHSV))
1275 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1276 Constant::getNullValue(RHS->getType()));
1277 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001278 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001279
Chris Lattner02446fc2010-01-04 07:37:31 +00001280 // Try to optimize things like "A[i]&42 == 0" to index computations.
1281 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1282 if (GetElementPtrInst *GEP =
1283 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1284 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1285 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1286 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1287 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1288 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1289 return Res;
1290 }
1291 }
David Majnemer36b6f742013-07-09 08:09:32 +00001292
1293 // X & -C == -C -> X > u ~C
1294 // X & -C != -C -> X <= u ~C
1295 // iff C is a power of 2
1296 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1297 return new ICmpInst(
1298 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1299 : ICmpInst::ICMP_ULE,
1300 LHSI->getOperand(0), SubOne(RHS));
Chris Lattner02446fc2010-01-04 07:37:31 +00001301 break;
1302
1303 case Instruction::Or: {
1304 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1305 break;
1306 Value *P, *Q;
1307 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1308 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1309 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner02446fc2010-01-04 07:37:31 +00001310 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1311 Constant::getNullValue(P->getType()));
1312 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1313 Constant::getNullValue(Q->getType()));
1314 Instruction *Op;
1315 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1316 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1317 else
1318 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1319 return Op;
1320 }
1321 break;
1322 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001323
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001324 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1325 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1326 if (!Val) break;
1327
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +00001328 // If this is a signed comparison to 0 and the mul is sign preserving,
1329 // use the mul LHS operand instead.
1330 ICmpInst::Predicate pred = ICI.getPredicate();
1331 if (isSignTest(pred, RHS) && !Val->isZero() &&
1332 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1333 return new ICmpInst(Val->isNegative() ?
1334 ICmpInst::getSwappedPredicate(pred) : pred,
1335 LHSI->getOperand(0),
1336 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001337
1338 break;
1339 }
1340
Chris Lattner02446fc2010-01-04 07:37:31 +00001341 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner02446fc2010-01-04 07:37:31 +00001342 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb41f4bb2013-06-28 23:42:03 +00001343 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1344 if (!ShAmt) {
1345 Value *X;
1346 // (1 << X) pred P2 -> X pred Log2(P2)
1347 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1348 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1349 ICmpInst::Predicate Pred = ICI.getPredicate();
1350 if (ICI.isUnsigned()) {
1351 if (!RHSVIsPowerOf2) {
1352 // (1 << X) < 30 -> X <= 4
1353 // (1 << X) <= 30 -> X <= 4
1354 // (1 << X) >= 30 -> X > 4
1355 // (1 << X) > 30 -> X > 4
1356 if (Pred == ICmpInst::ICMP_ULT)
1357 Pred = ICmpInst::ICMP_ULE;
1358 else if (Pred == ICmpInst::ICMP_UGE)
1359 Pred = ICmpInst::ICMP_UGT;
1360 }
1361 unsigned RHSLog2 = RHSV.logBase2();
1362
1363 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1364 // (1 << X) > 2147483648 -> X > 31 -> false
1365 // (1 << X) <= 2147483648 -> X <= 31 -> true
1366 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1367 if (RHSLog2 == TypeBits-1) {
1368 if (Pred == ICmpInst::ICMP_UGE)
1369 Pred = ICmpInst::ICMP_EQ;
1370 else if (Pred == ICmpInst::ICMP_UGT)
1371 return ReplaceInstUsesWith(ICI, Builder->getFalse());
1372 else if (Pred == ICmpInst::ICMP_ULE)
1373 return ReplaceInstUsesWith(ICI, Builder->getTrue());
1374 else if (Pred == ICmpInst::ICMP_ULT)
1375 Pred = ICmpInst::ICMP_NE;
1376 }
1377
1378 return new ICmpInst(Pred, X,
1379 ConstantInt::get(RHS->getType(), RHSLog2));
1380 } else if (ICI.isSigned()) {
1381 if (RHSV.isAllOnesValue()) {
1382 // (1 << X) <= -1 -> X == 31
1383 if (Pred == ICmpInst::ICMP_SLE)
1384 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1385 ConstantInt::get(RHS->getType(), TypeBits-1));
1386
1387 // (1 << X) > -1 -> X != 31
1388 if (Pred == ICmpInst::ICMP_SGT)
1389 return new ICmpInst(ICmpInst::ICMP_NE, X,
1390 ConstantInt::get(RHS->getType(), TypeBits-1));
1391 } else if (!RHSV) {
1392 // (1 << X) < 0 -> X == 31
1393 // (1 << X) <= 0 -> X == 31
1394 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1395 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1396 ConstantInt::get(RHS->getType(), TypeBits-1));
1397
1398 // (1 << X) >= 0 -> X != 31
1399 // (1 << X) > 0 -> X != 31
1400 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1401 return new ICmpInst(ICmpInst::ICMP_NE, X,
1402 ConstantInt::get(RHS->getType(), TypeBits-1));
1403 }
1404 } else if (ICI.isEquality()) {
1405 if (RHSVIsPowerOf2)
1406 return new ICmpInst(
1407 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1408
1409 return ReplaceInstUsesWith(
1410 ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
1411 : Builder->getTrue());
1412 }
1413 }
1414 break;
1415 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001416
Chris Lattner02446fc2010-01-04 07:37:31 +00001417 // Check that the shift amount is in range. If not, don't perform
1418 // undefined shifts. When the shift is visited it will be
1419 // simplified.
1420 if (ShAmt->uge(TypeBits))
1421 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001422
Chris Lattner02446fc2010-01-04 07:37:31 +00001423 if (ICI.isEquality()) {
1424 // If we are comparing against bits always shifted out, the
1425 // comparison cannot succeed.
1426 Constant *Comp =
1427 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1428 ShAmt);
1429 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1430 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszak3facc432013-06-06 20:18:46 +00001431 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner02446fc2010-01-04 07:37:31 +00001432 return ReplaceInstUsesWith(ICI, Cst);
1433 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001434
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001435 // If the shift is NUW, then it is just shifting out zeros, no need for an
1436 // AND.
1437 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1438 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1439 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001440
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001441 // If the shift is NSW and we compare to 0, then it is just shifting out
1442 // sign bits, no need for an AND either.
1443 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1444 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1445 ConstantExpr::getLShr(RHS, ShAmt));
1446
Chris Lattner02446fc2010-01-04 07:37:31 +00001447 if (LHSI->hasOneUse()) {
1448 // Otherwise strength reduce the shift into an and.
1449 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszak3facc432013-06-06 20:18:46 +00001450 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1451 TypeBits - ShAmtVal));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001452
Chris Lattner02446fc2010-01-04 07:37:31 +00001453 Value *And =
1454 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1455 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00001456 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner02446fc2010-01-04 07:37:31 +00001457 }
1458 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001459
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001460 // If this is a signed comparison to 0 and the shift is sign preserving,
1461 // use the shift LHS operand instead.
1462 ICmpInst::Predicate pred = ICI.getPredicate();
1463 if (isSignTest(pred, RHS) &&
1464 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1465 return new ICmpInst(pred,
1466 LHSI->getOperand(0),
1467 Constant::getNullValue(RHS->getType()));
1468
Chris Lattner02446fc2010-01-04 07:37:31 +00001469 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1470 bool TrueIfSigned = false;
1471 if (LHSI->hasOneUse() &&
1472 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1473 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattnerbb75d332011-02-13 08:07:21 +00001474 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001475 APInt::getOneBitSet(TypeBits,
Chris Lattnerbb75d332011-02-13 08:07:21 +00001476 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00001477 Value *And =
1478 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1479 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1480 And, Constant::getNullValue(And->getType()));
1481 }
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001482
1483 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaisonbdd2d982013-03-13 14:40:37 +00001484 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1485 // 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 +00001486 // This enables to get rid of the shift in favor of a trunc which can be
1487 // free on the target. It has the additional benefit of comparing to a
1488 // smaller constant, which will be target friendly.
1489 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaisonbdd2d982013-03-13 14:40:37 +00001490 if (LHSI->hasOneUse() &&
1491 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001492 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1493 Constant *NCI = ConstantExpr::getTrunc(
1494 ConstantExpr::getAShr(RHS,
1495 ConstantInt::get(RHS->getType(), Amt)),
1496 NTy);
1497 return new ICmpInst(ICI.getPredicate(),
1498 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaisonad079b22013-02-15 15:18:17 +00001499 NCI);
Arnaud A. de Grandmaison7c5c9b32013-02-15 14:35:47 +00001500 }
1501
Chris Lattner02446fc2010-01-04 07:37:31 +00001502 break;
1503 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001504
Chris Lattner02446fc2010-01-04 07:37:31 +00001505 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001506 case Instruction::AShr: {
1507 // Handle equality comparisons of shift-by-constant.
1508 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1509 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1510 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattner74542aa2011-02-13 07:43:07 +00001511 return Res;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001512 }
1513
1514 // Handle exact shr's.
1515 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1516 if (RHSV.isMinValue())
1517 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1518 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001519 break;
Nick Lewyckyb042f8e2011-02-28 08:31:40 +00001520 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001521
Chris Lattner02446fc2010-01-04 07:37:31 +00001522 case Instruction::SDiv:
1523 case Instruction::UDiv:
1524 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001525 // Fold this div into the comparison, producing a range check.
1526 // Determine, based on the divide type, what the range is being
1527 // checked. If there is an overflow on the low or high side, remember
Chris Lattner02446fc2010-01-04 07:37:31 +00001528 // it, otherwise compute the range [low, hi) bounding the new value.
1529 // See: InsertRangeTest above for the kinds of replacements possible.
1530 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1531 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1532 DivRHS))
1533 return R;
1534 break;
1535
David Majnemer377a5c12013-07-09 07:50:59 +00001536 case Instruction::Sub: {
1537 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1538 if (!LHSC) break;
1539 const APInt &LHSV = LHSC->getValue();
1540
1541 // C1-X <u C2 -> (X|(C2-1)) == C1
1542 // iff C1 & (C2-1) == C2-1
1543 // C2 is a power of 2
1544 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1545 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1546 return new ICmpInst(ICmpInst::ICMP_EQ,
1547 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1548 LHSC);
1549
1550 // C1-X >u C2 -> (X|C2) == C1
1551 // iff C1 & C2 == C2
1552 // C2+1 is a power of 2
1553 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1554 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1555 return new ICmpInst(ICmpInst::ICMP_NE,
1556 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1557 break;
1558 }
1559
Chris Lattner02446fc2010-01-04 07:37:31 +00001560 case Instruction::Add:
1561 // Fold: icmp pred (add X, C1), C2
1562 if (!ICI.isEquality()) {
1563 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1564 if (!LHSC) break;
1565 const APInt &LHSV = LHSC->getValue();
1566
1567 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1568 .subtract(LHSV);
1569
1570 if (ICI.isSigned()) {
1571 if (CR.getLower().isSignBit()) {
1572 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001573 Builder->getInt(CR.getUpper()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001574 } else if (CR.getUpper().isSignBit()) {
1575 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001576 Builder->getInt(CR.getLower()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001577 }
1578 } else {
1579 if (CR.getLower().isMinValue()) {
1580 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001581 Builder->getInt(CR.getUpper()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001582 } else if (CR.getUpper().isMinValue()) {
1583 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszak3facc432013-06-06 20:18:46 +00001584 Builder->getInt(CR.getLower()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001585 }
1586 }
David Majnemer53fc3992013-07-08 11:53:08 +00001587
David Majnemer11c29ba2013-07-09 07:58:32 +00001588 // X-C1 <u C2 -> (X & -C2) == C1
1589 // iff C1 & (C2-1) == 0
1590 // C2 is a power of 2
David Majnemer53fc3992013-07-08 11:53:08 +00001591 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemer11c29ba2013-07-09 07:58:32 +00001592 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemer53fc3992013-07-08 11:53:08 +00001593 return new ICmpInst(ICmpInst::ICMP_EQ,
1594 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1595 ConstantExpr::getNeg(LHSC));
David Majnemer11c29ba2013-07-09 07:58:32 +00001596
1597 // X-C1 >u C2 -> (X & ~C2) == C1
1598 // iff C1 & C2 == 0
1599 // C2+1 is a power of 2
1600 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1601 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1602 return new ICmpInst(ICmpInst::ICMP_NE,
1603 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1604 ConstantExpr::getNeg(LHSC));
Chris Lattner02446fc2010-01-04 07:37:31 +00001605 }
1606 break;
1607 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001608
Chris Lattner02446fc2010-01-04 07:37:31 +00001609 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1610 if (ICI.isEquality()) {
1611 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001612
1613 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner02446fc2010-01-04 07:37:31 +00001614 // the second operand is a constant, simplify a bit.
1615 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1616 switch (BO->getOpcode()) {
1617 case Instruction::SRem:
1618 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1619 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1620 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohmane0567812010-04-08 23:03:40 +00001621 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001622 Value *NewRem =
1623 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1624 BO->getName());
1625 return new ICmpInst(ICI.getPredicate(), NewRem,
1626 Constant::getNullValue(BO->getType()));
1627 }
1628 }
1629 break;
1630 case Instruction::Add:
1631 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1632 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1633 if (BO->hasOneUse())
1634 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1635 ConstantExpr::getSub(RHS, BOp1C));
1636 } else if (RHSV == 0) {
1637 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1638 // efficiently invertible, or if the add has just this one use.
1639 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001640
Chris Lattner02446fc2010-01-04 07:37:31 +00001641 if (Value *NegVal = dyn_castNegVal(BOp1))
1642 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner5036ce42011-04-26 20:02:45 +00001643 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner02446fc2010-01-04 07:37:31 +00001644 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner5036ce42011-04-26 20:02:45 +00001645 if (BO->hasOneUse()) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001646 Value *Neg = Builder->CreateNeg(BOp1);
1647 Neg->takeName(BO);
1648 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1649 }
1650 }
1651 break;
1652 case Instruction::Xor:
1653 // For the xor case, we can xor two constants together, eliminating
1654 // the explicit xor.
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001655 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1656 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner02446fc2010-01-04 07:37:31 +00001657 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001658 } else if (RHSV == 0) {
1659 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner02446fc2010-01-04 07:37:31 +00001660 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1661 BO->getOperand(1));
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001662 }
Chris Lattner02446fc2010-01-04 07:37:31 +00001663 break;
Benjamin Kramere7fdcad2011-06-13 15:24:24 +00001664 case Instruction::Sub:
1665 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1666 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1667 if (BO->hasOneUse())
1668 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1669 ConstantExpr::getSub(BOp0C, RHS));
1670 } else if (RHSV == 0) {
1671 // Replace ((sub A, B) != 0) with (A != B)
1672 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1673 BO->getOperand(1));
1674 }
1675 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001676 case Instruction::Or:
1677 // If bits are being or'd in that are not present in the constant we
1678 // are comparing against, then the comparison could never succeed!
Eli Friedman618898e2010-07-29 18:03:33 +00001679 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00001680 Constant *NotCI = ConstantExpr::getNot(RHS);
1681 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Jakub Staszak3facc432013-06-06 20:18:46 +00001682 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Chris Lattner02446fc2010-01-04 07:37:31 +00001683 }
1684 break;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001685
Chris Lattner02446fc2010-01-04 07:37:31 +00001686 case Instruction::And:
1687 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1688 // If bits are being compared against that are and'd out, then the
1689 // comparison can never succeed!
1690 if ((RHSV & ~BOC->getValue()) != 0)
Jakub Staszak3facc432013-06-06 20:18:46 +00001691 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001692
Chris Lattner02446fc2010-01-04 07:37:31 +00001693 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1694 if (RHS == BOC && RHSV.isPowerOf2())
1695 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1696 ICmpInst::ICMP_NE, LHSI,
1697 Constant::getNullValue(RHS->getType()));
Benjamin Kramerfc87cdc2011-07-04 20:16:36 +00001698
1699 // Don't perform the following transforms if the AND has multiple uses
1700 if (!BO->hasOneUse())
1701 break;
1702
Chris Lattner02446fc2010-01-04 07:37:31 +00001703 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1704 if (BOC->getValue().isSignBit()) {
1705 Value *X = BO->getOperand(0);
1706 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001707 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001708 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1709 return new ICmpInst(pred, X, Zero);
1710 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001711
Chris Lattner02446fc2010-01-04 07:37:31 +00001712 // ((X & ~7) == 0) --> X < 8
1713 if (RHSV == 0 && isHighOnes(BOC)) {
1714 Value *X = BO->getOperand(0);
1715 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001716 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner02446fc2010-01-04 07:37:31 +00001717 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1718 return new ICmpInst(pred, X, NegX);
1719 }
1720 }
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001721 break;
1722 case Instruction::Mul:
Arnaud A. de Grandmaison1bb93a92013-03-25 11:47:38 +00001723 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison35763b12013-03-25 09:48:49 +00001724 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1725 // The trivial case (mul X, 0) is handled by InstSimplify
1726 // General case : (mul X, C) != 0 iff X != 0
1727 // (mul X, C) == 0 iff X == 0
1728 if (!BOC->isZero())
1729 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1730 Constant::getNullValue(RHS->getType()));
1731 }
1732 }
1733 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001734 default: break;
1735 }
1736 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1737 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner03357402010-01-05 18:09:56 +00001738 switch (II->getIntrinsicID()) {
1739 case Intrinsic::bswap:
Chris Lattner02446fc2010-01-04 07:37:31 +00001740 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001741 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszak3facc432013-06-06 20:18:46 +00001742 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner02446fc2010-01-04 07:37:31 +00001743 return &ICI;
Chris Lattner03357402010-01-05 18:09:56 +00001744 case Intrinsic::ctlz:
1745 case Intrinsic::cttz:
1746 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1747 if (RHSV == RHS->getType()->getBitWidth()) {
1748 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001749 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001750 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1751 return &ICI;
1752 }
1753 break;
1754 case Intrinsic::ctpop:
1755 // popcount(A) == 0 -> A == 0 and likewise for !=
1756 if (RHS->isZero()) {
1757 Worklist.Add(II);
Gabor Greifcaf70b32010-06-24 16:11:44 +00001758 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner03357402010-01-05 18:09:56 +00001759 ICI.setOperand(1, RHS);
1760 return &ICI;
1761 }
1762 break;
1763 default:
Duncan Sands34727662010-07-12 08:16:59 +00001764 break;
Chris Lattner02446fc2010-01-04 07:37:31 +00001765 }
1766 }
1767 }
1768 return 0;
1769}
1770
1771/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1772/// We only handle extending casts so far.
1773///
1774Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1775 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1776 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001777 Type *SrcTy = LHSCIOp->getType();
1778 Type *DestTy = LHSCI->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00001779 Value *RHSCIOp;
1780
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001781 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner02446fc2010-01-04 07:37:31 +00001782 // integer type is the same size as the pointer type.
1783 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +00001784 TD->getPointerSizeInBits() ==
Chris Lattner02446fc2010-01-04 07:37:31 +00001785 cast<IntegerType>(DestTy)->getBitWidth()) {
1786 Value *RHSOp = 0;
1787 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1788 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1789 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1790 RHSOp = RHSC->getOperand(0);
1791 // If the pointer types don't match, insert a bitcast.
1792 if (LHSCIOp->getType() != RHSOp->getType())
1793 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1794 }
1795
1796 if (RHSOp)
1797 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1798 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001799
Chris Lattner02446fc2010-01-04 07:37:31 +00001800 // The code below only handles extension cast instructions, so far.
1801 // Enforce this.
1802 if (LHSCI->getOpcode() != Instruction::ZExt &&
1803 LHSCI->getOpcode() != Instruction::SExt)
1804 return 0;
1805
1806 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1807 bool isSignedCmp = ICI.isSigned();
1808
1809 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1810 // Not an extension from the same type?
1811 RHSCIOp = CI->getOperand(0);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001812 if (RHSCIOp->getType() != LHSCIOp->getType())
Chris Lattner02446fc2010-01-04 07:37:31 +00001813 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001814
Chris Lattner02446fc2010-01-04 07:37:31 +00001815 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1816 // and the other is a zext), then we can't handle this.
1817 if (CI->getOpcode() != LHSCI->getOpcode())
1818 return 0;
1819
1820 // Deal with equality cases early.
1821 if (ICI.isEquality())
1822 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1823
1824 // A signed comparison of sign extended values simplifies into a
1825 // signed comparison.
1826 if (isSignedCmp && isSignedExt)
1827 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1828
1829 // The other three cases all fold into an unsigned comparison.
1830 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1831 }
1832
1833 // If we aren't dealing with a constant on the RHS, exit early
1834 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1835 if (!CI)
1836 return 0;
1837
1838 // Compute the constant that would happen if we truncated to SrcTy then
1839 // reextended to DestTy.
1840 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1841 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1842 Res1, DestTy);
1843
1844 // If the re-extended constant didn't change...
1845 if (Res2 == CI) {
1846 // Deal with equality cases early.
1847 if (ICI.isEquality())
1848 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1849
1850 // A signed comparison of sign extended values simplifies into a
1851 // signed comparison.
1852 if (isSignedExt && isSignedCmp)
1853 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1854
1855 // The other three cases all fold into an unsigned comparison.
1856 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1857 }
1858
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001859 // The re-extended constant changed so the constant cannot be represented
Chris Lattner02446fc2010-01-04 07:37:31 +00001860 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands9d32f602011-01-20 13:21:55 +00001861 // All the cases that fold to true or false will have already been handled
1862 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner02446fc2010-01-04 07:37:31 +00001863
Duncan Sands9d32f602011-01-20 13:21:55 +00001864 if (isSignedCmp || !isSignedExt)
1865 return 0;
Chris Lattner02446fc2010-01-04 07:37:31 +00001866
1867 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1868 // should have been folded away previously and not enter in here.
Duncan Sands9d32f602011-01-20 13:21:55 +00001869
1870 // We're performing an unsigned comp with a sign extended value.
1871 // This is true if the input is >= 0. [aka >s -1]
1872 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1873 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner02446fc2010-01-04 07:37:31 +00001874
1875 // Finally, return the value computed.
Duncan Sands9d32f602011-01-20 13:21:55 +00001876 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner02446fc2010-01-04 07:37:31 +00001877 return ReplaceInstUsesWith(ICI, Result);
1878
Duncan Sands9d32f602011-01-20 13:21:55 +00001879 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner02446fc2010-01-04 07:37:31 +00001880 return BinaryOperator::CreateNot(Result);
1881}
1882
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001883/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1884/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001885/// If this is of the form:
1886/// sum = a + b
1887/// if (sum+128 >u 255)
1888/// Then replace it with llvm.sadd.with.overflow.i8.
1889///
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001890static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1891 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001892 InstCombiner &IC) {
Chris Lattner368397b2010-12-19 17:59:02 +00001893 // The transformation we're trying to do here is to transform this into an
1894 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1895 // with a narrower add, and discard the add-with-constant that is part of the
1896 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001897
Chris Lattner368397b2010-12-19 17:59:02 +00001898 // In order to eliminate the add-with-constant, the compare can be its only
1899 // use.
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001900 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Chris Lattner368397b2010-12-19 17:59:02 +00001901 if (!AddWithCst->hasOneUse()) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001902
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001903 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1904 if (!CI2->getValue().isPowerOf2()) return 0;
1905 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1906 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001907
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001908 // The width of the new add formed is 1 more than the bias.
1909 ++NewWidth;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001910
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001911 // Check to see that CI1 is an all-ones value with NewWidth bits.
1912 if (CI1->getBitWidth() == NewWidth ||
1913 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1914 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001915
Eli Friedman54b92112011-11-28 23:32:19 +00001916 // This is only really a signed overflow check if the inputs have been
1917 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1918 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1919 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1920 if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1921 IC.ComputeNumSignBits(B) < NeededSignBits)
1922 return 0;
1923
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001924 // In order to replace the original add with a narrower
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001925 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1926 // and truncates that discard the high bits of the add. Verify that this is
1927 // the case.
1928 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1929 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1930 UI != E; ++UI) {
1931 if (*UI == AddWithCst) continue;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001932
Chris Lattnerdd7e8372010-12-19 18:22:06 +00001933 // Only accept truncates for now. We would really like a nice recursive
1934 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1935 // chain to see which bits of a value are actually demanded. If the
1936 // original add had another add which was then immediately truncated, we
1937 // could still do the transformation.
1938 TruncInst *TI = dyn_cast<TruncInst>(*UI);
1939 if (TI == 0 ||
1940 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1941 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001942
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001943 // If the pattern matches, truncate the inputs to the narrower type and
1944 // use the sadd_with_overflow intrinsic to efficiently compute both the
1945 // result and the overflow bit.
Chris Lattner0a624742010-12-19 18:35:09 +00001946 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001947
Jay Foad5fdd6c82011-07-12 14:06:48 +00001948 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner0a624742010-12-19 18:35:09 +00001949 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001950 NewType);
Chris Lattner0a624742010-12-19 18:35:09 +00001951
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001952 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001953
Chris Lattner0a624742010-12-19 18:35:09 +00001954 // Put the new code above the original add, in case there are any uses of the
1955 // add between the add and the compare.
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001956 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001957
Chris Lattner0a624742010-12-19 18:35:09 +00001958 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1959 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1960 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1961 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1962 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001963
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001964 // The inner add was the result of the narrow add, zero extended to the
1965 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattner0fe80bb2010-12-19 18:38:44 +00001966 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001967
Chris Lattner0a624742010-12-19 18:35:09 +00001968 // The original icmp gets replaced with the overflow value.
1969 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattnerf0f568b2010-12-19 17:52:50 +00001970}
Chris Lattner02446fc2010-01-04 07:37:31 +00001971
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001972static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1973 InstCombiner &IC) {
1974 // Don't bother doing this transformation for pointers, don't do it for
1975 // vectors.
1976 if (!isa<IntegerType>(OrigAddV->getType())) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001977
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001978 // If the add is a constant expr, then we don't bother transforming it.
1979 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1980 if (OrigAdd == 0) return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001981
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001982 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00001983
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001984 // Put the new code above the original add, in case there are any uses of the
1985 // add between the add and the compare.
1986 InstCombiner::BuilderTy *Builder = IC.Builder;
1987 Builder->SetInsertPoint(OrigAdd);
1988
1989 Module *M = I.getParent()->getParent()->getParent();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001990 Type *Ty = LHS->getType();
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001991 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattnere5cbdca2010-12-19 19:37:52 +00001992 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
1993 Value *Add = Builder->CreateExtractValue(Call, 0);
1994
1995 IC.ReplaceInstUsesWith(*OrigAdd, Add);
1996
1997 // The original icmp gets replaced with the overflow value.
1998 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
1999}
2000
Owen Andersonda1c1222011-01-11 00:36:45 +00002001// DemandedBitsLHSMask - When performing a comparison against a constant,
2002// it is possible that not all the bits in the LHS are demanded. This helper
2003// method computes the mask that IS demanded.
2004static APInt DemandedBitsLHSMask(ICmpInst &I,
2005 unsigned BitWidth, bool isSignCheck) {
2006 if (isSignCheck)
2007 return APInt::getSignBit(BitWidth);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002008
Owen Andersonda1c1222011-01-11 00:36:45 +00002009 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2010 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Andersona33b6252011-01-11 18:26:37 +00002011 const APInt &RHS = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002012
Owen Andersonda1c1222011-01-11 00:36:45 +00002013 switch (I.getPredicate()) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002014 // For a UGT comparison, we don't care about any bits that
Owen Andersonda1c1222011-01-11 00:36:45 +00002015 // correspond to the trailing ones of the comparand. The value of these
2016 // bits doesn't impact the outcome of the comparison, because any value
2017 // greater than the RHS must differ in a bit higher than these due to carry.
2018 case ICmpInst::ICMP_UGT: {
2019 unsigned trailingOnes = RHS.countTrailingOnes();
2020 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2021 return ~lowBitsSet;
2022 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002023
Owen Andersonda1c1222011-01-11 00:36:45 +00002024 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2025 // Any value less than the RHS must differ in a higher bit because of carries.
2026 case ICmpInst::ICMP_ULT: {
2027 unsigned trailingZeros = RHS.countTrailingZeros();
2028 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2029 return ~lowBitsSet;
2030 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002031
Owen Andersonda1c1222011-01-11 00:36:45 +00002032 default:
2033 return APInt::getAllOnesValue(BitWidth);
2034 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002035
Owen Andersonda1c1222011-01-11 00:36:45 +00002036}
Chris Lattner02446fc2010-01-04 07:37:31 +00002037
2038Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2039 bool Changed = false;
Chris Lattner5f670d42010-02-01 19:54:45 +00002040 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002041
Chris Lattner02446fc2010-01-04 07:37:31 +00002042 /// Orders the operands of the compare so that they are listed from most
2043 /// complex to least complex. This puts constants before unary operators,
2044 /// before binary operators.
Chris Lattner5f670d42010-02-01 19:54:45 +00002045 if (getComplexity(Op0) < getComplexity(Op1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002046 I.swapOperands();
Chris Lattner5f670d42010-02-01 19:54:45 +00002047 std::swap(Op0, Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00002048 Changed = true;
2049 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002050
Chris Lattner02446fc2010-01-04 07:37:31 +00002051 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
2052 return ReplaceInstUsesWith(I, V);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002053
Pete Cooper65a6b572011-12-01 03:58:40 +00002054 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooper165695d2011-12-01 19:13:26 +00002055 // ie, abs(val) != 0 -> val != 0
Pete Cooper65a6b572011-12-01 03:58:40 +00002056 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2057 {
Pete Cooper165695d2011-12-01 19:13:26 +00002058 Value *Cond, *SelectTrue, *SelectFalse;
2059 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooper65a6b572011-12-01 03:58:40 +00002060 m_Value(SelectFalse)))) {
Pete Cooper165695d2011-12-01 19:13:26 +00002061 if (Value *V = dyn_castNegVal(SelectTrue)) {
2062 if (V == SelectFalse)
2063 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2064 }
2065 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2066 if (V == SelectTrue)
2067 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooper65a6b572011-12-01 03:58:40 +00002068 }
2069 }
2070 }
2071
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002072 Type *Ty = Op0->getType();
Chris Lattner02446fc2010-01-04 07:37:31 +00002073
2074 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002075 if (Ty->isIntegerTy(1)) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002076 switch (I.getPredicate()) {
2077 default: llvm_unreachable("Invalid icmp instruction!");
2078 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2079 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2080 return BinaryOperator::CreateNot(Xor);
2081 }
2082 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2083 return BinaryOperator::CreateXor(Op0, Op1);
2084
2085 case ICmpInst::ICMP_UGT:
2086 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2087 // FALL THROUGH
2088 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2089 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2090 return BinaryOperator::CreateAnd(Not, Op1);
2091 }
2092 case ICmpInst::ICMP_SGT:
2093 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2094 // FALL THROUGH
2095 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2096 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2097 return BinaryOperator::CreateAnd(Not, Op0);
2098 }
2099 case ICmpInst::ICMP_UGE:
2100 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2101 // FALL THROUGH
2102 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2103 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2104 return BinaryOperator::CreateOr(Not, Op1);
2105 }
2106 case ICmpInst::ICMP_SGE:
2107 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2108 // FALL THROUGH
2109 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2110 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2111 return BinaryOperator::CreateOr(Not, Op0);
2112 }
2113 }
2114 }
2115
2116 unsigned BitWidth = 0;
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002117 if (Ty->isIntOrIntVectorTy())
Chris Lattner02446fc2010-01-04 07:37:31 +00002118 BitWidth = Ty->getScalarSizeInBits();
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002119 else if (TD) // Pointers require TD info to get their size.
2120 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002121
Chris Lattner02446fc2010-01-04 07:37:31 +00002122 bool isSignBit = false;
2123
2124 // See if we are doing a comparison with a constant.
2125 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2126 Value *A = 0, *B = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002127
Owen Andersone63dda52010-12-17 18:08:00 +00002128 // Match the following pattern, which is a common idiom when writing
2129 // overflow-safe integer arithmetic function. The source performs an
2130 // addition in wider type, and explicitly checks for overflow using
2131 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2132 // sadd_with_overflow intrinsic.
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002133 //
2134 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002135 // operations if we worked out the formulas to compute the appropriate
Owen Andersone63dda52010-12-17 18:08:00 +00002136 // magic constants.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002137 //
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002138 // sum = a + b
2139 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Andersone63dda52010-12-17 18:08:00 +00002140 {
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002141 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Andersone63dda52010-12-17 18:08:00 +00002142 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002143 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattner0fe80bb2010-12-19 18:38:44 +00002144 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattnerf0f568b2010-12-19 17:52:50 +00002145 return Res;
Owen Andersone63dda52010-12-17 18:08:00 +00002146 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002147
Chris Lattner02446fc2010-01-04 07:37:31 +00002148 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2149 if (I.isEquality() && CI->isZero() &&
2150 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2151 // (icmp cond A B) if cond is equality
2152 return new ICmpInst(I.getPredicate(), A, B);
2153 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002154
Chris Lattner02446fc2010-01-04 07:37:31 +00002155 // If we have an icmp le or icmp ge instruction, turn it into the
2156 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2157 // them being folded in the code below. The SimplifyICmpInst code has
2158 // already handled the edge cases for us, so we just assert on them.
2159 switch (I.getPredicate()) {
2160 default: break;
2161 case ICmpInst::ICMP_ULE:
2162 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2163 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002164 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002165 case ICmpInst::ICMP_SLE:
2166 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2167 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002168 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002169 case ICmpInst::ICMP_UGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002170 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00002171 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002172 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002173 case ICmpInst::ICMP_SGE:
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002174 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner02446fc2010-01-04 07:37:31 +00002175 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002176 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002177 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002178
Chris Lattner02446fc2010-01-04 07:37:31 +00002179 // If this comparison is a normal comparison, it demands all
2180 // bits, if it is a sign bit comparison, it only demands the sign bit.
2181 bool UnusedBit;
2182 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2183 }
2184
2185 // See if we can fold the comparison based on range information we can get
2186 // by checking whether bits are known to be zero or one in the input.
2187 if (BitWidth != 0) {
2188 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2189 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2190
2191 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersonda1c1222011-01-11 00:36:45 +00002192 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner02446fc2010-01-04 07:37:31 +00002193 Op0KnownZero, Op0KnownOne, 0))
2194 return &I;
2195 if (SimplifyDemandedBits(I.getOperandUse(1),
2196 APInt::getAllOnesValue(BitWidth),
2197 Op1KnownZero, Op1KnownOne, 0))
2198 return &I;
2199
2200 // Given the known and unknown bits, compute a range that the LHS could be
2201 // in. Compute the Min, Max and RHS values based on the known bits. For the
2202 // EQ and NE we use unsigned values.
2203 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2204 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2205 if (I.isSigned()) {
2206 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2207 Op0Min, Op0Max);
2208 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2209 Op1Min, Op1Max);
2210 } else {
2211 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2212 Op0Min, Op0Max);
2213 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2214 Op1Min, Op1Max);
2215 }
2216
2217 // If Min and Max are known to be the same, then SimplifyDemandedBits
2218 // figured out that the LHS is a constant. Just constant fold this now so
2219 // that code below can assume that Min != Max.
2220 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2221 return new ICmpInst(I.getPredicate(),
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002222 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner02446fc2010-01-04 07:37:31 +00002223 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2224 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002225 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner02446fc2010-01-04 07:37:31 +00002226
2227 // Based on the range information we know about the LHS, see if we can
Nick Lewyckyd8d15842011-02-28 06:20:05 +00002228 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner02446fc2010-01-04 07:37:31 +00002229 switch (I.getPredicate()) {
2230 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner75d8f592010-11-21 06:44:42 +00002231 case ICmpInst::ICMP_EQ: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002232 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002233 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002234
Chris Lattner75d8f592010-11-21 06:44:42 +00002235 // If all bits are known zero except for one, then we know at most one
2236 // bit is set. If the comparison is against zero, then this is a check
2237 // to see if *that* bit is set.
2238 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2239 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2240 // If the LHS is an AND with the same constant, look through it.
2241 Value *LHS = 0;
2242 ConstantInt *LHSC = 0;
2243 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2244 LHSC->getValue() != Op0KnownZeroInverted)
2245 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002246
Chris Lattner75d8f592010-11-21 06:44:42 +00002247 // 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 +00002248 // then turn "((1 << x)&8) == 0" into "x != 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002249 Value *X = 0;
2250 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2251 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002252 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002253 ConstantInt::get(X->getType(), CmpVal));
2254 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002255
Chris Lattner75d8f592010-11-21 06:44:42 +00002256 // 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 +00002257 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002258 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002259 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002260 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002261 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002262 ConstantInt::get(X->getType(),
2263 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002264 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002265
Chris Lattner02446fc2010-01-04 07:37:31 +00002266 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002267 }
2268 case ICmpInst::ICMP_NE: {
Chris Lattner02446fc2010-01-04 07:37:31 +00002269 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002270 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002271
Chris Lattner75d8f592010-11-21 06:44:42 +00002272 // If all bits are known zero except for one, then we know at most one
2273 // bit is set. If the comparison is against zero, then this is a check
2274 // to see if *that* bit is set.
2275 APInt Op0KnownZeroInverted = ~Op0KnownZero;
2276 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2277 // If the LHS is an AND with the same constant, look through it.
2278 Value *LHS = 0;
2279 ConstantInt *LHSC = 0;
2280 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2281 LHSC->getValue() != Op0KnownZeroInverted)
2282 LHS = Op0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002283
Chris Lattner75d8f592010-11-21 06:44:42 +00002284 // 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 +00002285 // then turn "((1 << x)&8) != 0" into "x == 3".
Chris Lattner75d8f592010-11-21 06:44:42 +00002286 Value *X = 0;
2287 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2288 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
Chris Lattner79b967b2010-11-23 02:42:04 +00002289 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner75d8f592010-11-21 06:44:42 +00002290 ConstantInt::get(X->getType(), CmpVal));
2291 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002292
Chris Lattner75d8f592010-11-21 06:44:42 +00002293 // 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 +00002294 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002295 const APInt *CI;
Chris Lattner75d8f592010-11-21 06:44:42 +00002296 if (Op0KnownZeroInverted == 1 &&
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002297 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattner79b967b2010-11-23 02:42:04 +00002298 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattnerb20c0b52011-02-10 05:23:05 +00002299 ConstantInt::get(X->getType(),
2300 CI->countTrailingZeros()));
Chris Lattner75d8f592010-11-21 06:44:42 +00002301 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002302
Chris Lattner02446fc2010-01-04 07:37:31 +00002303 break;
Chris Lattner75d8f592010-11-21 06:44:42 +00002304 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002305 case ICmpInst::ICMP_ULT:
2306 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002307 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002308 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002309 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002310 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2311 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2312 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2313 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2314 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002315 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002316
2317 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2318 if (CI->isMinValue(true))
2319 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2320 Constant::getAllOnesValue(Op0->getType()));
2321 }
2322 break;
2323 case ICmpInst::ICMP_UGT:
2324 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002325 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002326 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002327 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002328
2329 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2330 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2331 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2332 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2333 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002334 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002335
2336 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2337 if (CI->isMaxValue(true))
2338 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2339 Constant::getNullValue(Op0->getType()));
2340 }
2341 break;
2342 case ICmpInst::ICMP_SLT:
2343 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002344 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002345 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002346 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002347 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2348 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2349 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2350 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2351 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002352 Builder->getInt(CI->getValue()-1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002353 }
2354 break;
2355 case ICmpInst::ICMP_SGT:
2356 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002357 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002358 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002359 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002360
2361 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2362 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2363 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2364 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2365 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszak3facc432013-06-06 20:18:46 +00002366 Builder->getInt(CI->getValue()+1));
Chris Lattner02446fc2010-01-04 07:37:31 +00002367 }
2368 break;
2369 case ICmpInst::ICMP_SGE:
2370 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2371 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002372 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002373 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002374 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002375 break;
2376 case ICmpInst::ICMP_SLE:
2377 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2378 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002379 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002380 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002381 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002382 break;
2383 case ICmpInst::ICMP_UGE:
2384 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2385 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002386 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002387 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002388 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002389 break;
2390 case ICmpInst::ICMP_ULE:
2391 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2392 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002393 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002394 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002395 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner02446fc2010-01-04 07:37:31 +00002396 break;
2397 }
2398
2399 // Turn a signed comparison into an unsigned one if both operands
2400 // are known to have the same sign.
2401 if (I.isSigned() &&
2402 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2403 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2404 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2405 }
2406
2407 // Test if the ICmpInst instruction is used exclusively by a select as
2408 // part of a minimum or maximum operation. If so, refrain from doing
2409 // any other folding. This helps out other analyses which understand
2410 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2411 // and CodeGen. And in this case, at least one of the comparison
2412 // operands has at least one user besides the compare (the select),
2413 // which would often largely negate the benefit of folding anyway.
2414 if (I.hasOneUse())
2415 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2416 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2417 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2418 return 0;
2419
2420 // See if we are doing a comparison between a constant and an instruction that
2421 // can be folded into the comparison.
2422 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002423 // Since the RHS is a ConstantInt (CI), if the left hand side is an
2424 // instruction, see if that instruction also has constants so that the
2425 // instruction can be folded into the icmp
Chris Lattner02446fc2010-01-04 07:37:31 +00002426 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2427 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2428 return Res;
2429 }
2430
2431 // Handle icmp with constant (but not simple integer constant) RHS
2432 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2433 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2434 switch (LHSI->getOpcode()) {
2435 case Instruction::GetElementPtr:
2436 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2437 if (RHSC->isNullValue() &&
2438 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2439 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2440 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2441 break;
2442 case Instruction::PHI:
2443 // Only fold icmp into the PHI if the phi and icmp are in the same
2444 // block. If in the same block, we're encouraging jump threading. If
2445 // not, we are just pessimizing the code by making an i1 phi.
2446 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00002447 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00002448 return NV;
2449 break;
2450 case Instruction::Select: {
2451 // If either operand of the select is a constant, we can fold the
2452 // comparison into the select arms, which will cause one to be
2453 // constant folded and the select turned into a bitwise or.
2454 Value *Op1 = 0, *Op2 = 0;
2455 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2456 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2457 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2458 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2459
2460 // We only want to perform this transformation if it will not lead to
2461 // additional code. This is true if either both sides of the select
2462 // fold to a constant (in which case the icmp is replaced with a select
2463 // which will usually simplify) or this is the only user of the
2464 // select (in which case we are trading a select+icmp for a simpler
2465 // select+icmp).
2466 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2467 if (!Op1)
2468 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2469 RHSC, I.getName());
2470 if (!Op2)
2471 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2472 RHSC, I.getName());
2473 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2474 }
2475 break;
2476 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002477 case Instruction::IntToPtr:
2478 // icmp pred inttoptr(X), null -> icmp pred X, 0
2479 if (RHSC->isNullValue() && TD &&
Chandler Carruthece6c6b2012-11-01 08:07:29 +00002480 TD->getIntPtrType(RHSC->getContext()) ==
Chris Lattner02446fc2010-01-04 07:37:31 +00002481 LHSI->getOperand(0)->getType())
2482 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2483 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2484 break;
2485
2486 case Instruction::Load:
2487 // Try to optimize things like "A[i] > 4" to index computations.
2488 if (GetElementPtrInst *GEP =
2489 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2490 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2491 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2492 !cast<LoadInst>(LHSI)->isVolatile())
2493 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2494 return Res;
2495 }
2496 break;
2497 }
2498 }
2499
2500 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2501 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2502 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2503 return NI;
2504 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2505 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2506 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2507 return NI;
2508
2509 // Test to see if the operands of the icmp are casted versions of other
2510 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
2511 // now.
2512 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002513 if (Op0->getType()->isPointerTy() &&
2514 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002515 // We keep moving the cast from the left operand over to the right
2516 // operand, where it can often be eliminated completely.
2517 Op0 = CI->getOperand(0);
2518
2519 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2520 // so eliminate it as well.
2521 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2522 Op1 = CI2->getOperand(0);
2523
2524 // If Op1 is a constant, we can fold the cast into the constant.
2525 if (Op0->getType() != Op1->getType()) {
2526 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2527 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2528 } else {
2529 // Otherwise, cast the RHS right before the icmp
2530 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2531 }
2532 }
2533 return new ICmpInst(I.getPredicate(), Op0, Op1);
2534 }
2535 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002536
Chris Lattner02446fc2010-01-04 07:37:31 +00002537 if (isa<CastInst>(Op0)) {
2538 // Handle the special case of: icmp (cast bool to X), <cst>
2539 // This comes up when you have code like
2540 // int X = A < B;
2541 // if (X) ...
2542 // For generality, we handle any zero-extension of any operand comparison
2543 // with a constant or another cast from the same type.
2544 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2545 if (Instruction *R = visitICmpInstWithCastAndCast(I))
2546 return R;
2547 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002548
Duncan Sandsa7724332011-02-17 07:46:37 +00002549 // Special logic for binary operators.
2550 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2551 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2552 if (BO0 || BO1) {
2553 CmpInst::Predicate Pred = I.getPredicate();
2554 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2555 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2556 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2557 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2558 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2559 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2560 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2561 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2562 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2563
2564 // Analyze the case when either Op0 or Op1 is an add instruction.
2565 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2566 Value *A = 0, *B = 0, *C = 0, *D = 0;
2567 if (BO0 && BO0->getOpcode() == Instruction::Add)
2568 A = BO0->getOperand(0), B = BO0->getOperand(1);
2569 if (BO1 && BO1->getOpcode() == Instruction::Add)
2570 C = BO1->getOperand(0), D = BO1->getOperand(1);
2571
2572 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2573 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2574 return new ICmpInst(Pred, A == Op1 ? B : A,
2575 Constant::getNullValue(Op1->getType()));
2576
2577 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2578 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2579 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2580 C == Op0 ? D : C);
2581
Duncan Sands39a7de72011-02-18 16:25:37 +00002582 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002583 if (A && C && (A == C || A == D || B == C || B == D) &&
2584 NoOp0WrapProblem && NoOp1WrapProblem &&
2585 // Try not to increase register pressure.
2586 BO0->hasOneUse() && BO1->hasOneUse()) {
2587 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsafe45392012-11-16 18:55:49 +00002588 Value *Y, *Z;
2589 if (A == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002590 // C + B == C + D -> B == D
Duncan Sandsafe45392012-11-16 18:55:49 +00002591 Y = B;
2592 Z = D;
2593 } else if (A == D) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002594 // D + B == C + D -> B == C
Duncan Sandsafe45392012-11-16 18:55:49 +00002595 Y = B;
2596 Z = C;
2597 } else if (B == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002598 // A + C == C + D -> A == D
Duncan Sandsafe45392012-11-16 18:55:49 +00002599 Y = A;
2600 Z = D;
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002601 } else {
2602 assert(B == D);
2603 // A + D == C + D -> A == C
Duncan Sandsafe45392012-11-16 18:55:49 +00002604 Y = A;
2605 Z = C;
2606 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002607 return new ICmpInst(Pred, Y, Z);
2608 }
2609
David Majnemer59b11c42013-04-11 20:05:46 +00002610 // icmp slt (X + -1), Y -> icmp sle X, Y
2611 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2612 match(B, m_AllOnes()))
2613 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2614
2615 // icmp sge (X + -1), Y -> icmp sgt X, Y
2616 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2617 match(B, m_AllOnes()))
2618 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2619
2620 // icmp sle (X + 1), Y -> icmp slt X, Y
2621 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2622 match(B, m_One()))
2623 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2624
2625 // icmp sgt (X + 1), Y -> icmp sge X, Y
2626 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2627 match(B, m_One()))
2628 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2629
2630 // if C1 has greater magnitude than C2:
2631 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2632 // s.t. C3 = C1 - C2
2633 //
2634 // if C2 has greater magnitude than C1:
2635 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2636 // s.t. C3 = C2 - C1
2637 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2638 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2639 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2640 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2641 const APInt &AP1 = C1->getValue();
2642 const APInt &AP2 = C2->getValue();
2643 if (AP1.isNegative() == AP2.isNegative()) {
2644 APInt AP1Abs = C1->getValue().abs();
2645 APInt AP2Abs = C2->getValue().abs();
2646 if (AP1Abs.uge(AP2Abs)) {
2647 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2648 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2649 return new ICmpInst(Pred, NewAdd, C);
2650 } else {
2651 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2652 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2653 return new ICmpInst(Pred, A, NewAdd);
2654 }
2655 }
2656 }
2657
2658
Duncan Sandsa7724332011-02-17 07:46:37 +00002659 // Analyze the case when either Op0 or Op1 is a sub instruction.
2660 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2661 A = 0; B = 0; C = 0; D = 0;
2662 if (BO0 && BO0->getOpcode() == Instruction::Sub)
2663 A = BO0->getOperand(0), B = BO0->getOperand(1);
2664 if (BO1 && BO1->getOpcode() == Instruction::Sub)
2665 C = BO1->getOperand(0), D = BO1->getOperand(1);
2666
Duncan Sands39a7de72011-02-18 16:25:37 +00002667 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2668 if (A == Op1 && NoOp0WrapProblem)
2669 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2670
2671 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2672 if (C == Op0 && NoOp1WrapProblem)
2673 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2674
2675 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandsa7724332011-02-17 07:46:37 +00002676 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2677 // Try not to increase register pressure.
2678 BO0->hasOneUse() && BO1->hasOneUse())
2679 return new ICmpInst(Pred, A, C);
2680
Duncan Sands39a7de72011-02-18 16:25:37 +00002681 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2682 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2683 // Try not to increase register pressure.
2684 BO0->hasOneUse() && BO1->hasOneUse())
2685 return new ICmpInst(Pred, D, B);
2686
Nick Lewycky9feda172011-03-05 04:28:48 +00002687 BinaryOperator *SRem = NULL;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002688 // icmp (srem X, Y), Y
Nick Lewycky9feda172011-03-05 04:28:48 +00002689 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2690 Op1 == BO0->getOperand(1))
2691 SRem = BO0;
Nick Lewyckydcf77572011-03-08 06:29:47 +00002692 // icmp Y, (srem X, Y)
Nick Lewycky9feda172011-03-05 04:28:48 +00002693 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2694 Op0 == BO1->getOperand(1))
2695 SRem = BO1;
2696 if (SRem) {
2697 // We don't check hasOneUse to avoid increasing register pressure because
2698 // the value we use is the same value this instruction was already using.
2699 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2700 default: break;
2701 case ICmpInst::ICMP_EQ:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002702 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002703 case ICmpInst::ICMP_NE:
Nick Lewyckyd01f50f2011-03-06 03:36:19 +00002704 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky9feda172011-03-05 04:28:48 +00002705 case ICmpInst::ICMP_SGT:
2706 case ICmpInst::ICMP_SGE:
2707 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2708 Constant::getAllOnesValue(SRem->getType()));
2709 case ICmpInst::ICMP_SLT:
2710 case ICmpInst::ICMP_SLE:
2711 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2712 Constant::getNullValue(SRem->getType()));
2713 }
2714 }
2715
Duncan Sandsa7724332011-02-17 07:46:37 +00002716 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2717 BO0->hasOneUse() && BO1->hasOneUse() &&
2718 BO0->getOperand(1) == BO1->getOperand(1)) {
2719 switch (BO0->getOpcode()) {
2720 default: break;
2721 case Instruction::Add:
2722 case Instruction::Sub:
2723 case Instruction::Xor:
2724 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
2725 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2726 BO1->getOperand(0));
2727 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2728 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2729 if (CI->getValue().isSignBit()) {
2730 ICmpInst::Predicate Pred = I.isSigned()
2731 ? I.getUnsignedPredicate()
2732 : I.getSignedPredicate();
2733 return new ICmpInst(Pred, BO0->getOperand(0),
2734 BO1->getOperand(0));
Chris Lattner02446fc2010-01-04 07:37:31 +00002735 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002736
Chris Lattnerc73b24d2011-07-15 06:08:15 +00002737 if (CI->isMaxValue(true)) {
Duncan Sandsa7724332011-02-17 07:46:37 +00002738 ICmpInst::Predicate Pred = I.isSigned()
2739 ? I.getUnsignedPredicate()
2740 : I.getSignedPredicate();
2741 Pred = I.getSwappedPredicate(Pred);
2742 return new ICmpInst(Pred, BO0->getOperand(0),
2743 BO1->getOperand(0));
2744 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002745 }
Duncan Sandsa7724332011-02-17 07:46:37 +00002746 break;
2747 case Instruction::Mul:
2748 if (!I.isEquality())
2749 break;
2750
2751 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2752 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2753 // Mask = -1 >> count-trailing-zeros(Cst).
2754 if (!CI->isZero() && !CI->isOne()) {
2755 const APInt &AP = CI->getValue();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002756 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandsa7724332011-02-17 07:46:37 +00002757 APInt::getLowBitsSet(AP.getBitWidth(),
2758 AP.getBitWidth() -
2759 AP.countTrailingZeros()));
2760 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2761 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2762 return new ICmpInst(I.getPredicate(), And1, And2);
2763 }
2764 }
2765 break;
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002766 case Instruction::UDiv:
2767 case Instruction::LShr:
2768 if (I.isSigned())
2769 break;
2770 // fall-through
2771 case Instruction::SDiv:
2772 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002773 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002774 break;
2775 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2776 BO1->getOperand(0));
2777 case Instruction::Shl: {
2778 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2779 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2780 if (!NUW && !NSW)
2781 break;
2782 if (!NSW && I.isSigned())
2783 break;
2784 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2785 BO1->getOperand(0));
2786 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002787 }
2788 }
2789 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002790
Chris Lattner02446fc2010-01-04 07:37:31 +00002791 { Value *A, *B;
David Majnemerfb1cd692013-04-12 17:25:07 +00002792 // Transform (A & ~B) == 0 --> (A & B) != 0
2793 // and (A & ~B) != 0 --> (A & B) == 0
2794 // if A is a power of 2.
2795 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2796 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
2797 return new ICmpInst(I.getInversePredicate(),
2798 Builder->CreateAnd(A, B),
2799 Op1);
2800
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002801 // ~x < ~y --> y < x
2802 // ~x < cst --> ~cst < x
2803 if (match(Op0, m_Not(m_Value(A)))) {
2804 if (match(Op1, m_Not(m_Value(B))))
2805 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner27a98482011-01-15 05:42:47 +00002806 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerfdb5b012011-01-15 05:41:33 +00002807 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2808 }
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002809
2810 // (a+b) <u a --> llvm.uadd.with.overflow.
2811 // (a+b) <u b --> llvm.uadd.with.overflow.
2812 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002813 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002814 (Op1 == A || Op1 == B))
2815 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2816 return R;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002817
Chris Lattnere5cbdca2010-12-19 19:37:52 +00002818 // a >u (a+b) --> llvm.uadd.with.overflow.
2819 // b >u (a+b) --> llvm.uadd.with.overflow.
2820 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2821 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2822 (Op0 == A || Op0 == B))
2823 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2824 return R;
Chris Lattner02446fc2010-01-04 07:37:31 +00002825 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002826
Chris Lattner02446fc2010-01-04 07:37:31 +00002827 if (I.isEquality()) {
2828 Value *A, *B, *C, *D;
Duncan Sands39a7de72011-02-18 16:25:37 +00002829
Chris Lattner02446fc2010-01-04 07:37:31 +00002830 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2831 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
2832 Value *OtherVal = A == Op1 ? B : A;
2833 return new ICmpInst(I.getPredicate(), OtherVal,
2834 Constant::getNullValue(A->getType()));
2835 }
2836
2837 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2838 // A^c1 == C^c2 --> A == C^(c1^c2)
2839 ConstantInt *C1, *C2;
2840 if (match(B, m_ConstantInt(C1)) &&
2841 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszak3facc432013-06-06 20:18:46 +00002842 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramera9390a42011-09-27 20:39:19 +00002843 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner02446fc2010-01-04 07:37:31 +00002844 return new ICmpInst(I.getPredicate(), A, Xor);
2845 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002846
Chris Lattner02446fc2010-01-04 07:37:31 +00002847 // A^B == A^D -> B == D
2848 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2849 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2850 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2851 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2852 }
2853 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002854
Chris Lattner02446fc2010-01-04 07:37:31 +00002855 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2856 (A == Op0 || B == Op0)) {
2857 // A == (A^B) -> B == 0
2858 Value *OtherVal = A == Op0 ? B : A;
2859 return new ICmpInst(I.getPredicate(), OtherVal,
2860 Constant::getNullValue(A->getType()));
2861 }
2862
Chris Lattner02446fc2010-01-04 07:37:31 +00002863 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002864 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner5036ce42011-04-26 20:02:45 +00002865 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner02446fc2010-01-04 07:37:31 +00002866 Value *X = 0, *Y = 0, *Z = 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002867
Chris Lattner02446fc2010-01-04 07:37:31 +00002868 if (A == C) {
2869 X = B; Y = D; Z = A;
2870 } else if (A == D) {
2871 X = B; Y = C; Z = A;
2872 } else if (B == C) {
2873 X = A; Y = D; Z = B;
2874 } else if (B == D) {
2875 X = A; Y = C; Z = B;
2876 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002877
Chris Lattner02446fc2010-01-04 07:37:31 +00002878 if (X) { // Build (X^Y) & Z
Benjamin Kramera9390a42011-09-27 20:39:19 +00002879 Op1 = Builder->CreateXor(X, Y);
2880 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner02446fc2010-01-04 07:37:31 +00002881 I.setOperand(0, Op1);
2882 I.setOperand(1, Constant::getNullValue(Op1->getType()));
2883 return &I;
2884 }
2885 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002886
Benjamin Kramer66821d92012-06-10 20:35:00 +00002887 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002888 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer66821d92012-06-10 20:35:00 +00002889 ConstantInt *Cst1;
Benjamin Kramer7a99b462012-06-11 08:01:25 +00002890 if ((Op0->hasOneUse() &&
2891 match(Op0, m_ZExt(m_Value(A))) &&
2892 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2893 (Op1->hasOneUse() &&
2894 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2895 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer66821d92012-06-10 20:35:00 +00002896 APInt Pow2 = Cst1->getValue() + 1;
2897 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2898 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2899 return new ICmpInst(I.getPredicate(), A,
2900 Builder->CreateTrunc(B, A->getType()));
2901 }
2902
Chris Lattner325eeb12011-04-26 20:18:20 +00002903 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2904 // "icmp (and X, mask), cst"
2905 uint64_t ShAmt = 0;
Chris Lattner325eeb12011-04-26 20:18:20 +00002906 if (Op0->hasOneUse() &&
2907 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2908 m_ConstantInt(ShAmt))))) &&
2909 match(Op1, m_ConstantInt(Cst1)) &&
2910 // Only do this when A has multiple uses. This is most important to do
2911 // when it exposes other optimizations.
2912 !A->hasOneUse()) {
2913 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002914
Chris Lattner325eeb12011-04-26 20:18:20 +00002915 if (ShAmt < ASize) {
2916 APInt MaskV =
2917 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2918 MaskV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002919
Chris Lattner325eeb12011-04-26 20:18:20 +00002920 APInt CmpV = Cst1->getValue().zext(ASize);
2921 CmpV <<= ShAmt;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002922
Chris Lattner325eeb12011-04-26 20:18:20 +00002923 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2924 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2925 }
2926 }
Chris Lattner02446fc2010-01-04 07:37:31 +00002927 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002928
Chris Lattner02446fc2010-01-04 07:37:31 +00002929 {
2930 Value *X; ConstantInt *Cst;
2931 // icmp X+Cst, X
2932 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
2933 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
2934
2935 // icmp X, X+Cst
2936 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
2937 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
2938 }
2939 return Changed ? &I : 0;
2940}
2941
2942
2943
2944
2945
2946
2947/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
2948///
2949Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
2950 Instruction *LHSI,
2951 Constant *RHSC) {
2952 if (!isa<ConstantFP>(RHSC)) return 0;
2953 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002954
Chris Lattner02446fc2010-01-04 07:37:31 +00002955 // Get the width of the mantissa. We don't want to hack on conversions that
2956 // might lose information from the integer, e.g. "i64 -> float"
2957 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
2958 if (MantissaWidth == -1) return 0; // Unknown.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002959
Chris Lattner02446fc2010-01-04 07:37:31 +00002960 // Check to see that the input is converted from an integer type that is small
2961 // enough that preserves all bits. TODO: check here for "known" sign bits.
2962 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
2963 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002964
Chris Lattner02446fc2010-01-04 07:37:31 +00002965 // If this is a uitofp instruction, we need an extra bit to hold the sign.
2966 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
2967 if (LHSUnsigned)
2968 ++InputSize;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002969
Chris Lattner02446fc2010-01-04 07:37:31 +00002970 // If the conversion would lose info, don't hack on this.
2971 if ((int)InputSize > MantissaWidth)
2972 return 0;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002973
Chris Lattner02446fc2010-01-04 07:37:31 +00002974 // Otherwise, we can potentially simplify the comparison. We know that it
2975 // will always come through as an integer value and we know the constant is
2976 // not a NAN (it would have been previously simplified).
2977 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach0cc4a952011-09-30 18:09:53 +00002978
Chris Lattner02446fc2010-01-04 07:37:31 +00002979 ICmpInst::Predicate Pred;
2980 switch (I.getPredicate()) {
2981 default: llvm_unreachable("Unexpected predicate!");
2982 case FCmpInst::FCMP_UEQ:
2983 case FCmpInst::FCMP_OEQ:
2984 Pred = ICmpInst::ICMP_EQ;
2985 break;
2986 case FCmpInst::FCMP_UGT:
2987 case FCmpInst::FCMP_OGT:
2988 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
2989 break;
2990 case FCmpInst::FCMP_UGE:
2991 case FCmpInst::FCMP_OGE:
2992 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
2993 break;
2994 case FCmpInst::FCMP_ULT:
2995 case FCmpInst::FCMP_OLT:
2996 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
2997 break;
2998 case FCmpInst::FCMP_ULE:
2999 case FCmpInst::FCMP_OLE:
3000 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3001 break;
3002 case FCmpInst::FCMP_UNE:
3003 case FCmpInst::FCMP_ONE:
3004 Pred = ICmpInst::ICMP_NE;
3005 break;
3006 case FCmpInst::FCMP_ORD:
Jakub Staszak3facc432013-06-06 20:18:46 +00003007 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003008 case FCmpInst::FCMP_UNO:
Jakub Staszak3facc432013-06-06 20:18:46 +00003009 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003010 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003011
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003012 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003013
Chris Lattner02446fc2010-01-04 07:37:31 +00003014 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003015
Chris Lattner02446fc2010-01-04 07:37:31 +00003016 // See if the FP constant is too large for the integer. For example,
3017 // comparing an i8 to 300.0.
3018 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003019
Chris Lattner02446fc2010-01-04 07:37:31 +00003020 if (!LHSUnsigned) {
3021 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3022 // and large values.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003023 APFloat SMax(RHS.getSemantics());
Chris Lattner02446fc2010-01-04 07:37:31 +00003024 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3025 APFloat::rmNearestTiesToEven);
3026 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3027 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3028 Pred == ICmpInst::ICMP_SLE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003029 return ReplaceInstUsesWith(I, Builder->getTrue());
3030 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003031 }
3032 } else {
3033 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3034 // +INF and large values.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003035 APFloat UMax(RHS.getSemantics());
Chris Lattner02446fc2010-01-04 07:37:31 +00003036 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3037 APFloat::rmNearestTiesToEven);
3038 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3039 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3040 Pred == ICmpInst::ICMP_ULE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003041 return ReplaceInstUsesWith(I, Builder->getTrue());
3042 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003043 }
3044 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003045
Chris Lattner02446fc2010-01-04 07:37:31 +00003046 if (!LHSUnsigned) {
3047 // See if the RHS value is < SignedMin.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003048 APFloat SMin(RHS.getSemantics());
Chris Lattner02446fc2010-01-04 07:37:31 +00003049 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3050 APFloat::rmNearestTiesToEven);
3051 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3052 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3053 Pred == ICmpInst::ICMP_SGE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003054 return ReplaceInstUsesWith(I, Builder->getTrue());
3055 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003056 }
Devang Patela2e0f6b2012-02-13 23:05:18 +00003057 } else {
3058 // See if the RHS value is < UnsignedMin.
Michael Gottesman4dfc2572013-06-27 21:58:19 +00003059 APFloat SMin(RHS.getSemantics());
Devang Patela2e0f6b2012-02-13 23:05:18 +00003060 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3061 APFloat::rmNearestTiesToEven);
3062 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3063 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3064 Pred == ICmpInst::ICMP_UGE)
Jakub Staszak3facc432013-06-06 20:18:46 +00003065 return ReplaceInstUsesWith(I, Builder->getTrue());
3066 return ReplaceInstUsesWith(I, Builder->getFalse());
Devang Patela2e0f6b2012-02-13 23:05:18 +00003067 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003068 }
3069
3070 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3071 // [0, UMAX], but it may still be fractional. See if it is fractional by
3072 // casting the FP value to the integer value and back, checking for equality.
3073 // Don't do this for zero, because -0.0 is not fractional.
3074 Constant *RHSInt = LHSUnsigned
3075 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3076 : ConstantExpr::getFPToSI(RHSC, IntTy);
3077 if (!RHS.isZero()) {
3078 bool Equal = LHSUnsigned
3079 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3080 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3081 if (!Equal) {
3082 // If we had a comparison against a fractional value, we have to adjust
3083 // the compare predicate and sometimes the value. RHSC is rounded towards
3084 // zero at this point.
3085 switch (Pred) {
3086 default: llvm_unreachable("Unexpected integer comparison!");
3087 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Jakub Staszak3facc432013-06-06 20:18:46 +00003088 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003089 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Jakub Staszak3facc432013-06-06 20:18:46 +00003090 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003091 case ICmpInst::ICMP_ULE:
3092 // (float)int <= 4.4 --> int <= 4
3093 // (float)int <= -4.4 --> false
3094 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003095 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003096 break;
3097 case ICmpInst::ICMP_SLE:
3098 // (float)int <= 4.4 --> int <= 4
3099 // (float)int <= -4.4 --> int < -4
3100 if (RHS.isNegative())
3101 Pred = ICmpInst::ICMP_SLT;
3102 break;
3103 case ICmpInst::ICMP_ULT:
3104 // (float)int < -4.4 --> false
3105 // (float)int < 4.4 --> int <= 4
3106 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003107 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner02446fc2010-01-04 07:37:31 +00003108 Pred = ICmpInst::ICMP_ULE;
3109 break;
3110 case ICmpInst::ICMP_SLT:
3111 // (float)int < -4.4 --> int < -4
3112 // (float)int < 4.4 --> int <= 4
3113 if (!RHS.isNegative())
3114 Pred = ICmpInst::ICMP_SLE;
3115 break;
3116 case ICmpInst::ICMP_UGT:
3117 // (float)int > 4.4 --> int > 4
3118 // (float)int > -4.4 --> true
3119 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003120 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003121 break;
3122 case ICmpInst::ICMP_SGT:
3123 // (float)int > 4.4 --> int > 4
3124 // (float)int > -4.4 --> int >= -4
3125 if (RHS.isNegative())
3126 Pred = ICmpInst::ICMP_SGE;
3127 break;
3128 case ICmpInst::ICMP_UGE:
3129 // (float)int >= -4.4 --> true
3130 // (float)int >= 4.4 --> int > 4
Bob Wilsonf12c95a2012-08-07 22:35:16 +00003131 if (RHS.isNegative())
Jakub Staszak3facc432013-06-06 20:18:46 +00003132 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner02446fc2010-01-04 07:37:31 +00003133 Pred = ICmpInst::ICMP_UGT;
3134 break;
3135 case ICmpInst::ICMP_SGE:
3136 // (float)int >= -4.4 --> int >= -4
3137 // (float)int >= 4.4 --> int > 4
3138 if (!RHS.isNegative())
3139 Pred = ICmpInst::ICMP_SGT;
3140 break;
3141 }
3142 }
3143 }
3144
3145 // Lower this FP comparison into an appropriate integer version of the
3146 // comparison.
3147 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3148}
3149
3150Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3151 bool Changed = false;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003152
Chris Lattner02446fc2010-01-04 07:37:31 +00003153 /// Orders the operands of the compare so that they are listed from most
3154 /// complex to least complex. This puts constants before unary operators,
3155 /// before binary operators.
3156 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3157 I.swapOperands();
3158 Changed = true;
3159 }
3160
3161 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003162
Chris Lattner02446fc2010-01-04 07:37:31 +00003163 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
3164 return ReplaceInstUsesWith(I, V);
3165
3166 // Simplify 'fcmp pred X, X'
3167 if (Op0 == Op1) {
3168 switch (I.getPredicate()) {
3169 default: llvm_unreachable("Unknown predicate!");
3170 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3171 case FCmpInst::FCMP_ULT: // True if unordered or less than
3172 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3173 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3174 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3175 I.setPredicate(FCmpInst::FCMP_UNO);
3176 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3177 return &I;
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003178
Chris Lattner02446fc2010-01-04 07:37:31 +00003179 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
3180 case FCmpInst::FCMP_OEQ: // True if ordered and equal
3181 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
3182 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
3183 // Canonicalize these to be 'fcmp ord %X, 0.0'.
3184 I.setPredicate(FCmpInst::FCMP_ORD);
3185 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3186 return &I;
3187 }
3188 }
Jim Grosbach0cc4a952011-09-30 18:09:53 +00003189
Chris Lattner02446fc2010-01-04 07:37:31 +00003190 // Handle fcmp with constant RHS
3191 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3192 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3193 switch (LHSI->getOpcode()) {
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003194 case Instruction::FPExt: {
3195 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3196 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3197 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3198 if (!RHSF)
3199 break;
3200
3201 const fltSemantics *Sem;
3202 // FIXME: This shouldn't be here.
Dan Gohmance163392011-12-17 00:04:22 +00003203 if (LHSExt->getSrcTy()->isHalfTy())
3204 Sem = &APFloat::IEEEhalf;
3205 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003206 Sem = &APFloat::IEEEsingle;
3207 else if (LHSExt->getSrcTy()->isDoubleTy())
3208 Sem = &APFloat::IEEEdouble;
3209 else if (LHSExt->getSrcTy()->isFP128Ty())
3210 Sem = &APFloat::IEEEquad;
3211 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3212 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand3467b9f2012-10-30 12:33:18 +00003213 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3214 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003215 else
3216 break;
3217
3218 bool Lossy;
3219 APFloat F = RHSF->getValueAPF();
3220 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3221
Jim Grosbachcbf676b2011-09-30 18:45:50 +00003222 // Avoid lossy conversions and denormals. Zero is a special case
3223 // that's OK to convert.
Jim Grosbach68e05fb2011-09-30 19:58:46 +00003224 APFloat Fabs = F;
3225 Fabs.clearSign();
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003226 if (!Lossy &&
Jim Grosbach68e05fb2011-09-30 19:58:46 +00003227 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3228 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbachcbf676b2011-09-30 18:45:50 +00003229
Benjamin Kramerb194bdc2011-03-31 10:12:07 +00003230 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3231 ConstantFP::get(RHSC->getContext(), F));
3232 break;
3233 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003234 case Instruction::PHI:
3235 // Only fold fcmp into the PHI if the phi and fcmp are in the same
3236 // block. If in the same block, we're encouraging jump threading. If
3237 // not, we are just pessimizing the code by making an i1 phi.
3238 if (LHSI->getParent() == I.getParent())
Chris Lattner9922ccf2011-01-16 05:14:26 +00003239 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner02446fc2010-01-04 07:37:31 +00003240 return NV;
3241 break;
3242 case Instruction::SIToFP:
3243 case Instruction::UIToFP:
3244 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3245 return NV;
3246 break;
3247 case Instruction::Select: {
3248 // If either operand of the select is a constant, we can fold the
3249 // comparison into the select arms, which will cause one to be
3250 // constant folded and the select turned into a bitwise or.
3251 Value *Op1 = 0, *Op2 = 0;
3252 if (LHSI->hasOneUse()) {
3253 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3254 // Fold the known value into the constant operand.
3255 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3256 // Insert a new FCmp of the other select operand.
3257 Op2 = Builder->CreateFCmp(I.getPredicate(),
3258 LHSI->getOperand(2), RHSC, I.getName());
3259 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3260 // Fold the known value into the constant operand.
3261 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3262 // Insert a new FCmp of the other select operand.
3263 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3264 RHSC, I.getName());
3265 }
3266 }
3267
3268 if (Op1)
3269 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3270 break;
3271 }
Benjamin Kramer0db50182011-03-31 10:12:15 +00003272 case Instruction::FSub: {
3273 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3274 Value *Op;
3275 if (match(LHSI, m_FNeg(m_Value(Op))))
3276 return new FCmpInst(I.getSwappedPredicate(), Op,
3277 ConstantExpr::getFNeg(RHSC));
3278 break;
3279 }
Dan Gohman39516a62010-02-24 06:46:09 +00003280 case Instruction::Load:
3281 if (GetElementPtrInst *GEP =
3282 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3283 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3284 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3285 !cast<LoadInst>(LHSI)->isVolatile())
3286 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3287 return Res;
3288 }
3289 break;
Benjamin Kramer00abcd32012-08-18 20:06:47 +00003290 case Instruction::Call: {
3291 CallInst *CI = cast<CallInst>(LHSI);
3292 LibFunc::Func Func;
3293 // Various optimization for fabs compared with zero.
Benjamin Kramera4b57172012-08-18 22:04:34 +00003294 if (RHSC->isNullValue() && CI->getCalledFunction() &&
Benjamin Kramer00abcd32012-08-18 20:06:47 +00003295 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3296 TLI->has(Func)) {
3297 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3298 Func == LibFunc::fabsl) {
3299 switch (I.getPredicate()) {
3300 default: break;
3301 // fabs(x) < 0 --> false
3302 case FCmpInst::FCMP_OLT:
3303 return ReplaceInstUsesWith(I, Builder->getFalse());
3304 // fabs(x) > 0 --> x != 0
3305 case FCmpInst::FCMP_OGT:
3306 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3307 RHSC);
3308 // fabs(x) <= 0 --> x == 0
3309 case FCmpInst::FCMP_OLE:
3310 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3311 RHSC);
3312 // fabs(x) >= 0 --> !isnan(x)
3313 case FCmpInst::FCMP_OGE:
3314 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3315 RHSC);
3316 // fabs(x) == 0 --> x == 0
3317 // fabs(x) != 0 --> x != 0
3318 case FCmpInst::FCMP_OEQ:
3319 case FCmpInst::FCMP_UEQ:
3320 case FCmpInst::FCMP_ONE:
3321 case FCmpInst::FCMP_UNE:
3322 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3323 RHSC);
3324 }
3325 }
3326 }
3327 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003328 }
Chris Lattner02446fc2010-01-04 07:37:31 +00003329 }
3330
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003331 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003332 Value *X, *Y;
3333 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramer00e00d62011-03-31 10:46:03 +00003334 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramer68b4bd02011-03-31 10:12:22 +00003335
Benjamin Kramercd0274c2011-03-31 10:11:58 +00003336 // fcmp (fpext x), (fpext y) -> fcmp x, y
3337 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3338 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3339 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3340 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3341 RHSExt->getOperand(0));
3342
Chris Lattner02446fc2010-01-04 07:37:31 +00003343 return Changed ? &I : 0;
3344}