blob: e960b1bf05e702a814b9969a0e33fe9eae049821 [file] [log] [blame]
Chris Lattner2188e402010-01-04 07:37:31 +00001//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitICmp and visitFCmp functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Matt Arsenault55e73122015-01-06 15:50:59 +000015#include "llvm/ADT/APSInt.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000016#include "llvm/ADT/Statistic.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000017#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000018#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000020#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000022#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000024#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000027#include "llvm/Analysis/TargetLibraryInfo.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000028
Chris Lattner2188e402010-01-04 07:37:31 +000029using namespace llvm;
30using namespace PatternMatch;
31
Chandler Carruth964daaa2014-04-22 02:55:47 +000032#define DEBUG_TYPE "instcombine"
33
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000034// How many times is a select replaced by one of its operands?
35STATISTIC(NumSel, "Number of select opts");
36
37// Initialization Routines
38
Chris Lattner98457102011-02-10 05:23:05 +000039static ConstantInt *getOne(Constant *C) {
40 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
41}
42
Chris Lattner2188e402010-01-04 07:37:31 +000043static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
44 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
45}
46
47static bool HasAddOverflow(ConstantInt *Result,
48 ConstantInt *In1, ConstantInt *In2,
49 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000050 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000051 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000052
53 if (In2->isNegative())
54 return Result->getValue().sgt(In1->getValue());
55 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000056}
57
58/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
59/// overflowed for this type.
60static bool AddWithOverflow(Constant *&Result, Constant *In1,
61 Constant *In2, bool IsSigned = false) {
62 Result = ConstantExpr::getAdd(In1, In2);
63
Chris Lattner229907c2011-07-18 04:54:35 +000064 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000065 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
66 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
67 if (HasAddOverflow(ExtractElement(Result, Idx),
68 ExtractElement(In1, Idx),
69 ExtractElement(In2, Idx),
70 IsSigned))
71 return true;
72 }
73 return false;
74 }
75
76 return HasAddOverflow(cast<ConstantInt>(Result),
77 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
78 IsSigned);
79}
80
81static bool HasSubOverflow(ConstantInt *Result,
82 ConstantInt *In1, ConstantInt *In2,
83 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000084 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000085 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000086
Chris Lattnerb1a15122011-07-15 06:08:15 +000087 if (In2->isNegative())
88 return Result->getValue().slt(In1->getValue());
89
90 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000091}
92
93/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
94/// overflowed for this type.
95static bool SubWithOverflow(Constant *&Result, Constant *In1,
96 Constant *In2, bool IsSigned = false) {
97 Result = ConstantExpr::getSub(In1, In2);
98
Chris Lattner229907c2011-07-18 04:54:35 +000099 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +0000100 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
101 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
102 if (HasSubOverflow(ExtractElement(Result, Idx),
103 ExtractElement(In1, Idx),
104 ExtractElement(In2, Idx),
105 IsSigned))
106 return true;
107 }
108 return false;
109 }
110
111 return HasSubOverflow(cast<ConstantInt>(Result),
112 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
113 IsSigned);
114}
115
116/// isSignBitCheck - Given an exploded icmp instruction, return true if the
117/// comparison only checks the sign bit. If it only checks the sign bit, set
118/// TrueIfSigned if the result of the comparison is true when the input value is
119/// signed.
120static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
121 bool &TrueIfSigned) {
122 switch (pred) {
123 case ICmpInst::ICMP_SLT: // True if LHS s< 0
124 TrueIfSigned = true;
125 return RHS->isZero();
126 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
127 TrueIfSigned = true;
128 return RHS->isAllOnesValue();
129 case ICmpInst::ICMP_SGT: // True if LHS s> -1
130 TrueIfSigned = false;
131 return RHS->isAllOnesValue();
132 case ICmpInst::ICMP_UGT:
133 // True if LHS u> RHS and RHS == high-bit-mask - 1
134 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000135 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000136 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000137 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
138 TrueIfSigned = true;
139 return RHS->getValue().isSignBit();
140 default:
141 return false;
142 }
143}
144
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000145/// Returns true if the exploded icmp can be expressed as a signed comparison
146/// to zero and updates the predicate accordingly.
147/// The signedness of the comparison is preserved.
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000148static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
149 if (!ICmpInst::isSigned(pred))
150 return false;
151
152 if (RHS->isZero())
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000153 return ICmpInst::isRelational(pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000154
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000155 if (RHS->isOne()) {
156 if (pred == ICmpInst::ICMP_SLT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000157 pred = ICmpInst::ICMP_SLE;
158 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000159 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000160 } else if (RHS->isAllOnesValue()) {
161 if (pred == ICmpInst::ICMP_SGT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000162 pred = ICmpInst::ICMP_SGE;
163 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000164 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000165 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000166
167 return false;
168}
169
Chris Lattner2188e402010-01-04 07:37:31 +0000170// isHighOnes - Return true if the constant is of the form 1+0+.
171// This is the same as lowones(~X).
172static bool isHighOnes(const ConstantInt *CI) {
173 return (~CI->getValue() + 1).isPowerOf2();
174}
175
Jim Grosbach129c52a2011-09-30 18:09:53 +0000176/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner2188e402010-01-04 07:37:31 +0000177/// set of known zero and one bits, compute the maximum and minimum values that
178/// could have the specified known zero and known one bits, returning them in
179/// min/max.
180static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
181 const APInt& KnownOne,
182 APInt& Min, APInt& Max) {
183 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
184 KnownZero.getBitWidth() == Min.getBitWidth() &&
185 KnownZero.getBitWidth() == Max.getBitWidth() &&
186 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
187 APInt UnknownBits = ~(KnownZero|KnownOne);
188
189 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
190 // bit if it is unknown.
191 Min = KnownOne;
192 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000193
Chris Lattner2188e402010-01-04 07:37:31 +0000194 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000195 Min.setBit(Min.getBitWidth()-1);
196 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000197 }
198}
199
200// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
201// a set of known zero and one bits, compute the maximum and minimum values that
202// could have the specified known zero and known one bits, returning them in
203// min/max.
204static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
205 const APInt &KnownOne,
206 APInt &Min, APInt &Max) {
207 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
208 KnownZero.getBitWidth() == Min.getBitWidth() &&
209 KnownZero.getBitWidth() == Max.getBitWidth() &&
210 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
211 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000212
Chris Lattner2188e402010-01-04 07:37:31 +0000213 // The minimum value is when the unknown bits are all zeros.
214 Min = KnownOne;
215 // The maximum value is when the unknown bits are all ones.
216 Max = KnownOne|UnknownBits;
217}
218
Chris Lattner2188e402010-01-04 07:37:31 +0000219/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
220/// cmp pred (load (gep GV, ...)), cmpcst
221/// where GV is a global variable with a constant initializer. Try to simplify
222/// this into some simple computation that does not need the load. For example
223/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
224///
225/// If AndCst is non-null, then the loaded value is masked with that constant
226/// before doing the comparison. This handles cases like "A[i]&4 == 0".
227Instruction *InstCombiner::
228FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
229 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000230 Constant *Init = GV->getInitializer();
231 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000232 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000233
Chris Lattnerfe741762012-01-31 02:55:06 +0000234 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000235 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000236
Chris Lattner2188e402010-01-04 07:37:31 +0000237 // There are many forms of this optimization we can handle, for now, just do
238 // the simple index into a single-dimensional array.
239 //
240 // Require: GEP GV, 0, i {{, constant indices}}
241 if (GEP->getNumOperands() < 3 ||
242 !isa<ConstantInt>(GEP->getOperand(1)) ||
243 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
244 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000245 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000246
247 // Check that indices after the variable are constants and in-range for the
248 // type they index. Collect the indices. This is typically for arrays of
249 // structs.
250 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000251
Chris Lattnerfe741762012-01-31 02:55:06 +0000252 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000253 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
254 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000255 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000256
Chris Lattner2188e402010-01-04 07:37:31 +0000257 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000258 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000259
Chris Lattner229907c2011-07-18 04:54:35 +0000260 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000261 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000262 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000263 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000264 EltTy = ATy->getElementType();
265 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000266 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000267 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000268
Chris Lattner2188e402010-01-04 07:37:31 +0000269 LaterIndices.push_back(IdxVal);
270 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000271
Chris Lattner2188e402010-01-04 07:37:31 +0000272 enum { Overdefined = -3, Undefined = -2 };
273
274 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000275
Chris Lattner2188e402010-01-04 07:37:31 +0000276 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
277 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
278 // and 87 is the second (and last) index. FirstTrueElement is -2 when
279 // undefined, otherwise set to the first true element. SecondTrueElement is
280 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
281 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
282
283 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
284 // form "i != 47 & i != 87". Same state transitions as for true elements.
285 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000286
Chris Lattner2188e402010-01-04 07:37:31 +0000287 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
288 /// define a state machine that triggers for ranges of values that the index
289 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
290 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
291 /// index in the range (inclusive). We use -2 for undefined here because we
292 /// use relative comparisons and don't want 0-1 to match -1.
293 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000294
Chris Lattner2188e402010-01-04 07:37:31 +0000295 // MagicBitvector - This is a magic bitvector where we set a bit if the
296 // comparison is true for element 'i'. If there are 64 elements or less in
297 // the array, this will fully represent all the comparison results.
298 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000299
Chris Lattner2188e402010-01-04 07:37:31 +0000300 // Scan the array and see if one of our patterns matches.
301 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000302 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
303 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000304 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000305
Chris Lattner2188e402010-01-04 07:37:31 +0000306 // If this is indexing an array of structures, get the structure element.
307 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000308 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000309
Chris Lattner2188e402010-01-04 07:37:31 +0000310 // If the element is masked, handle it.
311 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000312
Chris Lattner2188e402010-01-04 07:37:31 +0000313 // Find out if the comparison would be true or false for the i'th element.
314 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000315 CompareRHS, DL, TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000316 // If the result is undef for this element, ignore it.
317 if (isa<UndefValue>(C)) {
318 // Extend range state machines to cover this element in case there is an
319 // undef in the middle of the range.
320 if (TrueRangeEnd == (int)i-1)
321 TrueRangeEnd = i;
322 if (FalseRangeEnd == (int)i-1)
323 FalseRangeEnd = i;
324 continue;
325 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000326
Chris Lattner2188e402010-01-04 07:37:31 +0000327 // If we can't compute the result for any of the elements, we have to give
328 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000329 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000330
Chris Lattner2188e402010-01-04 07:37:31 +0000331 // Otherwise, we know if the comparison is true or false for this element,
332 // update our state machines.
333 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000334
Chris Lattner2188e402010-01-04 07:37:31 +0000335 // State machine for single/double/range index comparison.
336 if (IsTrueForElt) {
337 // Update the TrueElement state machine.
338 if (FirstTrueElement == Undefined)
339 FirstTrueElement = TrueRangeEnd = i; // First true element.
340 else {
341 // Update double-compare state machine.
342 if (SecondTrueElement == Undefined)
343 SecondTrueElement = i;
344 else
345 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000346
Chris Lattner2188e402010-01-04 07:37:31 +0000347 // Update range state machine.
348 if (TrueRangeEnd == (int)i-1)
349 TrueRangeEnd = i;
350 else
351 TrueRangeEnd = Overdefined;
352 }
353 } else {
354 // Update the FalseElement state machine.
355 if (FirstFalseElement == Undefined)
356 FirstFalseElement = FalseRangeEnd = i; // First false element.
357 else {
358 // Update double-compare state machine.
359 if (SecondFalseElement == Undefined)
360 SecondFalseElement = i;
361 else
362 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000363
Chris Lattner2188e402010-01-04 07:37:31 +0000364 // Update range state machine.
365 if (FalseRangeEnd == (int)i-1)
366 FalseRangeEnd = i;
367 else
368 FalseRangeEnd = Overdefined;
369 }
370 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000371
Chris Lattner2188e402010-01-04 07:37:31 +0000372 // If this element is in range, update our magic bitvector.
373 if (i < 64 && IsTrueForElt)
374 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000375
Chris Lattner2188e402010-01-04 07:37:31 +0000376 // If all of our states become overdefined, bail out early. Since the
377 // predicate is expensive, only check it every 8 elements. This is only
378 // really useful for really huge arrays.
379 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
380 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
381 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000382 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000383 }
384
385 // Now that we've scanned the entire array, emit our new comparison(s). We
386 // order the state machines in complexity of the generated code.
387 Value *Idx = GEP->getOperand(2);
388
Matt Arsenault5aeae182013-08-19 21:40:31 +0000389 // If the index is larger than the pointer size of the target, truncate the
390 // index down like the GEP would do implicitly. We don't have to do this for
391 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000392 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000393 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000394 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
395 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
396 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
397 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000398
Chris Lattner2188e402010-01-04 07:37:31 +0000399 // If the comparison is only true for one or two elements, emit direct
400 // comparisons.
401 if (SecondTrueElement != Overdefined) {
402 // None true -> false.
403 if (FirstTrueElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000404 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000405
Chris Lattner2188e402010-01-04 07:37:31 +0000406 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000407
Chris Lattner2188e402010-01-04 07:37:31 +0000408 // True for one element -> 'i == 47'.
409 if (SecondTrueElement == Undefined)
410 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000411
Chris Lattner2188e402010-01-04 07:37:31 +0000412 // True for two elements -> 'i == 47 | i == 72'.
413 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
414 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
415 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
416 return BinaryOperator::CreateOr(C1, C2);
417 }
418
419 // If the comparison is only false for one or two elements, emit direct
420 // comparisons.
421 if (SecondFalseElement != Overdefined) {
422 // None false -> true.
423 if (FirstFalseElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000424 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000425
Chris Lattner2188e402010-01-04 07:37:31 +0000426 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
427
428 // False for one element -> 'i != 47'.
429 if (SecondFalseElement == Undefined)
430 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000431
Chris Lattner2188e402010-01-04 07:37:31 +0000432 // False for two elements -> 'i != 47 & i != 72'.
433 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
434 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
435 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
436 return BinaryOperator::CreateAnd(C1, C2);
437 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000438
Chris Lattner2188e402010-01-04 07:37:31 +0000439 // If the comparison can be replaced with a range comparison for the elements
440 // where it is true, emit the range check.
441 if (TrueRangeEnd != Overdefined) {
442 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000443
Chris Lattner2188e402010-01-04 07:37:31 +0000444 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
445 if (FirstTrueElement) {
446 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
447 Idx = Builder->CreateAdd(Idx, Offs);
448 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000449
Chris Lattner2188e402010-01-04 07:37:31 +0000450 Value *End = ConstantInt::get(Idx->getType(),
451 TrueRangeEnd-FirstTrueElement+1);
452 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
453 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000454
Chris Lattner2188e402010-01-04 07:37:31 +0000455 // False range check.
456 if (FalseRangeEnd != Overdefined) {
457 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
458 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
459 if (FirstFalseElement) {
460 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
461 Idx = Builder->CreateAdd(Idx, Offs);
462 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000463
Chris Lattner2188e402010-01-04 07:37:31 +0000464 Value *End = ConstantInt::get(Idx->getType(),
465 FalseRangeEnd-FirstFalseElement);
466 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
467 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000468
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000469 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000470 // of this load, replace it with computation that does:
471 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000472 {
Craig Topperf40110f2014-04-25 05:29:35 +0000473 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000474
475 // Look for an appropriate type:
476 // - The type of Idx if the magic fits
477 // - The smallest fitting legal type if we have a DataLayout
478 // - Default to i32
479 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
480 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000481 else
482 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000483
Craig Topperf40110f2014-04-25 05:29:35 +0000484 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000485 Value *V = Builder->CreateIntCast(Idx, Ty, false);
486 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
487 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
488 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
489 }
Chris Lattner2188e402010-01-04 07:37:31 +0000490 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000491
Craig Topperf40110f2014-04-25 05:29:35 +0000492 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000493}
494
Chris Lattner2188e402010-01-04 07:37:31 +0000495/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
496/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
497/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
498/// be complex, and scales are involved. The above expression would also be
499/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
500/// This later form is less amenable to optimization though, and we are allowed
501/// to generate the first by knowing that pointer arithmetic doesn't overflow.
502///
503/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000504///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000505static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
506 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000507 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000508
Chris Lattner2188e402010-01-04 07:37:31 +0000509 // Check to see if this gep only has a single variable index. If so, and if
510 // any constant indices are a multiple of its scale, then we can compute this
511 // in terms of the scale of the variable index. For example, if the GEP
512 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
513 // because the expression will cross zero at the same point.
514 unsigned i, e = GEP->getNumOperands();
515 int64_t Offset = 0;
516 for (i = 1; i != e; ++i, ++GTI) {
517 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
518 // Compute the aggregate offset of constant indices.
519 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000520
Chris Lattner2188e402010-01-04 07:37:31 +0000521 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000522 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000523 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000524 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000525 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000526 Offset += Size*CI->getSExtValue();
527 }
528 } else {
529 // Found our variable index.
530 break;
531 }
532 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000533
Chris Lattner2188e402010-01-04 07:37:31 +0000534 // If there are no variable indices, we must have a constant offset, just
535 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000536 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000537
Chris Lattner2188e402010-01-04 07:37:31 +0000538 Value *VariableIdx = GEP->getOperand(i);
539 // Determine the scale factor of the variable element. For example, this is
540 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000541 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000542
Chris Lattner2188e402010-01-04 07:37:31 +0000543 // Verify that there are no other variable indices. If so, emit the hard way.
544 for (++i, ++GTI; i != e; ++i, ++GTI) {
545 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000546 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000547
Chris Lattner2188e402010-01-04 07:37:31 +0000548 // Compute the aggregate offset of constant indices.
549 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000550
Chris Lattner2188e402010-01-04 07:37:31 +0000551 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000552 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000553 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000554 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000555 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000556 Offset += Size*CI->getSExtValue();
557 }
558 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000559
Chris Lattner2188e402010-01-04 07:37:31 +0000560 // Okay, we know we have a single variable index, which must be a
561 // pointer/array/vector index. If there is no offset, life is simple, return
562 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000563 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000564 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000565 if (Offset == 0) {
566 // Cast to intptrty in case a truncation occurs. If an extension is needed,
567 // we don't need to bother extending: the extension won't affect where the
568 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000569 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000570 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
571 }
Chris Lattner2188e402010-01-04 07:37:31 +0000572 return VariableIdx;
573 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000574
Chris Lattner2188e402010-01-04 07:37:31 +0000575 // Otherwise, there is an index. The computation we will do will be modulo
576 // the pointer size, so get it.
577 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000578
Chris Lattner2188e402010-01-04 07:37:31 +0000579 Offset &= PtrSizeMask;
580 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000581
Chris Lattner2188e402010-01-04 07:37:31 +0000582 // To do this transformation, any constant index must be a multiple of the
583 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
584 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
585 // multiple of the variable scale.
586 int64_t NewOffs = Offset / (int64_t)VariableScale;
587 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000588 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000589
Chris Lattner2188e402010-01-04 07:37:31 +0000590 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000591 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000592 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
593 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000594 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000595 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000596}
597
598/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
599/// else. At this point we know that the GEP is on the LHS of the comparison.
600Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
601 ICmpInst::Predicate Cond,
602 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000603 // Don't transform signed compares of GEPs into index compares. Even if the
604 // GEP is inbounds, the final add of the base pointer can have signed overflow
605 // and would change the result of the icmp.
606 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000607 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000608 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000609 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000610
Matt Arsenault44f60d02014-06-09 19:20:29 +0000611 // Look through bitcasts and addrspacecasts. We do not however want to remove
612 // 0 GEPs.
613 if (!isa<GetElementPtrInst>(RHS))
614 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000615
616 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000617 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000618 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
619 // This transformation (ignoring the base and scales) is valid because we
620 // know pointers can't overflow since the gep is inbounds. See if we can
621 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000622 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000623
Chris Lattner2188e402010-01-04 07:37:31 +0000624 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000625 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000626 Offset = EmitGEPOffset(GEPLHS);
627 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
628 Constant::getNullValue(Offset->getType()));
629 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
630 // If the base pointers are different, but the indices are the same, just
631 // compare the base pointer.
632 if (PtrBase != GEPRHS->getOperand(0)) {
633 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
634 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
635 GEPRHS->getOperand(0)->getType();
636 if (IndicesTheSame)
637 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
638 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
639 IndicesTheSame = false;
640 break;
641 }
642
643 // If all indices are the same, just compare the base pointers.
644 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000645 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000646
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000647 // If we're comparing GEPs with two base pointers that only differ in type
648 // and both GEPs have only constant indices or just one use, then fold
649 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000650 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000651 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
652 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
653 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000654 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000655 Value *LOffset = EmitGEPOffset(GEPLHS);
656 Value *ROffset = EmitGEPOffset(GEPRHS);
657
658 // If we looked through an addrspacecast between different sized address
659 // spaces, the LHS and RHS pointers are different sized
660 // integers. Truncate to the smaller one.
661 Type *LHSIndexTy = LOffset->getType();
662 Type *RHSIndexTy = ROffset->getType();
663 if (LHSIndexTy != RHSIndexTy) {
664 if (LHSIndexTy->getPrimitiveSizeInBits() <
665 RHSIndexTy->getPrimitiveSizeInBits()) {
666 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
667 } else
668 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
669 }
670
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000671 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000672 LOffset, ROffset);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000673 return ReplaceInstUsesWith(I, Cmp);
674 }
675
Chris Lattner2188e402010-01-04 07:37:31 +0000676 // Otherwise, the base pointers are different and the indices are
677 // different, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000678 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000679 }
680
681 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000682 if (GEPLHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +0000683 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +0000684 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +0000685
686 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000687 if (GEPRHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +0000688 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
689
Stuart Hastings66a82b92011-05-14 05:55:10 +0000690 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +0000691 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
692 // If the GEPs only differ by one index, compare it.
693 unsigned NumDifferences = 0; // Keep track of # differences.
694 unsigned DiffOperand = 0; // The operand that differs.
695 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
696 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
697 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
698 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
699 // Irreconcilable differences.
700 NumDifferences = 2;
701 break;
702 } else {
703 if (NumDifferences++) break;
704 DiffOperand = i;
705 }
706 }
707
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +0000708 if (NumDifferences == 0) // SAME GEP?
709 return ReplaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +0000710 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +0000711
Stuart Hastings66a82b92011-05-14 05:55:10 +0000712 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +0000713 Value *LHSV = GEPLHS->getOperand(DiffOperand);
714 Value *RHSV = GEPRHS->getOperand(DiffOperand);
715 // Make sure we do a signed comparison here.
716 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
717 }
718 }
719
720 // Only lower this if the icmp is the only user of the GEP or if we expect
721 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000722 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +0000723 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
724 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
725 Value *L = EmitGEPOffset(GEPLHS);
726 Value *R = EmitGEPOffset(GEPRHS);
727 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
728 }
729 }
Craig Topperf40110f2014-04-25 05:29:35 +0000730 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000731}
732
Hans Wennborgf1f36512015-10-07 00:20:07 +0000733Instruction *InstCombiner::FoldAllocaCmp(ICmpInst &ICI, AllocaInst *Alloca,
734 Value *Other) {
735 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
736
737 // It would be tempting to fold away comparisons between allocas and any
738 // pointer not based on that alloca (e.g. an argument). However, even
739 // though such pointers cannot alias, they can still compare equal.
740 //
741 // But LLVM doesn't specify where allocas get their memory, so if the alloca
742 // doesn't escape we can argue that it's impossible to guess its value, and we
743 // can therefore act as if any such guesses are wrong.
744 //
745 // The code below checks that the alloca doesn't escape, and that it's only
746 // used in a comparison once (the current instruction). The
747 // single-comparison-use condition ensures that we're trivially folding all
748 // comparisons against the alloca consistently, and avoids the risk of
749 // erroneously folding a comparison of the pointer with itself.
750
751 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
752
753 SmallVector<Use *, 32> Worklist;
754 for (Use &U : Alloca->uses()) {
755 if (Worklist.size() >= MaxIter)
756 return nullptr;
757 Worklist.push_back(&U);
758 }
759
760 unsigned NumCmps = 0;
761 while (!Worklist.empty()) {
762 assert(Worklist.size() <= MaxIter);
763 Use *U = Worklist.pop_back_val();
764 Value *V = U->getUser();
765 --MaxIter;
766
767 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
768 isa<SelectInst>(V)) {
769 // Track the uses.
770 } else if (isa<LoadInst>(V)) {
771 // Loading from the pointer doesn't escape it.
772 continue;
773 } else if (auto *SI = dyn_cast<StoreInst>(V)) {
774 // Storing *to* the pointer is fine, but storing the pointer escapes it.
775 if (SI->getValueOperand() == U->get())
776 return nullptr;
777 continue;
778 } else if (isa<ICmpInst>(V)) {
779 if (NumCmps++)
780 return nullptr; // Found more than one cmp.
781 continue;
782 } else if (auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
783 switch (Intrin->getIntrinsicID()) {
784 // These intrinsics don't escape or compare the pointer. Memset is safe
785 // because we don't allow ptrtoint. Memcpy and memmove are safe because
786 // we don't allow stores, so src cannot point to V.
787 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
788 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
789 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
790 continue;
791 default:
792 return nullptr;
793 }
794 } else {
795 return nullptr;
796 }
797 for (Use &U : V->uses()) {
798 if (Worklist.size() >= MaxIter)
799 return nullptr;
800 Worklist.push_back(&U);
801 }
802 }
803
804 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
805 return ReplaceInstUsesWith(
806 ICI,
807 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
808}
809
Chris Lattner2188e402010-01-04 07:37:31 +0000810/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000811Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner2188e402010-01-04 07:37:31 +0000812 Value *X, ConstantInt *CI,
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000813 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000814 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000815 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +0000816 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000817
Chris Lattner8c92b572010-01-08 17:48:19 +0000818 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +0000819 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
820 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
821 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +0000822 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +0000823 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +0000824 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
825 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000826
Chris Lattner2188e402010-01-04 07:37:31 +0000827 // (X+1) >u X --> X <u (0-1) --> X != 255
828 // (X+2) >u X --> X <u (0-2) --> X <u 254
829 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +0000830 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +0000831 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000832
Chris Lattner2188e402010-01-04 07:37:31 +0000833 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
834 ConstantInt *SMax = ConstantInt::get(X->getContext(),
835 APInt::getSignedMaxValue(BitWidth));
836
837 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
838 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
839 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
840 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
841 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
842 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +0000843 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +0000844 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000845
Chris Lattner2188e402010-01-04 07:37:31 +0000846 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
847 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
848 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
849 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
850 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
851 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +0000852
Chris Lattner2188e402010-01-04 07:37:31 +0000853 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +0000854 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000855 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
856}
857
858/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
859/// and CmpRHS are both known to be integer constants.
860Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
861 ConstantInt *DivRHS) {
862 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
863 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000864
865 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +0000866 // then don't attempt this transform. The code below doesn't have the
867 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +0000868 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +0000869 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +0000870 // (x /u C1) <u C2. Simply casting the operands and result won't
871 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +0000872 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +0000873 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
874 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +0000875 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000876 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000877 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +0000878 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +0000879 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +0000880 if (DivRHS->isOne()) {
881 // This eliminates some funny cases with INT_MIN.
882 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
883 return &ICI;
884 }
Chris Lattner2188e402010-01-04 07:37:31 +0000885
886 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +0000887 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
888 // C2 (CI). By solving for X we can turn this into a range check
889 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +0000890 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
891
892 // Determine if the product overflows by seeing if the product is
893 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +0000894 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +0000895 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
896 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
897
898 // Get the ICmp opcode
899 ICmpInst::Predicate Pred = ICI.getPredicate();
900
Chris Lattner98457102011-02-10 05:23:05 +0000901 /// If the division is known to be exact, then there is no remainder from the
902 /// divide, so the covered range size is unit, otherwise it is the divisor.
903 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000904
Chris Lattner2188e402010-01-04 07:37:31 +0000905 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +0000906 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +0000907 // Compute this interval based on the constants involved and the signedness of
908 // the compare/divide. This computes a half-open interval, keeping track of
909 // whether either value in the interval overflows. After analysis each
910 // overflow variable is set to 0 if it's corresponding bound variable is valid
911 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
912 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000913 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +0000914
Chris Lattner2188e402010-01-04 07:37:31 +0000915 if (!DivIsSigned) { // udiv
916 // e.g. X/5 op 3 --> [15, 20)
917 LoBound = Prod;
918 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +0000919 if (!HiOverflow) {
920 // If this is not an exact divide, then many values in the range collapse
921 // to the same result value.
922 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
923 }
Chris Lattner2188e402010-01-04 07:37:31 +0000924 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
925 if (CmpRHSV == 0) { // (X / pos) op 0
926 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +0000927 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
928 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +0000929 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
930 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
931 HiOverflow = LoOverflow = ProdOV;
932 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000933 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000934 } else { // (X / pos) op neg
935 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
936 HiBound = AddOne(Prod);
937 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
938 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +0000939 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000940 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +0000941 }
Chris Lattner2188e402010-01-04 07:37:31 +0000942 }
Chris Lattnerb1a15122011-07-15 06:08:15 +0000943 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +0000944 if (DivI->isExact())
945 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000946 if (CmpRHSV == 0) { // (X / neg) op 0
947 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +0000948 LoBound = AddOne(RangeSize);
949 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000950 if (HiBound == DivRHS) { // -INTMIN = INTMIN
951 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +0000952 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +0000953 }
954 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
955 // e.g. X/-5 op 3 --> [-19, -14)
956 HiBound = AddOne(Prod);
957 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
958 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000959 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +0000960 } else { // (X / neg) op neg
961 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
962 LoOverflow = HiOverflow = ProdOV;
963 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000964 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000965 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000966
Chris Lattner2188e402010-01-04 07:37:31 +0000967 // Dividing by a negative swaps the condition. LT <-> GT
968 Pred = ICmpInst::getSwappedPredicate(Pred);
969 }
970
971 Value *X = DivI->getOperand(0);
972 switch (Pred) {
973 default: llvm_unreachable("Unhandled icmp opcode!");
974 case ICmpInst::ICMP_EQ:
975 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000976 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +0000977 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000978 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
979 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000980 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000981 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
982 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000983 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
984 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +0000985 case ICmpInst::ICMP_NE:
986 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000987 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +0000988 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000989 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
990 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000991 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000992 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
993 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000994 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
995 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +0000996 case ICmpInst::ICMP_ULT:
997 case ICmpInst::ICMP_SLT:
998 if (LoOverflow == +1) // Low bound is greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000999 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001000 if (LoOverflow == -1) // Low bound is less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +00001001 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001002 return new ICmpInst(Pred, X, LoBound);
1003 case ICmpInst::ICMP_UGT:
1004 case ICmpInst::ICMP_SGT:
1005 if (HiOverflow == +1) // High bound greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +00001006 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +00001007 if (HiOverflow == -1) // High bound less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +00001008 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001009 if (Pred == ICmpInst::ICMP_UGT)
1010 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +00001011 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +00001012 }
1013}
1014
Chris Lattnerd369f572011-02-13 07:43:07 +00001015/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
1016Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
1017 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +00001018 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001019
Chris Lattnerd369f572011-02-13 07:43:07 +00001020 // Check that the shift amount is in range. If not, don't perform
1021 // undefined shifts. When the shift is visited it will be
1022 // simplified.
1023 uint32_t TypeBits = CmpRHSV.getBitWidth();
1024 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +00001025 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001026 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001027
Chris Lattner43273af2011-02-13 08:07:21 +00001028 if (!ICI.isEquality()) {
1029 // If we have an unsigned comparison and an ashr, we can't simplify this.
1030 // Similarly for signed comparisons with lshr.
1031 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +00001032 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001033
Eli Friedman865866e2011-05-25 23:26:20 +00001034 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1035 // by a power of 2. Since we already have logic to simplify these,
1036 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +00001037 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +00001038 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +00001039 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001040
Chris Lattner43273af2011-02-13 08:07:21 +00001041 // Revisit the shift (to delete it).
1042 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001043
Chris Lattner43273af2011-02-13 08:07:21 +00001044 Constant *DivCst =
1045 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001046
Chris Lattner43273af2011-02-13 08:07:21 +00001047 Value *Tmp =
1048 Shr->getOpcode() == Instruction::AShr ?
1049 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1050 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001051
Chris Lattner43273af2011-02-13 08:07:21 +00001052 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001053
Chris Lattner43273af2011-02-13 08:07:21 +00001054 // If the builder folded the binop, just return it.
1055 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +00001056 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +00001057 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001058
Chris Lattner43273af2011-02-13 08:07:21 +00001059 // Otherwise, fold this div/compare.
1060 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1061 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001062
Chris Lattner43273af2011-02-13 08:07:21 +00001063 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1064 assert(Res && "This div/cst should have folded!");
1065 return Res;
1066 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001067
Chris Lattnerd369f572011-02-13 07:43:07 +00001068 // If we are comparing against bits always shifted out, the
1069 // comparison cannot succeed.
1070 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001071 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001072 if (Shr->getOpcode() == Instruction::LShr)
1073 Comp = Comp.lshr(ShAmtVal);
1074 else
1075 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001076
Chris Lattnerd369f572011-02-13 07:43:07 +00001077 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1078 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001079 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattnerd369f572011-02-13 07:43:07 +00001080 return ReplaceInstUsesWith(ICI, Cst);
1081 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001082
Chris Lattnerd369f572011-02-13 07:43:07 +00001083 // Otherwise, check to see if the bits shifted out are known to be zero.
1084 // If so, we can compare against the unshifted value:
1085 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001086 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001087 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001088
Chris Lattnerd369f572011-02-13 07:43:07 +00001089 if (Shr->hasOneUse()) {
1090 // Otherwise strength reduce the shift into an and.
1091 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001092 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001093
Chris Lattnerd369f572011-02-13 07:43:07 +00001094 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1095 Mask, Shr->getName()+".mask");
1096 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1097 }
Craig Topperf40110f2014-04-25 05:29:35 +00001098 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001099}
1100
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001101/// FoldICmpCstShrCst - Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
1102/// (icmp eq/ne A, Log2(const2/const1)) ->
1103/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
1104Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
1105 ConstantInt *CI1,
1106 ConstantInt *CI2) {
1107 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1108
1109 auto getConstant = [&I, this](bool IsTrue) {
1110 if (I.getPredicate() == I.ICMP_NE)
1111 IsTrue = !IsTrue;
1112 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
1113 };
1114
1115 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1116 if (I.getPredicate() == I.ICMP_NE)
1117 Pred = CmpInst::getInversePredicate(Pred);
1118 return new ICmpInst(Pred, LHS, RHS);
1119 };
1120
1121 APInt AP1 = CI1->getValue();
1122 APInt AP2 = CI2->getValue();
1123
David Majnemer2abb8182014-10-25 07:13:13 +00001124 // Don't bother doing any work for cases which InstSimplify handles.
1125 if (AP2 == 0)
1126 return nullptr;
1127 bool IsAShr = isa<AShrOperator>(Op);
1128 if (IsAShr) {
1129 if (AP2.isAllOnesValue())
1130 return nullptr;
1131 if (AP2.isNegative() != AP1.isNegative())
1132 return nullptr;
1133 if (AP2.sgt(AP1))
1134 return nullptr;
1135 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001136
David Majnemerd2056022014-10-21 19:51:55 +00001137 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001138 // 'A' must be large enough to shift out the highest set bit.
1139 return getICmp(I.ICMP_UGT, A,
1140 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001141
David Majnemerd2056022014-10-21 19:51:55 +00001142 if (AP1 == AP2)
1143 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001144
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001145 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001146 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001147 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001148 else
David Majnemere5977eb2015-09-19 00:48:26 +00001149 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001150
David Majnemerd2056022014-10-21 19:51:55 +00001151 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001152 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1153 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001154 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001155 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1156 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001157 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001158 } else if (AP1 == AP2.lshr(Shift)) {
1159 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1160 }
David Majnemerd2056022014-10-21 19:51:55 +00001161 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001162 // Shifting const2 will never be equal to const1.
1163 return getConstant(false);
1164}
Chris Lattner2188e402010-01-04 07:37:31 +00001165
David Majnemer59939ac2014-10-19 08:23:08 +00001166/// FoldICmpCstShlCst - Handle "(icmp eq/ne (shl const2, A), const1)" ->
1167/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
1168Instruction *InstCombiner::FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
1169 ConstantInt *CI1,
1170 ConstantInt *CI2) {
1171 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1172
1173 auto getConstant = [&I, this](bool IsTrue) {
1174 if (I.getPredicate() == I.ICMP_NE)
1175 IsTrue = !IsTrue;
1176 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
1177 };
1178
1179 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1180 if (I.getPredicate() == I.ICMP_NE)
1181 Pred = CmpInst::getInversePredicate(Pred);
1182 return new ICmpInst(Pred, LHS, RHS);
1183 };
1184
1185 APInt AP1 = CI1->getValue();
1186 APInt AP2 = CI2->getValue();
1187
David Majnemer2abb8182014-10-25 07:13:13 +00001188 // Don't bother doing any work for cases which InstSimplify handles.
1189 if (AP2 == 0)
1190 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001191
1192 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1193
1194 if (!AP1 && AP2TrailingZeros != 0)
1195 return getICmp(I.ICMP_UGE, A,
1196 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1197
1198 if (AP1 == AP2)
1199 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1200
1201 // Get the distance between the lowest bits that are set.
1202 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1203
1204 if (Shift > 0 && AP2.shl(Shift) == AP1)
1205 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1206
1207 // Shifting const2 will never be equal to const1.
1208 return getConstant(false);
1209}
1210
Chris Lattner2188e402010-01-04 07:37:31 +00001211/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1212///
1213Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1214 Instruction *LHSI,
1215 ConstantInt *RHS) {
1216 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001217
Chris Lattner2188e402010-01-04 07:37:31 +00001218 switch (LHSI->getOpcode()) {
1219 case Instruction::Trunc:
Sanjoy Dase5f48892015-09-16 20:41:29 +00001220 if (RHS->isOne() && RHSV.getBitWidth() > 1) {
1221 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1222 Value *V = nullptr;
1223 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1224 match(LHSI->getOperand(0), m_Signum(m_Value(V))))
1225 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1226 ConstantInt::get(V->getType(), 1));
1227 }
Chris Lattner2188e402010-01-04 07:37:31 +00001228 if (ICI.isEquality() && LHSI->hasOneUse()) {
1229 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1230 // of the high bits truncated out of x are known.
1231 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1232 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001233 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001234 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001235
Chris Lattner2188e402010-01-04 07:37:31 +00001236 // If all the high bits are known, we can do this xform.
1237 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1238 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001239 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001240 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001241 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001242 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001243 }
1244 }
1245 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001246
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001247 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1248 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001249 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1250 // fold the xor.
1251 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1252 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1253 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001254
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001255 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001256 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001257 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001258 ICI.setOperand(0, CompareVal);
1259 Worklist.Add(LHSI);
1260 return &ICI;
1261 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001262
Chris Lattner2188e402010-01-04 07:37:31 +00001263 // Was the old condition true if the operand is positive?
1264 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001265
Chris Lattner2188e402010-01-04 07:37:31 +00001266 // If so, the new one isn't.
1267 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001268
Chris Lattner2188e402010-01-04 07:37:31 +00001269 if (isTrueIfPositive)
1270 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1271 SubOne(RHS));
1272 else
1273 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1274 AddOne(RHS));
1275 }
1276
1277 if (LHSI->hasOneUse()) {
1278 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001279 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1280 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001281 ICmpInst::Predicate Pred = ICI.isSigned()
1282 ? ICI.getUnsignedPredicate()
1283 : ICI.getSignedPredicate();
1284 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001285 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001286 }
1287
1288 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001289 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1290 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001291 ICmpInst::Predicate Pred = ICI.isSigned()
1292 ? ICI.getUnsignedPredicate()
1293 : ICI.getSignedPredicate();
1294 Pred = ICI.getSwappedPredicate(Pred);
1295 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001296 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001297 }
1298 }
David Majnemer72d76272013-07-09 09:20:58 +00001299
1300 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1301 // iff -C is a power of 2
1302 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001303 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1304 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001305
1306 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1307 // iff -C is a power of 2
1308 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001309 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1310 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001311 }
1312 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001313 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001314 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1315 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001316 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001317
Chris Lattner2188e402010-01-04 07:37:31 +00001318 // If the LHS is an AND of a truncating cast, we can widen the
1319 // and/compare to be the input width without changing the value
1320 // produced, eliminating a cast.
1321 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1322 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001323 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001324 // Extending a relational comparison when we're checking the sign
1325 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001326 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001327 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001328 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001329 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001330 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001331 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001332 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001333 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001334 }
1335 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001336
1337 // If the LHS is an AND of a zext, and we have an equality compare, we can
1338 // shrink the and/compare to the smaller type, eliminating the cast.
1339 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001340 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001341 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1342 // should fold the icmp to true/false in that case.
1343 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1344 Value *NewAnd =
1345 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001346 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001347 NewAnd->takeName(LHSI);
1348 return new ICmpInst(ICI.getPredicate(), NewAnd,
1349 ConstantExpr::getTrunc(RHS, Ty));
1350 }
1351 }
1352
Chris Lattner2188e402010-01-04 07:37:31 +00001353 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1354 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1355 // happens a LOT in code produced by the C front-end, for bitfield
1356 // access.
1357 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1358 if (Shift && !Shift->isShift())
Craig Topperf40110f2014-04-25 05:29:35 +00001359 Shift = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001360
Chris Lattner2188e402010-01-04 07:37:31 +00001361 ConstantInt *ShAmt;
Craig Topperf40110f2014-04-25 05:29:35 +00001362 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001363
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001364 // This seemingly simple opportunity to fold away a shift turns out to
1365 // be rather complicated. See PR17827
1366 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001367 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001368 bool CanFold = false;
1369 unsigned ShiftOpcode = Shift->getOpcode();
1370 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001371 // There may be some constraints that make this possible,
1372 // but nothing simple has been discovered yet.
1373 CanFold = false;
1374 } else if (ShiftOpcode == Instruction::Shl) {
1375 // For a left shift, we can fold if the comparison is not signed.
1376 // We can also fold a signed comparison if the mask value and
1377 // comparison value are not negative. These constraints may not be
1378 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001379 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001380 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001381 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001382 } else if (ShiftOpcode == Instruction::LShr) {
1383 // For a logical right shift, we can fold if the comparison is not
1384 // signed. We can also fold a signed comparison if the shifted mask
1385 // value and the shifted comparison value are not negative.
1386 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001387 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001388 if (!ICI.isSigned())
1389 CanFold = true;
1390 else {
1391 ConstantInt *ShiftedAndCst =
1392 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1393 ConstantInt *ShiftedRHSCst =
1394 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1395
1396 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1397 CanFold = true;
1398 }
Chris Lattner2188e402010-01-04 07:37:31 +00001399 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001400
Chris Lattner2188e402010-01-04 07:37:31 +00001401 if (CanFold) {
1402 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001403 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001404 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1405 else
1406 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001407
Chris Lattner2188e402010-01-04 07:37:31 +00001408 // Check to see if we are shifting out any of the bits being
1409 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001410 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001411 // If we shifted bits out, the fold is not going to work out.
1412 // As a special case, check to see if this means that the
1413 // result is always true or false now.
1414 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Jakub Staszakbddea112013-06-06 20:18:46 +00001415 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001416 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Jakub Staszakbddea112013-06-06 20:18:46 +00001417 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001418 } else {
1419 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001420 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001421 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001422 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001423 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001424 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1425 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001426 LHSI->setOperand(0, Shift->getOperand(0));
1427 Worklist.Add(Shift); // Shift is dead.
1428 return &ICI;
1429 }
1430 }
1431 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001432
Chris Lattner2188e402010-01-04 07:37:31 +00001433 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1434 // preferable because it allows the C<<Y expression to be hoisted out
1435 // of a loop if Y is invariant and X is not.
1436 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1437 ICI.isEquality() && !Shift->isArithmeticShift() &&
1438 !isa<Constant>(Shift->getOperand(0))) {
1439 // Compute C << Y.
1440 Value *NS;
1441 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001442 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001443 } else {
1444 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001445 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001446 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001447
Chris Lattner2188e402010-01-04 07:37:31 +00001448 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001449 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001450 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001451
Chris Lattner2188e402010-01-04 07:37:31 +00001452 ICI.setOperand(0, NewAnd);
1453 return &ICI;
1454 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001455
David Majnemer0ffccf72014-08-24 09:10:57 +00001456 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1457 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1458 //
1459 // iff pred isn't signed
1460 {
1461 Value *X, *Y, *LShr;
1462 if (!ICI.isSigned() && RHSV == 0) {
1463 if (match(LHSI->getOperand(1), m_One())) {
1464 Constant *One = cast<Constant>(LHSI->getOperand(1));
1465 Value *Or = LHSI->getOperand(0);
1466 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1467 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1468 unsigned UsesRemoved = 0;
1469 if (LHSI->hasOneUse())
1470 ++UsesRemoved;
1471 if (Or->hasOneUse())
1472 ++UsesRemoved;
1473 if (LShr->hasOneUse())
1474 ++UsesRemoved;
1475 Value *NewOr = nullptr;
1476 // Compute X & ((1 << Y) | 1)
1477 if (auto *C = dyn_cast<Constant>(Y)) {
1478 if (UsesRemoved >= 1)
1479 NewOr =
1480 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1481 } else {
1482 if (UsesRemoved >= 3)
1483 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1484 LShr->getName(),
1485 /*HasNUW=*/true),
1486 One, Or->getName());
1487 }
1488 if (NewOr) {
1489 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1490 ICI.setOperand(0, NewAnd);
1491 return &ICI;
1492 }
1493 }
1494 }
1495 }
1496 }
1497
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001498 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1499 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001500 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001501 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1502 if ((NTZ < AndCst->getBitWidth()) &&
1503 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001504 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1505 Constant::getNullValue(RHS->getType()));
1506 }
Chris Lattner2188e402010-01-04 07:37:31 +00001507 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001508
Chris Lattner2188e402010-01-04 07:37:31 +00001509 // Try to optimize things like "A[i]&42 == 0" to index computations.
1510 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1511 if (GetElementPtrInst *GEP =
1512 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1513 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1514 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1515 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1516 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1517 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1518 return Res;
1519 }
1520 }
David Majnemer414d4e52013-07-09 08:09:32 +00001521
1522 // X & -C == -C -> X > u ~C
1523 // X & -C != -C -> X <= u ~C
1524 // iff C is a power of 2
1525 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1526 return new ICmpInst(
1527 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1528 : ICmpInst::ICMP_ULE,
1529 LHSI->getOperand(0), SubOne(RHS));
David Majnemerdfa3b092015-08-16 07:09:17 +00001530
1531 // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1532 // iff C is a power of 2
1533 if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) {
1534 if (auto *CI = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1535 const APInt &AI = CI->getValue();
1536 int32_t ExactLogBase2 = AI.exactLogBase2();
1537 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1538 Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1);
1539 Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy);
1540 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1541 ? ICmpInst::ICMP_SGE
1542 : ICmpInst::ICMP_SLT,
1543 Trunc, Constant::getNullValue(NTy));
1544 }
1545 }
1546 }
Chris Lattner2188e402010-01-04 07:37:31 +00001547 break;
1548
1549 case Instruction::Or: {
Sanjoy Dase5f48892015-09-16 20:41:29 +00001550 if (RHS->isOne()) {
1551 // icmp slt signum(V) 1 --> icmp slt V, 1
1552 Value *V = nullptr;
1553 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1554 match(LHSI, m_Signum(m_Value(V))))
1555 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1556 ConstantInt::get(V->getType(), 1));
1557 }
1558
Chris Lattner2188e402010-01-04 07:37:31 +00001559 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1560 break;
1561 Value *P, *Q;
1562 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1563 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1564 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001565 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1566 Constant::getNullValue(P->getType()));
1567 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1568 Constant::getNullValue(Q->getType()));
1569 Instruction *Op;
1570 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1571 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1572 else
1573 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1574 return Op;
1575 }
1576 break;
1577 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001578
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001579 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1580 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1581 if (!Val) break;
1582
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001583 // If this is a signed comparison to 0 and the mul is sign preserving,
1584 // use the mul LHS operand instead.
1585 ICmpInst::Predicate pred = ICI.getPredicate();
1586 if (isSignTest(pred, RHS) && !Val->isZero() &&
1587 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1588 return new ICmpInst(Val->isNegative() ?
1589 ICmpInst::getSwappedPredicate(pred) : pred,
1590 LHSI->getOperand(0),
1591 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001592
1593 break;
1594 }
1595
Chris Lattner2188e402010-01-04 07:37:31 +00001596 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001597 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001598 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1599 if (!ShAmt) {
1600 Value *X;
1601 // (1 << X) pred P2 -> X pred Log2(P2)
1602 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1603 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1604 ICmpInst::Predicate Pred = ICI.getPredicate();
1605 if (ICI.isUnsigned()) {
1606 if (!RHSVIsPowerOf2) {
1607 // (1 << X) < 30 -> X <= 4
1608 // (1 << X) <= 30 -> X <= 4
1609 // (1 << X) >= 30 -> X > 4
1610 // (1 << X) > 30 -> X > 4
1611 if (Pred == ICmpInst::ICMP_ULT)
1612 Pred = ICmpInst::ICMP_ULE;
1613 else if (Pred == ICmpInst::ICMP_UGE)
1614 Pred = ICmpInst::ICMP_UGT;
1615 }
1616 unsigned RHSLog2 = RHSV.logBase2();
1617
1618 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
David Majnemerb889e402013-06-28 23:42:03 +00001619 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1620 if (RHSLog2 == TypeBits-1) {
1621 if (Pred == ICmpInst::ICMP_UGE)
1622 Pred = ICmpInst::ICMP_EQ;
David Majnemerb889e402013-06-28 23:42:03 +00001623 else if (Pred == ICmpInst::ICMP_ULT)
1624 Pred = ICmpInst::ICMP_NE;
1625 }
1626
1627 return new ICmpInst(Pred, X,
1628 ConstantInt::get(RHS->getType(), RHSLog2));
1629 } else if (ICI.isSigned()) {
1630 if (RHSV.isAllOnesValue()) {
1631 // (1 << X) <= -1 -> X == 31
1632 if (Pred == ICmpInst::ICMP_SLE)
1633 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1634 ConstantInt::get(RHS->getType(), TypeBits-1));
1635
1636 // (1 << X) > -1 -> X != 31
1637 if (Pred == ICmpInst::ICMP_SGT)
1638 return new ICmpInst(ICmpInst::ICMP_NE, X,
1639 ConstantInt::get(RHS->getType(), TypeBits-1));
1640 } else if (!RHSV) {
1641 // (1 << X) < 0 -> X == 31
1642 // (1 << X) <= 0 -> X == 31
1643 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1644 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1645 ConstantInt::get(RHS->getType(), TypeBits-1));
1646
1647 // (1 << X) >= 0 -> X != 31
1648 // (1 << X) > 0 -> X != 31
1649 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1650 return new ICmpInst(ICmpInst::ICMP_NE, X,
1651 ConstantInt::get(RHS->getType(), TypeBits-1));
1652 }
1653 } else if (ICI.isEquality()) {
1654 if (RHSVIsPowerOf2)
1655 return new ICmpInst(
1656 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
David Majnemerb889e402013-06-28 23:42:03 +00001657 }
1658 }
1659 break;
1660 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001661
Chris Lattner2188e402010-01-04 07:37:31 +00001662 // Check that the shift amount is in range. If not, don't perform
1663 // undefined shifts. When the shift is visited it will be
1664 // simplified.
1665 if (ShAmt->uge(TypeBits))
1666 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001667
Chris Lattner2188e402010-01-04 07:37:31 +00001668 if (ICI.isEquality()) {
1669 // If we are comparing against bits always shifted out, the
1670 // comparison cannot succeed.
1671 Constant *Comp =
1672 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1673 ShAmt);
1674 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1675 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001676 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner2188e402010-01-04 07:37:31 +00001677 return ReplaceInstUsesWith(ICI, Cst);
1678 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001679
Chris Lattner98457102011-02-10 05:23:05 +00001680 // If the shift is NUW, then it is just shifting out zeros, no need for an
1681 // AND.
1682 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1683 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1684 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001685
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001686 // If the shift is NSW and we compare to 0, then it is just shifting out
1687 // sign bits, no need for an AND either.
1688 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1689 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1690 ConstantExpr::getLShr(RHS, ShAmt));
1691
Chris Lattner2188e402010-01-04 07:37:31 +00001692 if (LHSI->hasOneUse()) {
1693 // Otherwise strength reduce the shift into an and.
1694 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00001695 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1696 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001697
Chris Lattner2188e402010-01-04 07:37:31 +00001698 Value *And =
1699 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1700 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00001701 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00001702 }
1703 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001704
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001705 // If this is a signed comparison to 0 and the shift is sign preserving,
1706 // use the shift LHS operand instead.
1707 ICmpInst::Predicate pred = ICI.getPredicate();
1708 if (isSignTest(pred, RHS) &&
1709 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1710 return new ICmpInst(pred,
1711 LHSI->getOperand(0),
1712 Constant::getNullValue(RHS->getType()));
1713
Chris Lattner2188e402010-01-04 07:37:31 +00001714 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1715 bool TrueIfSigned = false;
1716 if (LHSI->hasOneUse() &&
1717 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1718 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00001719 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00001720 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00001721 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00001722 Value *And =
1723 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1724 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1725 And, Constant::getNullValue(And->getType()));
1726 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001727
1728 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001729 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1730 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001731 // This enables to get rid of the shift in favor of a trunc which can be
1732 // free on the target. It has the additional benefit of comparing to a
1733 // smaller constant, which will be target friendly.
1734 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001735 if (LHSI->hasOneUse() &&
1736 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001737 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1738 Constant *NCI = ConstantExpr::getTrunc(
1739 ConstantExpr::getAShr(RHS,
1740 ConstantInt::get(RHS->getType(), Amt)),
1741 NTy);
1742 return new ICmpInst(ICI.getPredicate(),
1743 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00001744 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001745 }
1746
Chris Lattner2188e402010-01-04 07:37:31 +00001747 break;
1748 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001749
Chris Lattner2188e402010-01-04 07:37:31 +00001750 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00001751 case Instruction::AShr: {
1752 // Handle equality comparisons of shift-by-constant.
1753 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1754 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1755 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00001756 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00001757 }
1758
1759 // Handle exact shr's.
1760 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1761 if (RHSV.isMinValue())
1762 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1763 }
Chris Lattner2188e402010-01-04 07:37:31 +00001764 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00001765 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001766
Chris Lattner2188e402010-01-04 07:37:31 +00001767 case Instruction::SDiv:
1768 case Instruction::UDiv:
1769 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00001770 // Fold this div into the comparison, producing a range check.
1771 // Determine, based on the divide type, what the range is being
1772 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00001773 // it, otherwise compute the range [low, hi) bounding the new value.
1774 // See: InsertRangeTest above for the kinds of replacements possible.
1775 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1776 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1777 DivRHS))
1778 return R;
1779 break;
1780
David Majnemerf2a9a512013-07-09 07:50:59 +00001781 case Instruction::Sub: {
1782 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1783 if (!LHSC) break;
1784 const APInt &LHSV = LHSC->getValue();
1785
1786 // C1-X <u C2 -> (X|(C2-1)) == C1
1787 // iff C1 & (C2-1) == C2-1
1788 // C2 is a power of 2
1789 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1790 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1791 return new ICmpInst(ICmpInst::ICMP_EQ,
1792 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1793 LHSC);
1794
David Majnemereeed73b2013-07-09 09:24:35 +00001795 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00001796 // iff C1 & C2 == C2
1797 // C2+1 is a power of 2
1798 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1799 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1800 return new ICmpInst(ICmpInst::ICMP_NE,
1801 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1802 break;
1803 }
1804
Chris Lattner2188e402010-01-04 07:37:31 +00001805 case Instruction::Add:
1806 // Fold: icmp pred (add X, C1), C2
1807 if (!ICI.isEquality()) {
1808 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1809 if (!LHSC) break;
1810 const APInt &LHSV = LHSC->getValue();
1811
1812 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1813 .subtract(LHSV);
1814
1815 if (ICI.isSigned()) {
1816 if (CR.getLower().isSignBit()) {
1817 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001818 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001819 } else if (CR.getUpper().isSignBit()) {
1820 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001821 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001822 }
1823 } else {
1824 if (CR.getLower().isMinValue()) {
1825 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001826 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001827 } else if (CR.getUpper().isMinValue()) {
1828 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001829 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001830 }
1831 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00001832
David Majnemerbafa5372013-07-09 07:58:32 +00001833 // X-C1 <u C2 -> (X & -C2) == C1
1834 // iff C1 & (C2-1) == 0
1835 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00001836 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00001837 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00001838 return new ICmpInst(ICmpInst::ICMP_EQ,
1839 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1840 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00001841
David Majnemereeed73b2013-07-09 09:24:35 +00001842 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00001843 // iff C1 & C2 == 0
1844 // C2+1 is a power of 2
1845 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1846 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1847 return new ICmpInst(ICmpInst::ICMP_NE,
1848 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1849 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00001850 }
1851 break;
1852 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001853
Chris Lattner2188e402010-01-04 07:37:31 +00001854 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1855 if (ICI.isEquality()) {
1856 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001857
1858 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner2188e402010-01-04 07:37:31 +00001859 // the second operand is a constant, simplify a bit.
1860 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1861 switch (BO->getOpcode()) {
1862 case Instruction::SRem:
1863 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1864 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1865 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohman4ce1fb12010-04-08 23:03:40 +00001866 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001867 Value *NewRem =
1868 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1869 BO->getName());
1870 return new ICmpInst(ICI.getPredicate(), NewRem,
1871 Constant::getNullValue(BO->getType()));
1872 }
1873 }
1874 break;
1875 case Instruction::Add:
1876 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1877 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1878 if (BO->hasOneUse())
1879 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1880 ConstantExpr::getSub(RHS, BOp1C));
1881 } else if (RHSV == 0) {
1882 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1883 // efficiently invertible, or if the add has just this one use.
1884 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001885
Chris Lattner2188e402010-01-04 07:37:31 +00001886 if (Value *NegVal = dyn_castNegVal(BOp1))
1887 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner31b106d2011-04-26 20:02:45 +00001888 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner2188e402010-01-04 07:37:31 +00001889 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner31b106d2011-04-26 20:02:45 +00001890 if (BO->hasOneUse()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001891 Value *Neg = Builder->CreateNeg(BOp1);
1892 Neg->takeName(BO);
1893 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1894 }
1895 }
1896 break;
1897 case Instruction::Xor:
1898 // For the xor case, we can xor two constants together, eliminating
1899 // the explicit xor.
Benjamin Kramerc9708492011-06-13 15:24:24 +00001900 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1901 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner2188e402010-01-04 07:37:31 +00001902 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001903 } else if (RHSV == 0) {
1904 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner2188e402010-01-04 07:37:31 +00001905 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1906 BO->getOperand(1));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001907 }
Chris Lattner2188e402010-01-04 07:37:31 +00001908 break;
Benjamin Kramerc9708492011-06-13 15:24:24 +00001909 case Instruction::Sub:
1910 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1911 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1912 if (BO->hasOneUse())
1913 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1914 ConstantExpr::getSub(BOp0C, RHS));
1915 } else if (RHSV == 0) {
1916 // Replace ((sub A, B) != 0) with (A != B)
1917 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1918 BO->getOperand(1));
1919 }
1920 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001921 case Instruction::Or:
1922 // If bits are being or'd in that are not present in the constant we
1923 // are comparing against, then the comparison could never succeed!
Eli Friedman0428a612010-07-29 18:03:33 +00001924 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001925 Constant *NotCI = ConstantExpr::getNot(RHS);
1926 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Jakub Staszakbddea112013-06-06 20:18:46 +00001927 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Chris Lattner2188e402010-01-04 07:37:31 +00001928 }
1929 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001930
Chris Lattner2188e402010-01-04 07:37:31 +00001931 case Instruction::And:
1932 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1933 // If bits are being compared against that are and'd out, then the
1934 // comparison can never succeed!
1935 if ((RHSV & ~BOC->getValue()) != 0)
Jakub Staszakbddea112013-06-06 20:18:46 +00001936 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001937
Chris Lattner2188e402010-01-04 07:37:31 +00001938 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1939 if (RHS == BOC && RHSV.isPowerOf2())
1940 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1941 ICmpInst::ICMP_NE, LHSI,
1942 Constant::getNullValue(RHS->getType()));
Benjamin Kramer9eca5fe2011-07-04 20:16:36 +00001943
1944 // Don't perform the following transforms if the AND has multiple uses
1945 if (!BO->hasOneUse())
1946 break;
1947
Chris Lattner2188e402010-01-04 07:37:31 +00001948 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1949 if (BOC->getValue().isSignBit()) {
1950 Value *X = BO->getOperand(0);
1951 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001952 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001953 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1954 return new ICmpInst(pred, X, Zero);
1955 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001956
Chris Lattner2188e402010-01-04 07:37:31 +00001957 // ((X & ~7) == 0) --> X < 8
1958 if (RHSV == 0 && isHighOnes(BOC)) {
1959 Value *X = BO->getOperand(0);
1960 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001961 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001962 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1963 return new ICmpInst(pred, X, NegX);
1964 }
1965 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001966 break;
1967 case Instruction::Mul:
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001968 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001969 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1970 // The trivial case (mul X, 0) is handled by InstSimplify
1971 // General case : (mul X, C) != 0 iff X != 0
1972 // (mul X, C) == 0 iff X == 0
1973 if (!BOC->isZero())
1974 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1975 Constant::getNullValue(RHS->getType()));
1976 }
1977 }
1978 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001979 default: break;
1980 }
1981 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1982 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner54f4e392010-01-05 18:09:56 +00001983 switch (II->getIntrinsicID()) {
1984 case Intrinsic::bswap:
Chris Lattner2188e402010-01-04 07:37:31 +00001985 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001986 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszakbddea112013-06-06 20:18:46 +00001987 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner2188e402010-01-04 07:37:31 +00001988 return &ICI;
Chris Lattner54f4e392010-01-05 18:09:56 +00001989 case Intrinsic::ctlz:
1990 case Intrinsic::cttz:
1991 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1992 if (RHSV == RHS->getType()->getBitWidth()) {
1993 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001994 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001995 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1996 return &ICI;
1997 }
1998 break;
1999 case Intrinsic::ctpop:
2000 // popcount(A) == 0 -> A == 0 and likewise for !=
2001 if (RHS->isZero()) {
2002 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00002003 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00002004 ICI.setOperand(1, RHS);
2005 return &ICI;
2006 }
2007 break;
2008 default:
Duncan Sands41b4a6b2010-07-12 08:16:59 +00002009 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002010 }
2011 }
2012 }
Craig Topperf40110f2014-04-25 05:29:35 +00002013 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002014}
2015
2016/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
2017/// We only handle extending casts so far.
2018///
2019Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
2020 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
2021 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002022 Type *SrcTy = LHSCIOp->getType();
2023 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002024 Value *RHSCIOp;
2025
Jim Grosbach129c52a2011-09-30 18:09:53 +00002026 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002027 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002028 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2029 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002030 Value *RHSOp = nullptr;
Michael Liaod266b922015-02-13 04:51:26 +00002031 if (PtrToIntOperator *RHSC = dyn_cast<PtrToIntOperator>(ICI.getOperand(1))) {
2032 Value *RHSCIOp = RHSC->getOperand(0);
2033 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2034 LHSCIOp->getType()->getPointerAddressSpace()) {
2035 RHSOp = RHSC->getOperand(0);
2036 // If the pointer types don't match, insert a bitcast.
2037 if (LHSCIOp->getType() != RHSOp->getType())
2038 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2039 }
2040 } else if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1)))
Chris Lattner2188e402010-01-04 07:37:31 +00002041 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002042
2043 if (RHSOp)
2044 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
2045 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002046
Chris Lattner2188e402010-01-04 07:37:31 +00002047 // The code below only handles extension cast instructions, so far.
2048 // Enforce this.
2049 if (LHSCI->getOpcode() != Instruction::ZExt &&
2050 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002051 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002052
2053 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
2054 bool isSignedCmp = ICI.isSigned();
2055
2056 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
2057 // Not an extension from the same type?
2058 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002059 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002060 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002061
Chris Lattner2188e402010-01-04 07:37:31 +00002062 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2063 // and the other is a zext), then we can't handle this.
2064 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002065 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002066
2067 // Deal with equality cases early.
2068 if (ICI.isEquality())
2069 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
2070
2071 // A signed comparison of sign extended values simplifies into a
2072 // signed comparison.
2073 if (isSignedCmp && isSignedExt)
2074 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
2075
2076 // The other three cases all fold into an unsigned comparison.
2077 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
2078 }
2079
2080 // If we aren't dealing with a constant on the RHS, exit early
2081 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
2082 if (!CI)
Craig Topperf40110f2014-04-25 05:29:35 +00002083 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002084
2085 // Compute the constant that would happen if we truncated to SrcTy then
2086 // reextended to DestTy.
2087 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
2088 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
2089 Res1, DestTy);
2090
2091 // If the re-extended constant didn't change...
2092 if (Res2 == CI) {
2093 // Deal with equality cases early.
2094 if (ICI.isEquality())
2095 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
2096
2097 // A signed comparison of sign extended values simplifies into a
2098 // signed comparison.
2099 if (isSignedExt && isSignedCmp)
2100 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
2101
2102 // The other three cases all fold into an unsigned comparison.
2103 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
2104 }
2105
Jim Grosbach129c52a2011-09-30 18:09:53 +00002106 // The re-extended constant changed so the constant cannot be represented
Chris Lattner2188e402010-01-04 07:37:31 +00002107 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002108 // All the cases that fold to true or false will have already been handled
2109 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002110
Duncan Sands8fb2c382011-01-20 13:21:55 +00002111 if (isSignedCmp || !isSignedExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002112 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002113
2114 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2115 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002116
2117 // We're performing an unsigned comp with a sign extended value.
2118 // This is true if the input is >= 0. [aka >s -1]
2119 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
2120 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002121
2122 // Finally, return the value computed.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002123 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner2188e402010-01-04 07:37:31 +00002124 return ReplaceInstUsesWith(ICI, Result);
2125
Duncan Sands8fb2c382011-01-20 13:21:55 +00002126 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002127 return BinaryOperator::CreateNot(Result);
2128}
2129
Chris Lattneree61c1d2010-12-19 17:52:50 +00002130/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
2131/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002132/// If this is of the form:
2133/// sum = a + b
2134/// if (sum+128 >u 255)
2135/// Then replace it with llvm.sadd.with.overflow.i8.
2136///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002137static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2138 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002139 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002140 // The transformation we're trying to do here is to transform this into an
2141 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2142 // with a narrower add, and discard the add-with-constant that is part of the
2143 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002144
Chris Lattnerf29562d2010-12-19 17:59:02 +00002145 // In order to eliminate the add-with-constant, the compare can be its only
2146 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002147 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002148 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002149
Chris Lattnerc56c8452010-12-19 18:22:06 +00002150 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002151 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002152 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002153 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002154
Chris Lattnerc56c8452010-12-19 18:22:06 +00002155 // The width of the new add formed is 1 more than the bias.
2156 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002157
Chris Lattnerc56c8452010-12-19 18:22:06 +00002158 // Check to see that CI1 is an all-ones value with NewWidth bits.
2159 if (CI1->getBitWidth() == NewWidth ||
2160 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002161 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002162
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002163 // This is only really a signed overflow check if the inputs have been
2164 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2165 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2166 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002167 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2168 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002169 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002170
Jim Grosbach129c52a2011-09-30 18:09:53 +00002171 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002172 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2173 // and truncates that discard the high bits of the add. Verify that this is
2174 // the case.
2175 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002176 for (User *U : OrigAdd->users()) {
2177 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002178
Chris Lattnerc56c8452010-12-19 18:22:06 +00002179 // Only accept truncates for now. We would really like a nice recursive
2180 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2181 // chain to see which bits of a value are actually demanded. If the
2182 // original add had another add which was then immediately truncated, we
2183 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002184 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002185 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2186 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002187 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002188
Chris Lattneree61c1d2010-12-19 17:52:50 +00002189 // If the pattern matches, truncate the inputs to the narrower type and
2190 // use the sadd_with_overflow intrinsic to efficiently compute both the
2191 // result and the overflow bit.
Chris Lattner79874562010-12-19 18:35:09 +00002192 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002193
Jay Foadb804a2b2011-07-12 14:06:48 +00002194 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner79874562010-12-19 18:35:09 +00002195 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramere6e19332011-07-14 17:45:39 +00002196 NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002197
Chris Lattnerce2995a2010-12-19 18:38:44 +00002198 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002199
Chris Lattner79874562010-12-19 18:35:09 +00002200 // Put the new code above the original add, in case there are any uses of the
2201 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002202 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002203
Chris Lattner79874562010-12-19 18:35:09 +00002204 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2205 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002206 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002207 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2208 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002209
Chris Lattneree61c1d2010-12-19 17:52:50 +00002210 // The inner add was the result of the narrow add, zero extended to the
2211 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattnerce2995a2010-12-19 18:38:44 +00002212 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002213
Chris Lattner79874562010-12-19 18:35:09 +00002214 // The original icmp gets replaced with the overflow value.
2215 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002216}
Chris Lattner2188e402010-01-04 07:37:31 +00002217
Sanjoy Dasb0984472015-04-08 04:27:22 +00002218bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2219 Value *RHS, Instruction &OrigI,
2220 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002221 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2222 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002223
2224 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2225 Result = OpResult;
2226 Overflow = OverflowVal;
2227 if (ReuseName)
2228 Result->takeName(&OrigI);
2229 return true;
2230 };
2231
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002232 // If the overflow check was an add followed by a compare, the insertion point
2233 // may be pointing to the compare. We want to insert the new instructions
2234 // before the add in case there are uses of the add between the add and the
2235 // compare.
2236 Builder->SetInsertPoint(&OrigI);
2237
Sanjoy Dasb0984472015-04-08 04:27:22 +00002238 switch (OCF) {
2239 case OCF_INVALID:
2240 llvm_unreachable("bad overflow check kind!");
2241
2242 case OCF_UNSIGNED_ADD: {
2243 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2244 if (OR == OverflowResult::NeverOverflows)
2245 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2246 true);
2247
2248 if (OR == OverflowResult::AlwaysOverflows)
2249 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
2250 }
2251 // FALL THROUGH uadd into sadd
2252 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002253 // X + 0 -> {X, false}
2254 if (match(RHS, m_Zero()))
2255 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002256
2257 // We can strength reduce this signed add into a regular add if we can prove
2258 // that it will never overflow.
2259 if (OCF == OCF_SIGNED_ADD)
2260 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2261 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2262 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002263 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002264 }
2265
2266 case OCF_UNSIGNED_SUB:
2267 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002268 // X - 0 -> {X, false}
2269 if (match(RHS, m_Zero()))
2270 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002271
2272 if (OCF == OCF_SIGNED_SUB) {
2273 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2274 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2275 true);
2276 } else {
2277 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2278 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2279 true);
2280 }
2281 break;
2282 }
2283
2284 case OCF_UNSIGNED_MUL: {
2285 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2286 if (OR == OverflowResult::NeverOverflows)
2287 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2288 true);
2289 if (OR == OverflowResult::AlwaysOverflows)
2290 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
2291 } // FALL THROUGH
2292 case OCF_SIGNED_MUL:
2293 // X * undef -> undef
2294 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002295 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002296
David Majnemer27e89ba2015-05-21 23:04:21 +00002297 // X * 0 -> {0, false}
2298 if (match(RHS, m_Zero()))
2299 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002300
David Majnemer27e89ba2015-05-21 23:04:21 +00002301 // X * 1 -> {X, false}
2302 if (match(RHS, m_One()))
2303 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002304
2305 if (OCF == OCF_SIGNED_MUL)
2306 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2307 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2308 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002309 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002310 }
2311
2312 return false;
2313}
2314
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002315/// \brief Recognize and process idiom involving test for multiplication
2316/// overflow.
2317///
2318/// The caller has matched a pattern of the form:
2319/// I = cmp u (mul(zext A, zext B), V
2320/// The function checks if this is a test for overflow and if so replaces
2321/// multiplication with call to 'mul.with.overflow' intrinsic.
2322///
2323/// \param I Compare instruction.
2324/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2325/// the compare instruction. Must be of integer type.
2326/// \param OtherVal The other argument of compare instruction.
2327/// \returns Instruction which must replace the compare instruction, NULL if no
2328/// replacement required.
2329static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2330 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002331 // Don't bother doing this transformation for pointers, don't do it for
2332 // vectors.
2333 if (!isa<IntegerType>(MulVal->getType()))
2334 return nullptr;
2335
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002336 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2337 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002338 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2339 if (!MulInstr)
2340 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002341 assert(MulInstr->getOpcode() == Instruction::Mul);
2342
David Majnemer634ca232014-11-01 23:46:05 +00002343 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2344 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002345 assert(LHS->getOpcode() == Instruction::ZExt);
2346 assert(RHS->getOpcode() == Instruction::ZExt);
2347 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2348
2349 // Calculate type and width of the result produced by mul.with.overflow.
2350 Type *TyA = A->getType(), *TyB = B->getType();
2351 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2352 WidthB = TyB->getPrimitiveSizeInBits();
2353 unsigned MulWidth;
2354 Type *MulType;
2355 if (WidthB > WidthA) {
2356 MulWidth = WidthB;
2357 MulType = TyB;
2358 } else {
2359 MulWidth = WidthA;
2360 MulType = TyA;
2361 }
2362
2363 // In order to replace the original mul with a narrower mul.with.overflow,
2364 // all uses must ignore upper bits of the product. The number of used low
2365 // bits must be not greater than the width of mul.with.overflow.
2366 if (MulVal->hasNUsesOrMore(2))
2367 for (User *U : MulVal->users()) {
2368 if (U == &I)
2369 continue;
2370 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2371 // Check if truncation ignores bits above MulWidth.
2372 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2373 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002374 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002375 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2376 // Check if AND ignores bits above MulWidth.
2377 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002378 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002379 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2380 const APInt &CVal = CI->getValue();
2381 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002382 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002383 }
2384 } else {
2385 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002386 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002387 }
2388 }
2389
2390 // Recognize patterns
2391 switch (I.getPredicate()) {
2392 case ICmpInst::ICMP_EQ:
2393 case ICmpInst::ICMP_NE:
2394 // Recognize pattern:
2395 // mulval = mul(zext A, zext B)
2396 // cmp eq/neq mulval, zext trunc mulval
2397 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2398 if (Zext->hasOneUse()) {
2399 Value *ZextArg = Zext->getOperand(0);
2400 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2401 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2402 break; //Recognized
2403 }
2404
2405 // Recognize pattern:
2406 // mulval = mul(zext A, zext B)
2407 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2408 ConstantInt *CI;
2409 Value *ValToMask;
2410 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2411 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002412 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002413 const APInt &CVal = CI->getValue() + 1;
2414 if (CVal.isPowerOf2()) {
2415 unsigned MaskWidth = CVal.logBase2();
2416 if (MaskWidth == MulWidth)
2417 break; // Recognized
2418 }
2419 }
Craig Topperf40110f2014-04-25 05:29:35 +00002420 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002421
2422 case ICmpInst::ICMP_UGT:
2423 // Recognize pattern:
2424 // mulval = mul(zext A, zext B)
2425 // cmp ugt mulval, max
2426 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2427 APInt MaxVal = APInt::getMaxValue(MulWidth);
2428 MaxVal = MaxVal.zext(CI->getBitWidth());
2429 if (MaxVal.eq(CI->getValue()))
2430 break; // Recognized
2431 }
Craig Topperf40110f2014-04-25 05:29:35 +00002432 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002433
2434 case ICmpInst::ICMP_UGE:
2435 // Recognize pattern:
2436 // mulval = mul(zext A, zext B)
2437 // cmp uge mulval, max+1
2438 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2439 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2440 if (MaxVal.eq(CI->getValue()))
2441 break; // Recognized
2442 }
Craig Topperf40110f2014-04-25 05:29:35 +00002443 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002444
2445 case ICmpInst::ICMP_ULE:
2446 // Recognize pattern:
2447 // mulval = mul(zext A, zext B)
2448 // cmp ule mulval, max
2449 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2450 APInt MaxVal = APInt::getMaxValue(MulWidth);
2451 MaxVal = MaxVal.zext(CI->getBitWidth());
2452 if (MaxVal.eq(CI->getValue()))
2453 break; // Recognized
2454 }
Craig Topperf40110f2014-04-25 05:29:35 +00002455 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002456
2457 case ICmpInst::ICMP_ULT:
2458 // Recognize pattern:
2459 // mulval = mul(zext A, zext B)
2460 // cmp ule mulval, max + 1
2461 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002462 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002463 if (MaxVal.eq(CI->getValue()))
2464 break; // Recognized
2465 }
Craig Topperf40110f2014-04-25 05:29:35 +00002466 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002467
2468 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002469 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002470 }
2471
2472 InstCombiner::BuilderTy *Builder = IC.Builder;
2473 Builder->SetInsertPoint(MulInstr);
2474 Module *M = I.getParent()->getParent()->getParent();
2475
2476 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2477 Value *MulA = A, *MulB = B;
2478 if (WidthA < MulWidth)
2479 MulA = Builder->CreateZExt(A, MulType);
2480 if (WidthB < MulWidth)
2481 MulB = Builder->CreateZExt(B, MulType);
2482 Value *F =
2483 Intrinsic::getDeclaration(M, Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002484 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002485 IC.Worklist.Add(MulInstr);
2486
2487 // If there are uses of mul result other than the comparison, we know that
2488 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002489 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002490 if (MulVal->hasNUsesOrMore(2)) {
2491 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2492 for (User *U : MulVal->users()) {
2493 if (U == &I || U == OtherVal)
2494 continue;
2495 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2496 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
2497 IC.ReplaceInstUsesWith(*TI, Mul);
2498 else
2499 TI->setOperand(0, Mul);
2500 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2501 assert(BO->getOpcode() == Instruction::And);
2502 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2503 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2504 APInt ShortMask = CI->getValue().trunc(MulWidth);
2505 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2506 Instruction *Zext =
2507 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2508 IC.Worklist.Add(Zext);
2509 IC.ReplaceInstUsesWith(*BO, Zext);
2510 } else {
2511 llvm_unreachable("Unexpected Binary operation");
2512 }
2513 IC.Worklist.Add(cast<Instruction>(U));
2514 }
2515 }
2516 if (isa<Instruction>(OtherVal))
2517 IC.Worklist.Add(cast<Instruction>(OtherVal));
2518
2519 // The original icmp gets replaced with the overflow value, maybe inverted
2520 // depending on predicate.
2521 bool Inverse = false;
2522 switch (I.getPredicate()) {
2523 case ICmpInst::ICMP_NE:
2524 break;
2525 case ICmpInst::ICMP_EQ:
2526 Inverse = true;
2527 break;
2528 case ICmpInst::ICMP_UGT:
2529 case ICmpInst::ICMP_UGE:
2530 if (I.getOperand(0) == MulVal)
2531 break;
2532 Inverse = true;
2533 break;
2534 case ICmpInst::ICMP_ULT:
2535 case ICmpInst::ICMP_ULE:
2536 if (I.getOperand(1) == MulVal)
2537 break;
2538 Inverse = true;
2539 break;
2540 default:
2541 llvm_unreachable("Unexpected predicate");
2542 }
2543 if (Inverse) {
2544 Value *Res = Builder->CreateExtractValue(Call, 1);
2545 return BinaryOperator::CreateNot(Res);
2546 }
2547
2548 return ExtractValueInst::Create(Call, 1);
2549}
2550
Owen Andersond490c2d2011-01-11 00:36:45 +00002551// DemandedBitsLHSMask - When performing a comparison against a constant,
2552// it is possible that not all the bits in the LHS are demanded. This helper
2553// method computes the mask that IS demanded.
2554static APInt DemandedBitsLHSMask(ICmpInst &I,
2555 unsigned BitWidth, bool isSignCheck) {
2556 if (isSignCheck)
2557 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002558
Owen Andersond490c2d2011-01-11 00:36:45 +00002559 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2560 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002561 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002562
Owen Andersond490c2d2011-01-11 00:36:45 +00002563 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002564 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002565 // correspond to the trailing ones of the comparand. The value of these
2566 // bits doesn't impact the outcome of the comparison, because any value
2567 // greater than the RHS must differ in a bit higher than these due to carry.
2568 case ICmpInst::ICMP_UGT: {
2569 unsigned trailingOnes = RHS.countTrailingOnes();
2570 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2571 return ~lowBitsSet;
2572 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002573
Owen Andersond490c2d2011-01-11 00:36:45 +00002574 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2575 // Any value less than the RHS must differ in a higher bit because of carries.
2576 case ICmpInst::ICMP_ULT: {
2577 unsigned trailingZeros = RHS.countTrailingZeros();
2578 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2579 return ~lowBitsSet;
2580 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002581
Owen Andersond490c2d2011-01-11 00:36:45 +00002582 default:
2583 return APInt::getAllOnesValue(BitWidth);
2584 }
Owen Andersond490c2d2011-01-11 00:36:45 +00002585}
Chris Lattner2188e402010-01-04 07:37:31 +00002586
Quentin Colombet5ab55552013-09-09 20:56:48 +00002587/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2588/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002589/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002590/// as subtract operands and their positions in those instructions.
2591/// The rational is that several architectures use the same instruction for
2592/// both subtract and cmp, thus it is better if the order of those operands
2593/// match.
2594/// \return true if Op0 and Op1 should be swapped.
2595static bool swapMayExposeCSEOpportunities(const Value * Op0,
2596 const Value * Op1) {
2597 // Filter out pointer value as those cannot appears directly in subtract.
2598 // FIXME: we may want to go through inttoptrs or bitcasts.
2599 if (Op0->getType()->isPointerTy())
2600 return false;
2601 // Count every uses of both Op0 and Op1 in a subtract.
2602 // Each time Op0 is the first operand, count -1: swapping is bad, the
2603 // subtract has already the same layout as the compare.
2604 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002605 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002606 // At the end, if the benefit is greater than 0, Op0 should come second to
2607 // expose more CSE opportunities.
2608 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002609 for (const User *U : Op0->users()) {
2610 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002611 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2612 continue;
2613 // If Op0 is the first argument, this is not beneficial to swap the
2614 // arguments.
2615 int LocalSwapBenefits = -1;
2616 unsigned Op1Idx = 1;
2617 if (BinOp->getOperand(Op1Idx) == Op0) {
2618 Op1Idx = 0;
2619 LocalSwapBenefits = 1;
2620 }
2621 if (BinOp->getOperand(Op1Idx) != Op1)
2622 continue;
2623 GlobalSwapBenefits += LocalSwapBenefits;
2624 }
2625 return GlobalSwapBenefits > 0;
2626}
2627
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002628/// \brief Check that one use is in the same block as the definition and all
2629/// other uses are in blocks dominated by a given block
2630///
2631/// \param DI Definition
2632/// \param UI Use
2633/// \param DB Block that must dominate all uses of \p DI outside
2634/// the parent block
2635/// \return true when \p UI is the only use of \p DI in the parent block
2636/// and all other uses of \p DI are in blocks dominated by \p DB.
2637///
2638bool InstCombiner::dominatesAllUses(const Instruction *DI,
2639 const Instruction *UI,
2640 const BasicBlock *DB) const {
2641 assert(DI && UI && "Instruction not defined\n");
2642 // ignore incomplete definitions
2643 if (!DI->getParent())
2644 return false;
2645 // DI and UI must be in the same block
2646 if (DI->getParent() != UI->getParent())
2647 return false;
2648 // Protect from self-referencing blocks
2649 if (DI->getParent() == DB)
2650 return false;
2651 // DominatorTree available?
2652 if (!DT)
2653 return false;
2654 for (const User *U : DI->users()) {
2655 auto *Usr = cast<Instruction>(U);
2656 if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
2657 return false;
2658 }
2659 return true;
2660}
2661
2662///
2663/// true when the instruction sequence within a block is select-cmp-br.
2664///
2665static bool isChainSelectCmpBranch(const SelectInst *SI) {
2666 const BasicBlock *BB = SI->getParent();
2667 if (!BB)
2668 return false;
2669 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
2670 if (!BI || BI->getNumSuccessors() != 2)
2671 return false;
2672 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
2673 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
2674 return false;
2675 return true;
2676}
2677
2678///
2679/// \brief True when a select result is replaced by one of its operands
2680/// in select-icmp sequence. This will eventually result in the elimination
2681/// of the select.
2682///
2683/// \param SI Select instruction
2684/// \param Icmp Compare instruction
2685/// \param SIOpd Operand that replaces the select
2686///
2687/// Notes:
2688/// - The replacement is global and requires dominator information
2689/// - The caller is responsible for the actual replacement
2690///
2691/// Example:
2692///
2693/// entry:
2694/// %4 = select i1 %3, %C* %0, %C* null
2695/// %5 = icmp eq %C* %4, null
2696/// br i1 %5, label %9, label %7
2697/// ...
2698/// ; <label>:7 ; preds = %entry
2699/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
2700/// ...
2701///
2702/// can be transformed to
2703///
2704/// %5 = icmp eq %C* %0, null
2705/// %6 = select i1 %3, i1 %5, i1 true
2706/// br i1 %6, label %9, label %7
2707/// ...
2708/// ; <label>:7 ; preds = %entry
2709/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
2710///
2711/// Similar when the first operand of the select is a constant or/and
2712/// the compare is for not equal rather than equal.
2713///
2714/// NOTE: The function is only called when the select and compare constants
2715/// are equal, the optimization can work only for EQ predicates. This is not a
2716/// major restriction since a NE compare should be 'normalized' to an equal
2717/// compare, which usually happens in the combiner and test case
2718/// select-cmp-br.ll
2719/// checks for it.
2720bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
2721 const ICmpInst *Icmp,
2722 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00002723 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002724 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
2725 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
2726 // The check for the unique predecessor is not the best that can be
2727 // done. But it protects efficiently against cases like when SI's
2728 // home block has two successors, Succ and Succ1, and Succ1 predecessor
2729 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
2730 // replaced can be reached on either path. So the uniqueness check
2731 // guarantees that the path all uses of SI (outside SI's parent) are on
2732 // is disjoint from all other paths out of SI. But that information
2733 // is more expensive to compute, and the trade-off here is in favor
2734 // of compile-time.
2735 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
2736 NumSel++;
2737 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
2738 return true;
2739 }
2740 }
2741 return false;
2742}
2743
Chris Lattner2188e402010-01-04 07:37:31 +00002744Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2745 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00002746 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002747 unsigned Op0Cplxity = getComplexity(Op0);
2748 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002749
Chris Lattner2188e402010-01-04 07:37:31 +00002750 /// Orders the operands of the compare so that they are listed from most
2751 /// complex to least complex. This puts constants before unary operators,
2752 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002753 if (Op0Cplxity < Op1Cplxity ||
2754 (Op0Cplxity == Op1Cplxity &&
2755 swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002756 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00002757 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002758 Changed = true;
2759 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002760
Jingyue Wu5e34ce32015-06-25 20:14:47 +00002761 if (Value *V =
2762 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC, &I))
Chris Lattner2188e402010-01-04 07:37:31 +00002763 return ReplaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002764
Pete Cooperbc5c5242011-12-01 03:58:40 +00002765 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00002766 // ie, abs(val) != 0 -> val != 0
Pete Cooperbc5c5242011-12-01 03:58:40 +00002767 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2768 {
Pete Cooperfdddc272011-12-01 19:13:26 +00002769 Value *Cond, *SelectTrue, *SelectFalse;
2770 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00002771 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00002772 if (Value *V = dyn_castNegVal(SelectTrue)) {
2773 if (V == SelectFalse)
2774 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2775 }
2776 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2777 if (V == SelectTrue)
2778 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00002779 }
2780 }
2781 }
2782
Chris Lattner229907c2011-07-18 04:54:35 +00002783 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002784
2785 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sands9dff9be2010-02-15 16:12:20 +00002786 if (Ty->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00002787 switch (I.getPredicate()) {
2788 default: llvm_unreachable("Invalid icmp instruction!");
2789 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2790 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2791 return BinaryOperator::CreateNot(Xor);
2792 }
2793 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2794 return BinaryOperator::CreateXor(Op0, Op1);
2795
2796 case ICmpInst::ICMP_UGT:
2797 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2798 // FALL THROUGH
2799 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2800 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2801 return BinaryOperator::CreateAnd(Not, Op1);
2802 }
2803 case ICmpInst::ICMP_SGT:
2804 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2805 // FALL THROUGH
2806 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2807 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2808 return BinaryOperator::CreateAnd(Not, Op0);
2809 }
2810 case ICmpInst::ICMP_UGE:
2811 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2812 // FALL THROUGH
2813 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2814 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2815 return BinaryOperator::CreateOr(Not, Op1);
2816 }
2817 case ICmpInst::ICMP_SGE:
2818 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2819 // FALL THROUGH
2820 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2821 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2822 return BinaryOperator::CreateOr(Not, Op0);
2823 }
2824 }
2825 }
2826
2827 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002828 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00002829 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002830 else // Get pointer size.
2831 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002832
Chris Lattner2188e402010-01-04 07:37:31 +00002833 bool isSignBit = false;
2834
2835 // See if we are doing a comparison with a constant.
2836 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002837 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002838
Owen Anderson1294ea72010-12-17 18:08:00 +00002839 // Match the following pattern, which is a common idiom when writing
2840 // overflow-safe integer arithmetic function. The source performs an
2841 // addition in wider type, and explicitly checks for overflow using
2842 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2843 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00002844 //
2845 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00002846 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00002847 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00002848 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00002849 // sum = a + b
2850 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00002851 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00002852 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00002853 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00002854 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00002855 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00002856 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00002857 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002858
David Majnemera0afb552015-01-14 19:26:56 +00002859 // The following transforms are only 'worth it' if the only user of the
2860 // subtraction is the icmp.
2861 if (Op0->hasOneUse()) {
2862 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2863 if (I.isEquality() && CI->isZero() &&
2864 match(Op0, m_Sub(m_Value(A), m_Value(B))))
2865 return new ICmpInst(I.getPredicate(), A, B);
2866
2867 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
2868 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
2869 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2870 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
2871
2872 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
2873 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
2874 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2875 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
2876
2877 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
2878 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
2879 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2880 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
2881
2882 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
2883 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
2884 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2885 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00002886 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002887
Chris Lattner2188e402010-01-04 07:37:31 +00002888 // If we have an icmp le or icmp ge instruction, turn it into the
2889 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2890 // them being folded in the code below. The SimplifyICmpInst code has
2891 // already handled the edge cases for us, so we just assert on them.
2892 switch (I.getPredicate()) {
2893 default: break;
2894 case ICmpInst::ICMP_ULE:
2895 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2896 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002897 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002898 case ICmpInst::ICMP_SLE:
2899 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2900 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002901 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002902 case ICmpInst::ICMP_UGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002903 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002904 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002905 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002906 case ICmpInst::ICMP_SGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002907 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002908 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002909 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002910 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002911
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00002912 if (I.isEquality()) {
2913 ConstantInt *CI2;
2914 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
2915 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00002916 // (icmp eq/ne (ashr/lshr const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00002917 if (Instruction *Inst = FoldICmpCstShrCst(I, Op0, A, CI, CI2))
2918 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00002919 }
David Majnemer59939ac2014-10-19 08:23:08 +00002920 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
2921 // (icmp eq/ne (shl const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00002922 if (Instruction *Inst = FoldICmpCstShlCst(I, Op0, A, CI, CI2))
2923 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00002924 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00002925 }
2926
Chris Lattner2188e402010-01-04 07:37:31 +00002927 // If this comparison is a normal comparison, it demands all
2928 // bits, if it is a sign bit comparison, it only demands the sign bit.
2929 bool UnusedBit;
2930 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2931 }
2932
2933 // See if we can fold the comparison based on range information we can get
2934 // by checking whether bits are known to be zero or one in the input.
2935 if (BitWidth != 0) {
2936 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2937 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2938
2939 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00002940 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00002941 Op0KnownZero, Op0KnownOne, 0))
2942 return &I;
2943 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002944 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
2945 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00002946 return &I;
2947
2948 // Given the known and unknown bits, compute a range that the LHS could be
2949 // in. Compute the Min, Max and RHS values based on the known bits. For the
2950 // EQ and NE we use unsigned values.
2951 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2952 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2953 if (I.isSigned()) {
2954 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2955 Op0Min, Op0Max);
2956 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2957 Op1Min, Op1Max);
2958 } else {
2959 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2960 Op0Min, Op0Max);
2961 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2962 Op1Min, Op1Max);
2963 }
2964
2965 // If Min and Max are known to be the same, then SimplifyDemandedBits
2966 // figured out that the LHS is a constant. Just constant fold this now so
2967 // that code below can assume that Min != Max.
2968 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2969 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00002970 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002971 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2972 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00002973 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00002974
2975 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00002976 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00002977 switch (I.getPredicate()) {
2978 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00002979 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00002980 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002981 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002982
Chris Lattnerf7e89612010-11-21 06:44:42 +00002983 // If all bits are known zero except for one, then we know at most one
2984 // bit is set. If the comparison is against zero, then this is a check
2985 // to see if *that* bit is set.
2986 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002987 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00002988 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00002989 Value *LHS = nullptr;
2990 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002991 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2992 LHSC->getValue() != Op0KnownZeroInverted)
2993 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002994
Chris Lattnerf7e89612010-11-21 06:44:42 +00002995 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattnere5afa152010-11-23 02:42:04 +00002996 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002997 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00002998 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002999 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003000 APInt ValToCheck = Op0KnownZeroInverted;
3001 if (ValToCheck.isPowerOf2()) {
3002 unsigned CmpVal = ValToCheck.countTrailingZeros();
3003 return new ICmpInst(ICmpInst::ICMP_NE, X,
3004 ConstantInt::get(X->getType(), CmpVal));
3005 } else if ((++ValToCheck).isPowerOf2()) {
3006 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3007 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3008 ConstantInt::get(X->getType(), CmpVal));
3009 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003010 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003011
Chris Lattnerf7e89612010-11-21 06:44:42 +00003012 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattnere5afa152010-11-23 02:42:04 +00003013 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00003014 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003015 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003016 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003017 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00003018 ConstantInt::get(X->getType(),
3019 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003020 }
Chris Lattner2188e402010-01-04 07:37:31 +00003021 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003022 }
3023 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00003024 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00003025 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003026
Chris Lattnerf7e89612010-11-21 06:44:42 +00003027 // If all bits are known zero except for one, then we know at most one
3028 // bit is set. If the comparison is against zero, then this is a check
3029 // to see if *that* bit is set.
3030 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003031 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003032 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003033 Value *LHS = nullptr;
3034 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003035 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3036 LHSC->getValue() != Op0KnownZeroInverted)
3037 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003038
Chris Lattnerf7e89612010-11-21 06:44:42 +00003039 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattnere5afa152010-11-23 02:42:04 +00003040 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003041 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00003042 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003043 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003044 APInt ValToCheck = Op0KnownZeroInverted;
3045 if (ValToCheck.isPowerOf2()) {
3046 unsigned CmpVal = ValToCheck.countTrailingZeros();
3047 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3048 ConstantInt::get(X->getType(), CmpVal));
3049 } else if ((++ValToCheck).isPowerOf2()) {
3050 unsigned CmpVal = ValToCheck.countTrailingZeros();
3051 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3052 ConstantInt::get(X->getType(), CmpVal));
3053 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003054 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003055
Chris Lattnerf7e89612010-11-21 06:44:42 +00003056 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattnere5afa152010-11-23 02:42:04 +00003057 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00003058 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003059 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003060 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003061 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00003062 ConstantInt::get(X->getType(),
3063 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003064 }
Chris Lattner2188e402010-01-04 07:37:31 +00003065 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003066 }
Chris Lattner2188e402010-01-04 07:37:31 +00003067 case ICmpInst::ICMP_ULT:
3068 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003069 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003070 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003071 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003072 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3073 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3074 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3075 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
3076 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003077 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003078
3079 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3080 if (CI->isMinValue(true))
3081 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3082 Constant::getAllOnesValue(Op0->getType()));
3083 }
3084 break;
3085 case ICmpInst::ICMP_UGT:
3086 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003087 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003088 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003089 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003090
3091 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3092 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3093 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3094 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
3095 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003096 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003097
3098 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3099 if (CI->isMaxValue(true))
3100 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3101 Constant::getNullValue(Op0->getType()));
3102 }
3103 break;
3104 case ICmpInst::ICMP_SLT:
3105 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003106 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003107 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003108 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003109 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3110 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3112 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3113 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003114 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003115 }
3116 break;
3117 case ICmpInst::ICMP_SGT:
3118 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003119 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003120 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003121 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003122
3123 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3124 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3125 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3126 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3127 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003128 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003129 }
3130 break;
3131 case ICmpInst::ICMP_SGE:
3132 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3133 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003134 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003135 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003136 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003137 break;
3138 case ICmpInst::ICMP_SLE:
3139 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3140 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003141 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003142 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003143 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003144 break;
3145 case ICmpInst::ICMP_UGE:
3146 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3147 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003148 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003149 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003150 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003151 break;
3152 case ICmpInst::ICMP_ULE:
3153 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3154 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003155 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003156 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00003157 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003158 break;
3159 }
3160
3161 // Turn a signed comparison into an unsigned one if both operands
3162 // are known to have the same sign.
3163 if (I.isSigned() &&
3164 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3165 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3166 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3167 }
3168
3169 // Test if the ICmpInst instruction is used exclusively by a select as
3170 // part of a minimum or maximum operation. If so, refrain from doing
3171 // any other folding. This helps out other analyses which understand
3172 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3173 // and CodeGen. And in this case, at least one of the comparison
3174 // operands has at least one user besides the compare (the select),
3175 // which would often largely negate the benefit of folding anyway.
3176 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003177 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003178 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3179 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003180 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003181
3182 // See if we are doing a comparison between a constant and an instruction that
3183 // can be folded into the comparison.
3184 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003185 // Since the RHS is a ConstantInt (CI), if the left hand side is an
3186 // instruction, see if that instruction also has constants so that the
3187 // instruction can be folded into the icmp
Chris Lattner2188e402010-01-04 07:37:31 +00003188 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3189 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
3190 return Res;
3191 }
3192
3193 // Handle icmp with constant (but not simple integer constant) RHS
3194 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3195 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3196 switch (LHSI->getOpcode()) {
3197 case Instruction::GetElementPtr:
3198 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3199 if (RHSC->isNullValue() &&
3200 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3201 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3202 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3203 break;
3204 case Instruction::PHI:
3205 // Only fold icmp into the PHI if the phi and icmp are in the same
3206 // block. If in the same block, we're encouraging jump threading. If
3207 // not, we are just pessimizing the code by making an i1 phi.
3208 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003209 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003210 return NV;
3211 break;
3212 case Instruction::Select: {
3213 // If either operand of the select is a constant, we can fold the
3214 // comparison into the select arms, which will cause one to be
3215 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003216 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003217 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003218 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003219 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003220 CI = dyn_cast<ConstantInt>(Op1);
3221 }
3222 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003223 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003224 CI = dyn_cast<ConstantInt>(Op2);
3225 }
Chris Lattner2188e402010-01-04 07:37:31 +00003226
3227 // We only want to perform this transformation if it will not lead to
3228 // additional code. This is true if either both sides of the select
3229 // fold to a constant (in which case the icmp is replaced with a select
3230 // which will usually simplify) or this is the only user of the
3231 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003232 // select+icmp) or all uses of the select can be replaced based on
3233 // dominance information ("Global cases").
3234 bool Transform = false;
3235 if (Op1 && Op2)
3236 Transform = true;
3237 else if (Op1 || Op2) {
3238 // Local case
3239 if (LHSI->hasOneUse())
3240 Transform = true;
3241 // Global cases
3242 else if (CI && !CI->isZero())
3243 // When Op1 is constant try replacing select with second operand.
3244 // Otherwise Op2 is constant and try replacing select with first
3245 // operand.
3246 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3247 Op1 ? 2 : 1);
3248 }
3249 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003250 if (!Op1)
3251 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3252 RHSC, I.getName());
3253 if (!Op2)
3254 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3255 RHSC, I.getName());
3256 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3257 }
3258 break;
3259 }
Chris Lattner2188e402010-01-04 07:37:31 +00003260 case Instruction::IntToPtr:
3261 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003262 if (RHSC->isNullValue() &&
3263 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003264 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3265 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3266 break;
3267
3268 case Instruction::Load:
3269 // Try to optimize things like "A[i] > 4" to index computations.
3270 if (GetElementPtrInst *GEP =
3271 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3272 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3273 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3274 !cast<LoadInst>(LHSI)->isVolatile())
3275 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3276 return Res;
3277 }
3278 break;
3279 }
3280 }
3281
3282 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3283 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
3284 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
3285 return NI;
3286 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
3287 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
3288 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3289 return NI;
3290
Hans Wennborgf1f36512015-10-07 00:20:07 +00003291 // Try to optimize equality comparisons against alloca-based pointers.
3292 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3293 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3294 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
3295 if (Instruction *New = FoldAllocaCmp(I, Alloca, Op1))
3296 return New;
3297 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
3298 if (Instruction *New = FoldAllocaCmp(I, Alloca, Op0))
3299 return New;
3300 }
3301
Chris Lattner2188e402010-01-04 07:37:31 +00003302 // Test to see if the operands of the icmp are casted versions of other
3303 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3304 // now.
3305 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003306 if (Op0->getType()->isPointerTy() &&
3307 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003308 // We keep moving the cast from the left operand over to the right
3309 // operand, where it can often be eliminated completely.
3310 Op0 = CI->getOperand(0);
3311
3312 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3313 // so eliminate it as well.
3314 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3315 Op1 = CI2->getOperand(0);
3316
3317 // If Op1 is a constant, we can fold the cast into the constant.
3318 if (Op0->getType() != Op1->getType()) {
3319 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3320 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3321 } else {
3322 // Otherwise, cast the RHS right before the icmp
3323 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3324 }
3325 }
3326 return new ICmpInst(I.getPredicate(), Op0, Op1);
3327 }
3328 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003329
Chris Lattner2188e402010-01-04 07:37:31 +00003330 if (isa<CastInst>(Op0)) {
3331 // Handle the special case of: icmp (cast bool to X), <cst>
3332 // This comes up when you have code like
3333 // int X = A < B;
3334 // if (X) ...
3335 // For generality, we handle any zero-extension of any operand comparison
3336 // with a constant or another cast from the same type.
3337 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
3338 if (Instruction *R = visitICmpInstWithCastAndCast(I))
3339 return R;
3340 }
Chris Lattner2188e402010-01-04 07:37:31 +00003341
Duncan Sandse5220012011-02-17 07:46:37 +00003342 // Special logic for binary operators.
3343 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3344 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3345 if (BO0 || BO1) {
3346 CmpInst::Predicate Pred = I.getPredicate();
3347 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3348 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3349 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3350 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3351 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3352 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3353 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3354 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3355 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3356
3357 // Analyze the case when either Op0 or Op1 is an add instruction.
3358 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
Craig Topperf40110f2014-04-25 05:29:35 +00003359 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandse5220012011-02-17 07:46:37 +00003360 if (BO0 && BO0->getOpcode() == Instruction::Add)
3361 A = BO0->getOperand(0), B = BO0->getOperand(1);
3362 if (BO1 && BO1->getOpcode() == Instruction::Add)
3363 C = BO1->getOperand(0), D = BO1->getOperand(1);
3364
David Majnemer549f4f22014-11-01 09:09:51 +00003365 // icmp (X+cst) < 0 --> X < -cst
3366 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3367 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3368 if (!RHSC->isMinValue(/*isSigned=*/true))
3369 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3370
Duncan Sandse5220012011-02-17 07:46:37 +00003371 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3372 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3373 return new ICmpInst(Pred, A == Op1 ? B : A,
3374 Constant::getNullValue(Op1->getType()));
3375
3376 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3377 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3378 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3379 C == Op0 ? D : C);
3380
Duncan Sands84653b32011-02-18 16:25:37 +00003381 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003382 if (A && C && (A == C || A == D || B == C || B == D) &&
3383 NoOp0WrapProblem && NoOp1WrapProblem &&
3384 // Try not to increase register pressure.
3385 BO0->hasOneUse() && BO1->hasOneUse()) {
3386 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003387 Value *Y, *Z;
3388 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003389 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003390 Y = B;
3391 Z = D;
3392 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003393 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003394 Y = B;
3395 Z = C;
3396 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003397 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003398 Y = A;
3399 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003400 } else {
3401 assert(B == D);
3402 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003403 Y = A;
3404 Z = C;
3405 }
Duncan Sandse5220012011-02-17 07:46:37 +00003406 return new ICmpInst(Pred, Y, Z);
3407 }
3408
David Majnemerb81cd632013-04-11 20:05:46 +00003409 // icmp slt (X + -1), Y -> icmp sle X, Y
3410 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3411 match(B, m_AllOnes()))
3412 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3413
3414 // icmp sge (X + -1), Y -> icmp sgt X, Y
3415 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3416 match(B, m_AllOnes()))
3417 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3418
3419 // icmp sle (X + 1), Y -> icmp slt X, Y
3420 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3421 match(B, m_One()))
3422 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3423
3424 // icmp sgt (X + 1), Y -> icmp sge X, Y
3425 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3426 match(B, m_One()))
3427 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3428
Michael Liaoc65d3862015-10-19 22:08:14 +00003429 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3430 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3431 match(D, m_AllOnes()))
3432 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3433
3434 // icmp sle X, (Y + -1) -> icmp slt X, Y
3435 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3436 match(D, m_AllOnes()))
3437 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3438
3439 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3440 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3441 match(D, m_One()))
3442 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3443
3444 // icmp slt X, (Y + 1) -> icmp sle X, Y
3445 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3446 match(D, m_One()))
3447 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3448
David Majnemerb81cd632013-04-11 20:05:46 +00003449 // if C1 has greater magnitude than C2:
3450 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3451 // s.t. C3 = C1 - C2
3452 //
3453 // if C2 has greater magnitude than C1:
3454 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3455 // s.t. C3 = C2 - C1
3456 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3457 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3458 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3459 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3460 const APInt &AP1 = C1->getValue();
3461 const APInt &AP2 = C2->getValue();
3462 if (AP1.isNegative() == AP2.isNegative()) {
3463 APInt AP1Abs = C1->getValue().abs();
3464 APInt AP2Abs = C2->getValue().abs();
3465 if (AP1Abs.uge(AP2Abs)) {
3466 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3467 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3468 return new ICmpInst(Pred, NewAdd, C);
3469 } else {
3470 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3471 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3472 return new ICmpInst(Pred, A, NewAdd);
3473 }
3474 }
3475 }
3476
3477
Duncan Sandse5220012011-02-17 07:46:37 +00003478 // Analyze the case when either Op0 or Op1 is a sub instruction.
3479 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
Craig Topperf40110f2014-04-25 05:29:35 +00003480 A = nullptr; B = nullptr; C = nullptr; D = nullptr;
Duncan Sandse5220012011-02-17 07:46:37 +00003481 if (BO0 && BO0->getOpcode() == Instruction::Sub)
3482 A = BO0->getOperand(0), B = BO0->getOperand(1);
3483 if (BO1 && BO1->getOpcode() == Instruction::Sub)
3484 C = BO1->getOperand(0), D = BO1->getOperand(1);
3485
Duncan Sands84653b32011-02-18 16:25:37 +00003486 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3487 if (A == Op1 && NoOp0WrapProblem)
3488 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3489
3490 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3491 if (C == Op0 && NoOp1WrapProblem)
3492 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3493
3494 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003495 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3496 // Try not to increase register pressure.
3497 BO0->hasOneUse() && BO1->hasOneUse())
3498 return new ICmpInst(Pred, A, C);
3499
Duncan Sands84653b32011-02-18 16:25:37 +00003500 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3501 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3502 // Try not to increase register pressure.
3503 BO0->hasOneUse() && BO1->hasOneUse())
3504 return new ICmpInst(Pred, D, B);
3505
David Majnemer186c9422014-05-15 00:02:20 +00003506 // icmp (0-X) < cst --> x > -cst
3507 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3508 Value *X;
3509 if (match(BO0, m_Neg(m_Value(X))))
3510 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3511 if (!RHSC->isMinValue(/*isSigned=*/true))
3512 return new ICmpInst(I.getSwappedPredicate(), X,
3513 ConstantExpr::getNeg(RHSC));
3514 }
3515
Craig Topperf40110f2014-04-25 05:29:35 +00003516 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003517 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00003518 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3519 Op1 == BO0->getOperand(1))
3520 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003521 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00003522 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3523 Op0 == BO1->getOperand(1))
3524 SRem = BO1;
3525 if (SRem) {
3526 // We don't check hasOneUse to avoid increasing register pressure because
3527 // the value we use is the same value this instruction was already using.
3528 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3529 default: break;
3530 case ICmpInst::ICMP_EQ:
Nick Lewycky92db8e82011-03-06 03:36:19 +00003531 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003532 case ICmpInst::ICMP_NE:
Nick Lewycky92db8e82011-03-06 03:36:19 +00003533 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003534 case ICmpInst::ICMP_SGT:
3535 case ICmpInst::ICMP_SGE:
3536 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3537 Constant::getAllOnesValue(SRem->getType()));
3538 case ICmpInst::ICMP_SLT:
3539 case ICmpInst::ICMP_SLE:
3540 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3541 Constant::getNullValue(SRem->getType()));
3542 }
3543 }
3544
Duncan Sandse5220012011-02-17 07:46:37 +00003545 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
3546 BO0->hasOneUse() && BO1->hasOneUse() &&
3547 BO0->getOperand(1) == BO1->getOperand(1)) {
3548 switch (BO0->getOpcode()) {
3549 default: break;
3550 case Instruction::Add:
3551 case Instruction::Sub:
3552 case Instruction::Xor:
3553 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3554 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3555 BO1->getOperand(0));
3556 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
3557 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3558 if (CI->getValue().isSignBit()) {
3559 ICmpInst::Predicate Pred = I.isSigned()
3560 ? I.getUnsignedPredicate()
3561 : I.getSignedPredicate();
3562 return new ICmpInst(Pred, BO0->getOperand(0),
3563 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00003564 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003565
Chris Lattnerb1a15122011-07-15 06:08:15 +00003566 if (CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00003567 ICmpInst::Predicate Pred = I.isSigned()
3568 ? I.getUnsignedPredicate()
3569 : I.getSignedPredicate();
3570 Pred = I.getSwappedPredicate(Pred);
3571 return new ICmpInst(Pred, BO0->getOperand(0),
3572 BO1->getOperand(0));
3573 }
Chris Lattner2188e402010-01-04 07:37:31 +00003574 }
Duncan Sandse5220012011-02-17 07:46:37 +00003575 break;
3576 case Instruction::Mul:
3577 if (!I.isEquality())
3578 break;
3579
3580 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3581 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
3582 // Mask = -1 >> count-trailing-zeros(Cst).
3583 if (!CI->isZero() && !CI->isOne()) {
3584 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003585 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00003586 APInt::getLowBitsSet(AP.getBitWidth(),
3587 AP.getBitWidth() -
3588 AP.countTrailingZeros()));
3589 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
3590 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
3591 return new ICmpInst(I.getPredicate(), And1, And2);
3592 }
3593 }
3594 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00003595 case Instruction::UDiv:
3596 case Instruction::LShr:
3597 if (I.isSigned())
3598 break;
3599 // fall-through
3600 case Instruction::SDiv:
3601 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00003602 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00003603 break;
3604 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3605 BO1->getOperand(0));
3606 case Instruction::Shl: {
3607 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3608 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3609 if (!NUW && !NSW)
3610 break;
3611 if (!NSW && I.isSigned())
3612 break;
3613 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3614 BO1->getOperand(0));
3615 }
Chris Lattner2188e402010-01-04 07:37:31 +00003616 }
3617 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00003618
3619 if (BO0) {
3620 // Transform A & (L - 1) `ult` L --> L != 0
3621 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
3622 auto BitwiseAnd =
3623 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
3624
3625 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
3626 auto *Zero = Constant::getNullValue(BO0->getType());
3627 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
3628 }
3629 }
Chris Lattner2188e402010-01-04 07:37:31 +00003630 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003631
Chris Lattner2188e402010-01-04 07:37:31 +00003632 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00003633 // Transform (A & ~B) == 0 --> (A & B) != 0
3634 // and (A & ~B) != 0 --> (A & B) == 0
3635 // if A is a power of 2.
3636 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00003637 match(Op1, m_Zero()) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003638 isKnownToBeAPowerOfTwo(A, DL, false, 0, AC, &I, DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00003639 return new ICmpInst(I.getInversePredicate(),
3640 Builder->CreateAnd(A, B),
3641 Op1);
3642
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00003643 // ~x < ~y --> y < x
3644 // ~x < cst --> ~cst < x
3645 if (match(Op0, m_Not(m_Value(A)))) {
3646 if (match(Op1, m_Not(m_Value(B))))
3647 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00003648 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00003649 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
3650 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003651
Sanjoy Dasb6c59142015-04-10 21:07:09 +00003652 Instruction *AddI = nullptr;
3653 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
3654 m_Instruction(AddI))) &&
3655 isa<IntegerType>(A->getType())) {
3656 Value *Result;
3657 Constant *Overflow;
3658 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
3659 Overflow)) {
3660 ReplaceInstUsesWith(*AddI, Result);
3661 return ReplaceInstUsesWith(I, Overflow);
3662 }
3663 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003664
3665 // (zext a) * (zext b) --> llvm.umul.with.overflow.
3666 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3667 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
3668 return R;
3669 }
3670 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3671 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
3672 return R;
3673 }
Chris Lattner2188e402010-01-04 07:37:31 +00003674 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003675
Chris Lattner2188e402010-01-04 07:37:31 +00003676 if (I.isEquality()) {
3677 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00003678
Chris Lattner2188e402010-01-04 07:37:31 +00003679 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3680 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
3681 Value *OtherVal = A == Op1 ? B : A;
3682 return new ICmpInst(I.getPredicate(), OtherVal,
3683 Constant::getNullValue(A->getType()));
3684 }
3685
3686 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3687 // A^c1 == C^c2 --> A == C^(c1^c2)
3688 ConstantInt *C1, *C2;
3689 if (match(B, m_ConstantInt(C1)) &&
3690 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00003691 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003692 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00003693 return new ICmpInst(I.getPredicate(), A, Xor);
3694 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003695
Chris Lattner2188e402010-01-04 07:37:31 +00003696 // A^B == A^D -> B == D
3697 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
3698 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
3699 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
3700 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
3701 }
3702 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003703
Chris Lattner2188e402010-01-04 07:37:31 +00003704 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3705 (A == Op0 || B == Op0)) {
3706 // A == (A^B) -> B == 0
3707 Value *OtherVal = A == Op0 ? B : A;
3708 return new ICmpInst(I.getPredicate(), OtherVal,
3709 Constant::getNullValue(A->getType()));
3710 }
3711
Chris Lattner2188e402010-01-04 07:37:31 +00003712 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00003713 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00003714 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00003715 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003716
Chris Lattner2188e402010-01-04 07:37:31 +00003717 if (A == C) {
3718 X = B; Y = D; Z = A;
3719 } else if (A == D) {
3720 X = B; Y = C; Z = A;
3721 } else if (B == C) {
3722 X = A; Y = D; Z = B;
3723 } else if (B == D) {
3724 X = A; Y = C; Z = B;
3725 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003726
Chris Lattner2188e402010-01-04 07:37:31 +00003727 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003728 Op1 = Builder->CreateXor(X, Y);
3729 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00003730 I.setOperand(0, Op1);
3731 I.setOperand(1, Constant::getNullValue(Op1->getType()));
3732 return &I;
3733 }
3734 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003735
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003736 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00003737 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003738 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00003739 if ((Op0->hasOneUse() &&
3740 match(Op0, m_ZExt(m_Value(A))) &&
3741 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3742 (Op1->hasOneUse() &&
3743 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3744 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003745 APInt Pow2 = Cst1->getValue() + 1;
3746 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3747 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3748 return new ICmpInst(I.getPredicate(), A,
3749 Builder->CreateTrunc(B, A->getType()));
3750 }
3751
Benjamin Kramer03f3e242013-11-16 16:00:48 +00003752 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
3753 // For lshr and ashr pairs.
3754 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3755 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
3756 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3757 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
3758 unsigned TypeBits = Cst1->getBitWidth();
3759 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3760 if (ShAmt < TypeBits && ShAmt != 0) {
3761 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
3762 ? ICmpInst::ICMP_UGE
3763 : ICmpInst::ICMP_ULT;
3764 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3765 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
3766 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
3767 }
3768 }
3769
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00003770 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
3771 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
3772 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
3773 unsigned TypeBits = Cst1->getBitWidth();
3774 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3775 if (ShAmt < TypeBits && ShAmt != 0) {
3776 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3777 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
3778 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
3779 I.getName() + ".mask");
3780 return new ICmpInst(I.getPredicate(), And,
3781 Constant::getNullValue(Cst1->getType()));
3782 }
3783 }
3784
Chris Lattner1b06c712011-04-26 20:18:20 +00003785 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
3786 // "icmp (and X, mask), cst"
3787 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00003788 if (Op0->hasOneUse() &&
3789 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
3790 m_ConstantInt(ShAmt))))) &&
3791 match(Op1, m_ConstantInt(Cst1)) &&
3792 // Only do this when A has multiple uses. This is most important to do
3793 // when it exposes other optimizations.
3794 !A->hasOneUse()) {
3795 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003796
Chris Lattner1b06c712011-04-26 20:18:20 +00003797 if (ShAmt < ASize) {
3798 APInt MaskV =
3799 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3800 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003801
Chris Lattner1b06c712011-04-26 20:18:20 +00003802 APInt CmpV = Cst1->getValue().zext(ASize);
3803 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003804
Chris Lattner1b06c712011-04-26 20:18:20 +00003805 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3806 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3807 }
3808 }
Chris Lattner2188e402010-01-04 07:37:31 +00003809 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003810
David Majnemerc1eca5a2014-11-06 23:23:30 +00003811 // The 'cmpxchg' instruction returns an aggregate containing the old value and
3812 // an i1 which indicates whether or not we successfully did the swap.
3813 //
3814 // Replace comparisons between the old value and the expected value with the
3815 // indicator that 'cmpxchg' returns.
3816 //
3817 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
3818 // spuriously fail. In those cases, the old value may equal the expected
3819 // value but it is possible for the swap to not occur.
3820 if (I.getPredicate() == ICmpInst::ICMP_EQ)
3821 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
3822 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
3823 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
3824 !ACXI->isWeak())
3825 return ExtractValueInst::Create(ACXI, 1);
3826
Chris Lattner2188e402010-01-04 07:37:31 +00003827 {
3828 Value *X; ConstantInt *Cst;
3829 // icmp X+Cst, X
3830 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003831 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003832
3833 // icmp X, X+Cst
3834 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003835 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003836 }
Craig Topperf40110f2014-04-25 05:29:35 +00003837 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003838}
3839
Chris Lattner2188e402010-01-04 07:37:31 +00003840/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
Chris Lattner2188e402010-01-04 07:37:31 +00003841Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3842 Instruction *LHSI,
3843 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00003844 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003845 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003846
Chris Lattner2188e402010-01-04 07:37:31 +00003847 // Get the width of the mantissa. We don't want to hack on conversions that
3848 // might lose information from the integer, e.g. "i64 -> float"
3849 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00003850 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003851
Matt Arsenault55e73122015-01-06 15:50:59 +00003852 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
3853
Chris Lattner2188e402010-01-04 07:37:31 +00003854 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003855
Matt Arsenault55e73122015-01-06 15:50:59 +00003856 if (I.isEquality()) {
3857 FCmpInst::Predicate P = I.getPredicate();
3858 bool IsExact = false;
3859 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
3860 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
3861
3862 // If the floating point constant isn't an integer value, we know if we will
3863 // ever compare equal / not equal to it.
3864 if (!IsExact) {
3865 // TODO: Can never be -0.0 and other non-representable values
3866 APFloat RHSRoundInt(RHS);
3867 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
3868 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
3869 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
3870 return ReplaceInstUsesWith(I, Builder->getFalse());
3871
3872 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
3873 return ReplaceInstUsesWith(I, Builder->getTrue());
3874 }
3875 }
3876
3877 // TODO: If the constant is exactly representable, is it always OK to do
3878 // equality compares as integer?
3879 }
3880
Arch D. Robison8ed08542015-09-15 17:51:59 +00003881 // Check to see that the input is converted from an integer type that is small
3882 // enough that preserves all bits. TODO: check here for "known" sign bits.
3883 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3884 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00003885
Arch D. Robison8ed08542015-09-15 17:51:59 +00003886 // Following test does NOT adjust InputSize downwards for signed inputs,
3887 // because the most negative value still requires all the mantissa bits
3888 // to distinguish it from one less than that value.
3889 if ((int)InputSize > MantissaWidth) {
3890 // Conversion would lose accuracy. Check if loss can impact comparison.
3891 int Exp = ilogb(RHS);
3892 if (Exp == APFloat::IEK_Inf) {
3893 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
3894 if (MaxExponent < (int)InputSize - !LHSUnsigned)
3895 // Conversion could create infinity.
3896 return nullptr;
3897 } else {
3898 // Note that if RHS is zero or NaN, then Exp is negative
3899 // and first condition is trivially false.
3900 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
3901 // Conversion could affect comparison.
3902 return nullptr;
3903 }
3904 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003905
Chris Lattner2188e402010-01-04 07:37:31 +00003906 // Otherwise, we can potentially simplify the comparison. We know that it
3907 // will always come through as an integer value and we know the constant is
3908 // not a NAN (it would have been previously simplified).
3909 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00003910
Chris Lattner2188e402010-01-04 07:37:31 +00003911 ICmpInst::Predicate Pred;
3912 switch (I.getPredicate()) {
3913 default: llvm_unreachable("Unexpected predicate!");
3914 case FCmpInst::FCMP_UEQ:
3915 case FCmpInst::FCMP_OEQ:
3916 Pred = ICmpInst::ICMP_EQ;
3917 break;
3918 case FCmpInst::FCMP_UGT:
3919 case FCmpInst::FCMP_OGT:
3920 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3921 break;
3922 case FCmpInst::FCMP_UGE:
3923 case FCmpInst::FCMP_OGE:
3924 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3925 break;
3926 case FCmpInst::FCMP_ULT:
3927 case FCmpInst::FCMP_OLT:
3928 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3929 break;
3930 case FCmpInst::FCMP_ULE:
3931 case FCmpInst::FCMP_OLE:
3932 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3933 break;
3934 case FCmpInst::FCMP_UNE:
3935 case FCmpInst::FCMP_ONE:
3936 Pred = ICmpInst::ICMP_NE;
3937 break;
3938 case FCmpInst::FCMP_ORD:
Jakub Staszakbddea112013-06-06 20:18:46 +00003939 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003940 case FCmpInst::FCMP_UNO:
Jakub Staszakbddea112013-06-06 20:18:46 +00003941 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003942 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003943
Chris Lattner2188e402010-01-04 07:37:31 +00003944 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003945
Chris Lattner2188e402010-01-04 07:37:31 +00003946 // See if the FP constant is too large for the integer. For example,
3947 // comparing an i8 to 300.0.
3948 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003949
Chris Lattner2188e402010-01-04 07:37:31 +00003950 if (!LHSUnsigned) {
3951 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3952 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003953 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003954 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3955 APFloat::rmNearestTiesToEven);
3956 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3957 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3958 Pred == ICmpInst::ICMP_SLE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003959 return ReplaceInstUsesWith(I, Builder->getTrue());
3960 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003961 }
3962 } else {
3963 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3964 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003965 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003966 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3967 APFloat::rmNearestTiesToEven);
3968 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3969 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3970 Pred == ICmpInst::ICMP_ULE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003971 return ReplaceInstUsesWith(I, Builder->getTrue());
3972 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003973 }
3974 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003975
Chris Lattner2188e402010-01-04 07:37:31 +00003976 if (!LHSUnsigned) {
3977 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003978 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003979 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3980 APFloat::rmNearestTiesToEven);
3981 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3982 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3983 Pred == ICmpInst::ICMP_SGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003984 return ReplaceInstUsesWith(I, Builder->getTrue());
3985 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003986 }
Devang Patel698452b2012-02-13 23:05:18 +00003987 } else {
3988 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003989 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00003990 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3991 APFloat::rmNearestTiesToEven);
3992 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3993 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3994 Pred == ICmpInst::ICMP_UGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003995 return ReplaceInstUsesWith(I, Builder->getTrue());
3996 return ReplaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00003997 }
Chris Lattner2188e402010-01-04 07:37:31 +00003998 }
3999
4000 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4001 // [0, UMAX], but it may still be fractional. See if it is fractional by
4002 // casting the FP value to the integer value and back, checking for equality.
4003 // Don't do this for zero, because -0.0 is not fractional.
4004 Constant *RHSInt = LHSUnsigned
4005 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4006 : ConstantExpr::getFPToSI(RHSC, IntTy);
4007 if (!RHS.isZero()) {
4008 bool Equal = LHSUnsigned
4009 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4010 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4011 if (!Equal) {
4012 // If we had a comparison against a fractional value, we have to adjust
4013 // the compare predicate and sometimes the value. RHSC is rounded towards
4014 // zero at this point.
4015 switch (Pred) {
4016 default: llvm_unreachable("Unexpected integer comparison!");
4017 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Jakub Staszakbddea112013-06-06 20:18:46 +00004018 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004019 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Jakub Staszakbddea112013-06-06 20:18:46 +00004020 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004021 case ICmpInst::ICMP_ULE:
4022 // (float)int <= 4.4 --> int <= 4
4023 // (float)int <= -4.4 --> false
4024 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00004025 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004026 break;
4027 case ICmpInst::ICMP_SLE:
4028 // (float)int <= 4.4 --> int <= 4
4029 // (float)int <= -4.4 --> int < -4
4030 if (RHS.isNegative())
4031 Pred = ICmpInst::ICMP_SLT;
4032 break;
4033 case ICmpInst::ICMP_ULT:
4034 // (float)int < -4.4 --> false
4035 // (float)int < 4.4 --> int <= 4
4036 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00004037 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004038 Pred = ICmpInst::ICMP_ULE;
4039 break;
4040 case ICmpInst::ICMP_SLT:
4041 // (float)int < -4.4 --> int < -4
4042 // (float)int < 4.4 --> int <= 4
4043 if (!RHS.isNegative())
4044 Pred = ICmpInst::ICMP_SLE;
4045 break;
4046 case ICmpInst::ICMP_UGT:
4047 // (float)int > 4.4 --> int > 4
4048 // (float)int > -4.4 --> true
4049 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00004050 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004051 break;
4052 case ICmpInst::ICMP_SGT:
4053 // (float)int > 4.4 --> int > 4
4054 // (float)int > -4.4 --> int >= -4
4055 if (RHS.isNegative())
4056 Pred = ICmpInst::ICMP_SGE;
4057 break;
4058 case ICmpInst::ICMP_UGE:
4059 // (float)int >= -4.4 --> true
4060 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004061 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00004062 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004063 Pred = ICmpInst::ICMP_UGT;
4064 break;
4065 case ICmpInst::ICMP_SGE:
4066 // (float)int >= -4.4 --> int >= -4
4067 // (float)int >= 4.4 --> int > 4
4068 if (!RHS.isNegative())
4069 Pred = ICmpInst::ICMP_SGT;
4070 break;
4071 }
4072 }
4073 }
4074
4075 // Lower this FP comparison into an appropriate integer version of the
4076 // comparison.
4077 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4078}
4079
4080Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4081 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004082
Chris Lattner2188e402010-01-04 07:37:31 +00004083 /// Orders the operands of the compare so that they are listed from most
4084 /// complex to least complex. This puts constants before unary operators,
4085 /// before binary operators.
4086 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4087 I.swapOperands();
4088 Changed = true;
4089 }
4090
4091 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004092
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004093 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
4094 I.getFastMathFlags(), DL, TLI, DT, AC, &I))
Chris Lattner2188e402010-01-04 07:37:31 +00004095 return ReplaceInstUsesWith(I, V);
4096
4097 // Simplify 'fcmp pred X, X'
4098 if (Op0 == Op1) {
4099 switch (I.getPredicate()) {
4100 default: llvm_unreachable("Unknown predicate!");
4101 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4102 case FCmpInst::FCMP_ULT: // True if unordered or less than
4103 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4104 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4105 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4106 I.setPredicate(FCmpInst::FCMP_UNO);
4107 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4108 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004109
Chris Lattner2188e402010-01-04 07:37:31 +00004110 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4111 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4112 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4113 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4114 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4115 I.setPredicate(FCmpInst::FCMP_ORD);
4116 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4117 return &I;
4118 }
4119 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004120
James Molloy2b21a7c2015-05-20 18:41:25 +00004121 // Test if the FCmpInst instruction is used exclusively by a select as
4122 // part of a minimum or maximum operation. If so, refrain from doing
4123 // any other folding. This helps out other analyses which understand
4124 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4125 // and CodeGen. And in this case, at least one of the comparison
4126 // operands has at least one user besides the compare (the select),
4127 // which would often largely negate the benefit of folding anyway.
4128 if (I.hasOneUse())
4129 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4130 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4131 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4132 return nullptr;
4133
Chris Lattner2188e402010-01-04 07:37:31 +00004134 // Handle fcmp with constant RHS
4135 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4136 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4137 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004138 case Instruction::FPExt: {
4139 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4140 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4141 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4142 if (!RHSF)
4143 break;
4144
4145 const fltSemantics *Sem;
4146 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004147 if (LHSExt->getSrcTy()->isHalfTy())
4148 Sem = &APFloat::IEEEhalf;
4149 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004150 Sem = &APFloat::IEEEsingle;
4151 else if (LHSExt->getSrcTy()->isDoubleTy())
4152 Sem = &APFloat::IEEEdouble;
4153 else if (LHSExt->getSrcTy()->isFP128Ty())
4154 Sem = &APFloat::IEEEquad;
4155 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4156 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004157 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4158 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004159 else
4160 break;
4161
4162 bool Lossy;
4163 APFloat F = RHSF->getValueAPF();
4164 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4165
Jim Grosbach24ff8342011-09-30 18:45:50 +00004166 // Avoid lossy conversions and denormals. Zero is a special case
4167 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004168 APFloat Fabs = F;
4169 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004170 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004171 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4172 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004173
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004174 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4175 ConstantFP::get(RHSC->getContext(), F));
4176 break;
4177 }
Chris Lattner2188e402010-01-04 07:37:31 +00004178 case Instruction::PHI:
4179 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4180 // block. If in the same block, we're encouraging jump threading. If
4181 // not, we are just pessimizing the code by making an i1 phi.
4182 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004183 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004184 return NV;
4185 break;
4186 case Instruction::SIToFP:
4187 case Instruction::UIToFP:
4188 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
4189 return NV;
4190 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004191 case Instruction::FSub: {
4192 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4193 Value *Op;
4194 if (match(LHSI, m_FNeg(m_Value(Op))))
4195 return new FCmpInst(I.getSwappedPredicate(), Op,
4196 ConstantExpr::getFNeg(RHSC));
4197 break;
4198 }
Dan Gohman94732022010-02-24 06:46:09 +00004199 case Instruction::Load:
4200 if (GetElementPtrInst *GEP =
4201 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4202 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4203 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4204 !cast<LoadInst>(LHSI)->isVolatile())
4205 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
4206 return Res;
4207 }
4208 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004209 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004210 if (!RHSC->isNullValue())
4211 break;
4212
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004213 CallInst *CI = cast<CallInst>(LHSI);
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004214 const Function *F = CI->getCalledFunction();
4215 if (!F)
4216 break;
4217
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004218 // Various optimization for fabs compared with zero.
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004219 LibFunc::Func Func;
4220 if (F->getIntrinsicID() == Intrinsic::fabs ||
4221 (TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
4222 (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
4223 Func == LibFunc::fabsl))) {
4224 switch (I.getPredicate()) {
4225 default:
4226 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004227 // fabs(x) < 0 --> false
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004228 case FCmpInst::FCMP_OLT:
4229 return ReplaceInstUsesWith(I, Builder->getFalse());
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004230 // fabs(x) > 0 --> x != 0
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004231 case FCmpInst::FCMP_OGT:
4232 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004233 // fabs(x) <= 0 --> x == 0
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004234 case FCmpInst::FCMP_OLE:
4235 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004236 // fabs(x) >= 0 --> !isnan(x)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004237 case FCmpInst::FCMP_OGE:
4238 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004239 // fabs(x) == 0 --> x == 0
4240 // fabs(x) != 0 --> x != 0
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004241 case FCmpInst::FCMP_OEQ:
4242 case FCmpInst::FCMP_UEQ:
4243 case FCmpInst::FCMP_ONE:
4244 case FCmpInst::FCMP_UNE:
4245 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004246 }
4247 }
4248 }
Chris Lattner2188e402010-01-04 07:37:31 +00004249 }
Chris Lattner2188e402010-01-04 07:37:31 +00004250 }
4251
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004252 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004253 Value *X, *Y;
4254 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004255 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004256
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004257 // fcmp (fpext x), (fpext y) -> fcmp x, y
4258 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4259 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4260 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4261 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4262 RHSExt->getOperand(0));
4263
Craig Topperf40110f2014-04-25 05:29:35 +00004264 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004265}