blob: 3bfe49bbae36967703a539dfdd4daa6f8a8fde71 [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"
Silviu Barangaf29dfd32016-01-15 15:52:05 +000016#include "llvm/ADT/SetVector.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000017#include "llvm/ADT/Statistic.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000018#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000019#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/MemoryBuiltins.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000025#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000027#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000028#include "llvm/Support/Debug.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000029
Chris Lattner2188e402010-01-04 07:37:31 +000030using namespace llvm;
31using namespace PatternMatch;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "instcombine"
34
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000035// How many times is a select replaced by one of its operands?
36STATISTIC(NumSel, "Number of select opts");
37
38// Initialization Routines
39
Chris Lattner98457102011-02-10 05:23:05 +000040static ConstantInt *getOne(Constant *C) {
41 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
42}
43
Chris Lattner2188e402010-01-04 07:37:31 +000044static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
45 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
46}
47
48static bool HasAddOverflow(ConstantInt *Result,
49 ConstantInt *In1, ConstantInt *In2,
50 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000051 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000052 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000053
54 if (In2->isNegative())
55 return Result->getValue().sgt(In1->getValue());
56 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000057}
58
59/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
60/// overflowed for this type.
61static bool AddWithOverflow(Constant *&Result, Constant *In1,
62 Constant *In2, bool IsSigned = false) {
63 Result = ConstantExpr::getAdd(In1, In2);
64
Chris Lattner229907c2011-07-18 04:54:35 +000065 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000066 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
67 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
68 if (HasAddOverflow(ExtractElement(Result, Idx),
69 ExtractElement(In1, Idx),
70 ExtractElement(In2, Idx),
71 IsSigned))
72 return true;
73 }
74 return false;
75 }
76
77 return HasAddOverflow(cast<ConstantInt>(Result),
78 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
79 IsSigned);
80}
81
82static bool HasSubOverflow(ConstantInt *Result,
83 ConstantInt *In1, ConstantInt *In2,
84 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000085 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000086 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000087
Chris Lattnerb1a15122011-07-15 06:08:15 +000088 if (In2->isNegative())
89 return Result->getValue().slt(In1->getValue());
90
91 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000092}
93
94/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
95/// overflowed for this type.
96static bool SubWithOverflow(Constant *&Result, Constant *In1,
97 Constant *In2, bool IsSigned = false) {
98 Result = ConstantExpr::getSub(In1, In2);
99
Chris Lattner229907c2011-07-18 04:54:35 +0000100 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +0000101 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
102 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
103 if (HasSubOverflow(ExtractElement(Result, Idx),
104 ExtractElement(In1, Idx),
105 ExtractElement(In2, Idx),
106 IsSigned))
107 return true;
108 }
109 return false;
110 }
111
112 return HasSubOverflow(cast<ConstantInt>(Result),
113 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
114 IsSigned);
115}
116
117/// isSignBitCheck - Given an exploded icmp instruction, return true if the
118/// comparison only checks the sign bit. If it only checks the sign bit, set
119/// TrueIfSigned if the result of the comparison is true when the input value is
120/// signed.
121static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
122 bool &TrueIfSigned) {
123 switch (pred) {
124 case ICmpInst::ICMP_SLT: // True if LHS s< 0
125 TrueIfSigned = true;
126 return RHS->isZero();
127 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
128 TrueIfSigned = true;
129 return RHS->isAllOnesValue();
130 case ICmpInst::ICMP_SGT: // True if LHS s> -1
131 TrueIfSigned = false;
132 return RHS->isAllOnesValue();
133 case ICmpInst::ICMP_UGT:
134 // True if LHS u> RHS and RHS == high-bit-mask - 1
135 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000136 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000137 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000138 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
139 TrueIfSigned = true;
140 return RHS->getValue().isSignBit();
141 default:
142 return false;
143 }
144}
145
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000146/// Returns true if the exploded icmp can be expressed as a signed comparison
147/// to zero and updates the predicate accordingly.
148/// The signedness of the comparison is preserved.
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000149static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
150 if (!ICmpInst::isSigned(pred))
151 return false;
152
153 if (RHS->isZero())
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000154 return ICmpInst::isRelational(pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000155
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000156 if (RHS->isOne()) {
157 if (pred == ICmpInst::ICMP_SLT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000158 pred = ICmpInst::ICMP_SLE;
159 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000160 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000161 } else if (RHS->isAllOnesValue()) {
162 if (pred == ICmpInst::ICMP_SGT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000163 pred = ICmpInst::ICMP_SGE;
164 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000165 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000166 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000167
168 return false;
169}
170
Chris Lattner2188e402010-01-04 07:37:31 +0000171// isHighOnes - Return true if the constant is of the form 1+0+.
172// This is the same as lowones(~X).
173static bool isHighOnes(const ConstantInt *CI) {
174 return (~CI->getValue() + 1).isPowerOf2();
175}
176
Jim Grosbach129c52a2011-09-30 18:09:53 +0000177/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner2188e402010-01-04 07:37:31 +0000178/// set of known zero and one bits, compute the maximum and minimum values that
179/// could have the specified known zero and known one bits, returning them in
180/// min/max.
181static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
182 const APInt& KnownOne,
183 APInt& Min, APInt& Max) {
184 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
185 KnownZero.getBitWidth() == Min.getBitWidth() &&
186 KnownZero.getBitWidth() == Max.getBitWidth() &&
187 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
188 APInt UnknownBits = ~(KnownZero|KnownOne);
189
190 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
191 // bit if it is unknown.
192 Min = KnownOne;
193 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000194
Chris Lattner2188e402010-01-04 07:37:31 +0000195 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000196 Min.setBit(Min.getBitWidth()-1);
197 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000198 }
199}
200
201// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
202// a set of known zero and one bits, compute the maximum and minimum values that
203// could have the specified known zero and known one bits, returning them in
204// min/max.
205static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
206 const APInt &KnownOne,
207 APInt &Min, APInt &Max) {
208 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
209 KnownZero.getBitWidth() == Min.getBitWidth() &&
210 KnownZero.getBitWidth() == Max.getBitWidth() &&
211 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
212 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000213
Chris Lattner2188e402010-01-04 07:37:31 +0000214 // The minimum value is when the unknown bits are all zeros.
215 Min = KnownOne;
216 // The maximum value is when the unknown bits are all ones.
217 Max = KnownOne|UnknownBits;
218}
219
Chris Lattner2188e402010-01-04 07:37:31 +0000220/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
221/// cmp pred (load (gep GV, ...)), cmpcst
222/// where GV is a global variable with a constant initializer. Try to simplify
223/// this into some simple computation that does not need the load. For example
224/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
225///
226/// If AndCst is non-null, then the loaded value is masked with that constant
227/// before doing the comparison. This handles cases like "A[i]&4 == 0".
228Instruction *InstCombiner::
229FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
230 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000231 Constant *Init = GV->getInitializer();
232 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000233 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000234
Chris Lattnerfe741762012-01-31 02:55:06 +0000235 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000236 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000237
Chris Lattner2188e402010-01-04 07:37:31 +0000238 // There are many forms of this optimization we can handle, for now, just do
239 // the simple index into a single-dimensional array.
240 //
241 // Require: GEP GV, 0, i {{, constant indices}}
242 if (GEP->getNumOperands() < 3 ||
243 !isa<ConstantInt>(GEP->getOperand(1)) ||
244 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
245 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000246 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000247
248 // Check that indices after the variable are constants and in-range for the
249 // type they index. Collect the indices. This is typically for arrays of
250 // structs.
251 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000252
Chris Lattnerfe741762012-01-31 02:55:06 +0000253 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000254 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
255 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000256 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000257
Chris Lattner2188e402010-01-04 07:37:31 +0000258 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000259 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000260
Chris Lattner229907c2011-07-18 04:54:35 +0000261 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000262 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000263 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000264 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000265 EltTy = ATy->getElementType();
266 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000267 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000268 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000269
Chris Lattner2188e402010-01-04 07:37:31 +0000270 LaterIndices.push_back(IdxVal);
271 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000272
Chris Lattner2188e402010-01-04 07:37:31 +0000273 enum { Overdefined = -3, Undefined = -2 };
274
275 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000276
Chris Lattner2188e402010-01-04 07:37:31 +0000277 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
278 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
279 // and 87 is the second (and last) index. FirstTrueElement is -2 when
280 // undefined, otherwise set to the first true element. SecondTrueElement is
281 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
282 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
283
284 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
285 // form "i != 47 & i != 87". Same state transitions as for true elements.
286 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000287
Chris Lattner2188e402010-01-04 07:37:31 +0000288 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
289 /// define a state machine that triggers for ranges of values that the index
290 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
291 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
292 /// index in the range (inclusive). We use -2 for undefined here because we
293 /// use relative comparisons and don't want 0-1 to match -1.
294 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000295
Chris Lattner2188e402010-01-04 07:37:31 +0000296 // MagicBitvector - This is a magic bitvector where we set a bit if the
297 // comparison is true for element 'i'. If there are 64 elements or less in
298 // the array, this will fully represent all the comparison results.
299 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000300
Chris Lattner2188e402010-01-04 07:37:31 +0000301 // Scan the array and see if one of our patterns matches.
302 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000303 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
304 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000305 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000306
Chris Lattner2188e402010-01-04 07:37:31 +0000307 // If this is indexing an array of structures, get the structure element.
308 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000309 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000310
Chris Lattner2188e402010-01-04 07:37:31 +0000311 // If the element is masked, handle it.
312 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000313
Chris Lattner2188e402010-01-04 07:37:31 +0000314 // Find out if the comparison would be true or false for the i'th element.
315 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000316 CompareRHS, DL, TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000317 // If the result is undef for this element, ignore it.
318 if (isa<UndefValue>(C)) {
319 // Extend range state machines to cover this element in case there is an
320 // undef in the middle of the range.
321 if (TrueRangeEnd == (int)i-1)
322 TrueRangeEnd = i;
323 if (FalseRangeEnd == (int)i-1)
324 FalseRangeEnd = i;
325 continue;
326 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000327
Chris Lattner2188e402010-01-04 07:37:31 +0000328 // If we can't compute the result for any of the elements, we have to give
329 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000330 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000331
Chris Lattner2188e402010-01-04 07:37:31 +0000332 // Otherwise, we know if the comparison is true or false for this element,
333 // update our state machines.
334 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000335
Chris Lattner2188e402010-01-04 07:37:31 +0000336 // State machine for single/double/range index comparison.
337 if (IsTrueForElt) {
338 // Update the TrueElement state machine.
339 if (FirstTrueElement == Undefined)
340 FirstTrueElement = TrueRangeEnd = i; // First true element.
341 else {
342 // Update double-compare state machine.
343 if (SecondTrueElement == Undefined)
344 SecondTrueElement = i;
345 else
346 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000347
Chris Lattner2188e402010-01-04 07:37:31 +0000348 // Update range state machine.
349 if (TrueRangeEnd == (int)i-1)
350 TrueRangeEnd = i;
351 else
352 TrueRangeEnd = Overdefined;
353 }
354 } else {
355 // Update the FalseElement state machine.
356 if (FirstFalseElement == Undefined)
357 FirstFalseElement = FalseRangeEnd = i; // First false element.
358 else {
359 // Update double-compare state machine.
360 if (SecondFalseElement == Undefined)
361 SecondFalseElement = i;
362 else
363 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000364
Chris Lattner2188e402010-01-04 07:37:31 +0000365 // Update range state machine.
366 if (FalseRangeEnd == (int)i-1)
367 FalseRangeEnd = i;
368 else
369 FalseRangeEnd = Overdefined;
370 }
371 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000372
Chris Lattner2188e402010-01-04 07:37:31 +0000373 // If this element is in range, update our magic bitvector.
374 if (i < 64 && IsTrueForElt)
375 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000376
Chris Lattner2188e402010-01-04 07:37:31 +0000377 // If all of our states become overdefined, bail out early. Since the
378 // predicate is expensive, only check it every 8 elements. This is only
379 // really useful for really huge arrays.
380 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
381 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
382 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000383 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000384 }
385
386 // Now that we've scanned the entire array, emit our new comparison(s). We
387 // order the state machines in complexity of the generated code.
388 Value *Idx = GEP->getOperand(2);
389
Matt Arsenault5aeae182013-08-19 21:40:31 +0000390 // If the index is larger than the pointer size of the target, truncate the
391 // index down like the GEP would do implicitly. We don't have to do this for
392 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000393 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000394 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000395 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
396 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
397 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
398 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000399
Chris Lattner2188e402010-01-04 07:37:31 +0000400 // If the comparison is only true for one or two elements, emit direct
401 // comparisons.
402 if (SecondTrueElement != Overdefined) {
403 // None true -> false.
404 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000405 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000406
Chris Lattner2188e402010-01-04 07:37:31 +0000407 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000408
Chris Lattner2188e402010-01-04 07:37:31 +0000409 // True for one element -> 'i == 47'.
410 if (SecondTrueElement == Undefined)
411 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000412
Chris Lattner2188e402010-01-04 07:37:31 +0000413 // True for two elements -> 'i == 47 | i == 72'.
414 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
415 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
416 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
417 return BinaryOperator::CreateOr(C1, C2);
418 }
419
420 // If the comparison is only false for one or two elements, emit direct
421 // comparisons.
422 if (SecondFalseElement != Overdefined) {
423 // None false -> true.
424 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000425 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000426
Chris Lattner2188e402010-01-04 07:37:31 +0000427 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
428
429 // False for one element -> 'i != 47'.
430 if (SecondFalseElement == Undefined)
431 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000432
Chris Lattner2188e402010-01-04 07:37:31 +0000433 // False for two elements -> 'i != 47 & i != 72'.
434 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
435 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
436 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
437 return BinaryOperator::CreateAnd(C1, C2);
438 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000439
Chris Lattner2188e402010-01-04 07:37:31 +0000440 // If the comparison can be replaced with a range comparison for the elements
441 // where it is true, emit the range check.
442 if (TrueRangeEnd != Overdefined) {
443 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000444
Chris Lattner2188e402010-01-04 07:37:31 +0000445 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
446 if (FirstTrueElement) {
447 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
448 Idx = Builder->CreateAdd(Idx, Offs);
449 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000450
Chris Lattner2188e402010-01-04 07:37:31 +0000451 Value *End = ConstantInt::get(Idx->getType(),
452 TrueRangeEnd-FirstTrueElement+1);
453 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
454 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000455
Chris Lattner2188e402010-01-04 07:37:31 +0000456 // False range check.
457 if (FalseRangeEnd != Overdefined) {
458 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
459 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
460 if (FirstFalseElement) {
461 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
462 Idx = Builder->CreateAdd(Idx, Offs);
463 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000464
Chris Lattner2188e402010-01-04 07:37:31 +0000465 Value *End = ConstantInt::get(Idx->getType(),
466 FalseRangeEnd-FirstFalseElement);
467 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
468 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000469
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000470 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000471 // of this load, replace it with computation that does:
472 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000473 {
Craig Topperf40110f2014-04-25 05:29:35 +0000474 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000475
476 // Look for an appropriate type:
477 // - The type of Idx if the magic fits
478 // - The smallest fitting legal type if we have a DataLayout
479 // - Default to i32
480 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
481 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000482 else
483 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000484
Craig Topperf40110f2014-04-25 05:29:35 +0000485 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000486 Value *V = Builder->CreateIntCast(Idx, Ty, false);
487 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
488 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
489 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
490 }
Chris Lattner2188e402010-01-04 07:37:31 +0000491 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000492
Craig Topperf40110f2014-04-25 05:29:35 +0000493 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000494}
495
Chris Lattner2188e402010-01-04 07:37:31 +0000496/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
497/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
498/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
499/// be complex, and scales are involved. The above expression would also be
500/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
501/// This later form is less amenable to optimization though, and we are allowed
502/// to generate the first by knowing that pointer arithmetic doesn't overflow.
503///
504/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000505///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000506static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
507 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000508 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000509
Chris Lattner2188e402010-01-04 07:37:31 +0000510 // Check to see if this gep only has a single variable index. If so, and if
511 // any constant indices are a multiple of its scale, then we can compute this
512 // in terms of the scale of the variable index. For example, if the GEP
513 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
514 // because the expression will cross zero at the same point.
515 unsigned i, e = GEP->getNumOperands();
516 int64_t Offset = 0;
517 for (i = 1; i != e; ++i, ++GTI) {
518 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
519 // Compute the aggregate offset of constant indices.
520 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000521
Chris Lattner2188e402010-01-04 07:37:31 +0000522 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000523 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000524 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000525 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000526 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000527 Offset += Size*CI->getSExtValue();
528 }
529 } else {
530 // Found our variable index.
531 break;
532 }
533 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000534
Chris Lattner2188e402010-01-04 07:37:31 +0000535 // If there are no variable indices, we must have a constant offset, just
536 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000537 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000538
Chris Lattner2188e402010-01-04 07:37:31 +0000539 Value *VariableIdx = GEP->getOperand(i);
540 // Determine the scale factor of the variable element. For example, this is
541 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000542 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000543
Chris Lattner2188e402010-01-04 07:37:31 +0000544 // Verify that there are no other variable indices. If so, emit the hard way.
545 for (++i, ++GTI; i != e; ++i, ++GTI) {
546 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000547 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000548
Chris Lattner2188e402010-01-04 07:37:31 +0000549 // Compute the aggregate offset of constant indices.
550 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000551
Chris Lattner2188e402010-01-04 07:37:31 +0000552 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000553 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000554 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000555 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000556 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000557 Offset += Size*CI->getSExtValue();
558 }
559 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000560
Chris Lattner2188e402010-01-04 07:37:31 +0000561 // Okay, we know we have a single variable index, which must be a
562 // pointer/array/vector index. If there is no offset, life is simple, return
563 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000564 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000565 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000566 if (Offset == 0) {
567 // Cast to intptrty in case a truncation occurs. If an extension is needed,
568 // we don't need to bother extending: the extension won't affect where the
569 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000570 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000571 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
572 }
Chris Lattner2188e402010-01-04 07:37:31 +0000573 return VariableIdx;
574 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000575
Chris Lattner2188e402010-01-04 07:37:31 +0000576 // Otherwise, there is an index. The computation we will do will be modulo
577 // the pointer size, so get it.
578 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000579
Chris Lattner2188e402010-01-04 07:37:31 +0000580 Offset &= PtrSizeMask;
581 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000582
Chris Lattner2188e402010-01-04 07:37:31 +0000583 // To do this transformation, any constant index must be a multiple of the
584 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
585 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
586 // multiple of the variable scale.
587 int64_t NewOffs = Offset / (int64_t)VariableScale;
588 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000589 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000590
Chris Lattner2188e402010-01-04 07:37:31 +0000591 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000592 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000593 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
594 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000595 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000596 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000597}
598
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000599/// Returns true if we can rewrite Start as a GEP with pointer Base
600/// and some integer offset. The nodes that need to be re-written
601/// for this transformation will be added to Explored.
602static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
603 const DataLayout &DL,
604 SetVector<Value *> &Explored) {
605 SmallVector<Value *, 16> WorkList(1, Start);
606 Explored.insert(Base);
607
608 // The following traversal gives us an order which can be used
609 // when doing the final transformation. Since in the final
610 // transformation we create the PHI replacement instructions first,
611 // we don't have to get them in any particular order.
612 //
613 // However, for other instructions we will have to traverse the
614 // operands of an instruction first, which means that we have to
615 // do a post-order traversal.
616 while (!WorkList.empty()) {
617 SetVector<PHINode *> PHIs;
618
619 while (!WorkList.empty()) {
620 if (Explored.size() >= 100)
621 return false;
622
623 Value *V = WorkList.back();
624
625 if (Explored.count(V) != 0) {
626 WorkList.pop_back();
627 continue;
628 }
629
630 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
631 !isa<GEPOperator>(V) && !isa<PHINode>(V))
632 // We've found some value that we can't explore which is different from
633 // the base. Therefore we can't do this transformation.
634 return false;
635
636 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
637 auto *CI = dyn_cast<CastInst>(V);
638 if (!CI->isNoopCast(DL))
639 return false;
640
641 if (Explored.count(CI->getOperand(0)) == 0)
642 WorkList.push_back(CI->getOperand(0));
643 }
644
645 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
646 // We're limiting the GEP to having one index. This will preserve
647 // the original pointer type. We could handle more cases in the
648 // future.
649 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
650 GEP->getType() != Start->getType())
651 return false;
652
653 if (Explored.count(GEP->getOperand(0)) == 0)
654 WorkList.push_back(GEP->getOperand(0));
655 }
656
657 if (WorkList.back() == V) {
658 WorkList.pop_back();
659 // We've finished visiting this node, mark it as such.
660 Explored.insert(V);
661 }
662
663 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000664 // We cannot transform PHIs on unsplittable basic blocks.
665 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
666 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000667 Explored.insert(PN);
668 PHIs.insert(PN);
669 }
670 }
671
672 // Explore the PHI nodes further.
673 for (auto *PN : PHIs)
674 for (Value *Op : PN->incoming_values())
675 if (Explored.count(Op) == 0)
676 WorkList.push_back(Op);
677 }
678
679 // Make sure that we can do this. Since we can't insert GEPs in a basic
680 // block before a PHI node, we can't easily do this transformation if
681 // we have PHI node users of transformed instructions.
682 for (Value *Val : Explored) {
683 for (Value *Use : Val->uses()) {
684
685 auto *PHI = dyn_cast<PHINode>(Use);
686 auto *Inst = dyn_cast<Instruction>(Val);
687
688 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
689 Explored.count(PHI) == 0)
690 continue;
691
692 if (PHI->getParent() == Inst->getParent())
693 return false;
694 }
695 }
696 return true;
697}
698
699// Sets the appropriate insert point on Builder where we can add
700// a replacement Instruction for V (if that is possible).
701static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
702 bool Before = true) {
703 if (auto *PHI = dyn_cast<PHINode>(V)) {
704 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
705 return;
706 }
707 if (auto *I = dyn_cast<Instruction>(V)) {
708 if (!Before)
709 I = &*std::next(I->getIterator());
710 Builder.SetInsertPoint(I);
711 return;
712 }
713 if (auto *A = dyn_cast<Argument>(V)) {
714 // Set the insertion point in the entry block.
715 BasicBlock &Entry = A->getParent()->getEntryBlock();
716 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
717 return;
718 }
719 // Otherwise, this is a constant and we don't need to set a new
720 // insertion point.
721 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
722}
723
724/// Returns a re-written value of Start as an indexed GEP using Base as a
725/// pointer.
726static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
727 const DataLayout &DL,
728 SetVector<Value *> &Explored) {
729 // Perform all the substitutions. This is a bit tricky because we can
730 // have cycles in our use-def chains.
731 // 1. Create the PHI nodes without any incoming values.
732 // 2. Create all the other values.
733 // 3. Add the edges for the PHI nodes.
734 // 4. Emit GEPs to get the original pointers.
735 // 5. Remove the original instructions.
736 Type *IndexType = IntegerType::get(
737 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
738
739 DenseMap<Value *, Value *> NewInsts;
740 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
741
742 // Create the new PHI nodes, without adding any incoming values.
743 for (Value *Val : Explored) {
744 if (Val == Base)
745 continue;
746 // Create empty phi nodes. This avoids cyclic dependencies when creating
747 // the remaining instructions.
748 if (auto *PHI = dyn_cast<PHINode>(Val))
749 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
750 PHI->getName() + ".idx", PHI);
751 }
752 IRBuilder<> Builder(Base->getContext());
753
754 // Create all the other instructions.
755 for (Value *Val : Explored) {
756
757 if (NewInsts.find(Val) != NewInsts.end())
758 continue;
759
760 if (auto *CI = dyn_cast<CastInst>(Val)) {
761 NewInsts[CI] = NewInsts[CI->getOperand(0)];
762 continue;
763 }
764 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
765 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
766 : GEP->getOperand(1);
767 setInsertionPoint(Builder, GEP);
768 // Indices might need to be sign extended. GEPs will magically do
769 // this, but we need to do it ourselves here.
770 if (Index->getType()->getScalarSizeInBits() !=
771 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
772 Index = Builder.CreateSExtOrTrunc(
773 Index, NewInsts[GEP->getOperand(0)]->getType(),
774 GEP->getOperand(0)->getName() + ".sext");
775 }
776
777 auto *Op = NewInsts[GEP->getOperand(0)];
778 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
779 NewInsts[GEP] = Index;
780 else
781 NewInsts[GEP] = Builder.CreateNSWAdd(
782 Op, Index, GEP->getOperand(0)->getName() + ".add");
783 continue;
784 }
785 if (isa<PHINode>(Val))
786 continue;
787
788 llvm_unreachable("Unexpected instruction type");
789 }
790
791 // Add the incoming values to the PHI nodes.
792 for (Value *Val : Explored) {
793 if (Val == Base)
794 continue;
795 // All the instructions have been created, we can now add edges to the
796 // phi nodes.
797 if (auto *PHI = dyn_cast<PHINode>(Val)) {
798 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
799 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
800 Value *NewIncoming = PHI->getIncomingValue(I);
801
802 if (NewInsts.find(NewIncoming) != NewInsts.end())
803 NewIncoming = NewInsts[NewIncoming];
804
805 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
806 }
807 }
808 }
809
810 for (Value *Val : Explored) {
811 if (Val == Base)
812 continue;
813
814 // Depending on the type, for external users we have to emit
815 // a GEP or a GEP + ptrtoint.
816 setInsertionPoint(Builder, Val, false);
817
818 // If required, create an inttoptr instruction for Base.
819 Value *NewBase = Base;
820 if (!Base->getType()->isPointerTy())
821 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
822 Start->getName() + "to.ptr");
823
824 Value *GEP = Builder.CreateInBoundsGEP(
825 Start->getType()->getPointerElementType(), NewBase,
826 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
827
828 if (!Val->getType()->isPointerTy()) {
829 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
830 Val->getName() + ".conv");
831 GEP = Cast;
832 }
833 Val->replaceAllUsesWith(GEP);
834 }
835
836 return NewInsts[Start];
837}
838
839/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
840/// the input Value as a constant indexed GEP. Returns a pair containing
841/// the GEPs Pointer and Index.
842static std::pair<Value *, Value *>
843getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
844 Type *IndexType = IntegerType::get(V->getContext(),
845 DL.getPointerTypeSizeInBits(V->getType()));
846
847 Constant *Index = ConstantInt::getNullValue(IndexType);
848 while (true) {
849 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
850 // We accept only inbouds GEPs here to exclude the possibility of
851 // overflow.
852 if (!GEP->isInBounds())
853 break;
854 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
855 GEP->getType() == V->getType()) {
856 V = GEP->getOperand(0);
857 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
858 Index = ConstantExpr::getAdd(
859 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
860 continue;
861 }
862 break;
863 }
864 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
865 if (!CI->isNoopCast(DL))
866 break;
867 V = CI->getOperand(0);
868 continue;
869 }
870 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
871 if (!CI->isNoopCast(DL))
872 break;
873 V = CI->getOperand(0);
874 continue;
875 }
876 break;
877 }
878 return {V, Index};
879}
880
881// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
882// We can look through PHIs, GEPs and casts in order to determine a
883// common base between GEPLHS and RHS.
884static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
885 ICmpInst::Predicate Cond,
886 const DataLayout &DL) {
887 if (!GEPLHS->hasAllConstantIndices())
888 return nullptr;
889
890 Value *PtrBase, *Index;
891 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
892
893 // The set of nodes that will take part in this transformation.
894 SetVector<Value *> Nodes;
895
896 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
897 return nullptr;
898
899 // We know we can re-write this as
900 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
901 // Since we've only looked through inbouds GEPs we know that we
902 // can't have overflow on either side. We can therefore re-write
903 // this as:
904 // OFFSET1 cmp OFFSET2
905 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
906
907 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
908 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
909 // offset. Since Index is the offset of LHS to the base pointer, we will now
910 // compare the offsets instead of comparing the pointers.
911 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
912}
913
Chris Lattner2188e402010-01-04 07:37:31 +0000914/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
915/// else. At this point we know that the GEP is on the LHS of the comparison.
916Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
917 ICmpInst::Predicate Cond,
918 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000919 // Don't transform signed compares of GEPs into index compares. Even if the
920 // GEP is inbounds, the final add of the base pointer can have signed overflow
921 // and would change the result of the icmp.
922 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000923 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000924 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000925 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000926
Matt Arsenault44f60d02014-06-09 19:20:29 +0000927 // Look through bitcasts and addrspacecasts. We do not however want to remove
928 // 0 GEPs.
929 if (!isa<GetElementPtrInst>(RHS))
930 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000931
932 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000933 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000934 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
935 // This transformation (ignoring the base and scales) is valid because we
936 // know pointers can't overflow since the gep is inbounds. See if we can
937 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000938 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000939
Chris Lattner2188e402010-01-04 07:37:31 +0000940 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000941 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000942 Offset = EmitGEPOffset(GEPLHS);
943 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
944 Constant::getNullValue(Offset->getType()));
945 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
946 // If the base pointers are different, but the indices are the same, just
947 // compare the base pointer.
948 if (PtrBase != GEPRHS->getOperand(0)) {
949 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
950 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
951 GEPRHS->getOperand(0)->getType();
952 if (IndicesTheSame)
953 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
954 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
955 IndicesTheSame = false;
956 break;
957 }
958
959 // If all indices are the same, just compare the base pointers.
960 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000961 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000962
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000963 // If we're comparing GEPs with two base pointers that only differ in type
964 // and both GEPs have only constant indices or just one use, then fold
965 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000966 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000967 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
968 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
969 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000970 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000971 Value *LOffset = EmitGEPOffset(GEPLHS);
972 Value *ROffset = EmitGEPOffset(GEPRHS);
973
974 // If we looked through an addrspacecast between different sized address
975 // spaces, the LHS and RHS pointers are different sized
976 // integers. Truncate to the smaller one.
977 Type *LHSIndexTy = LOffset->getType();
978 Type *RHSIndexTy = ROffset->getType();
979 if (LHSIndexTy != RHSIndexTy) {
980 if (LHSIndexTy->getPrimitiveSizeInBits() <
981 RHSIndexTy->getPrimitiveSizeInBits()) {
982 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
983 } else
984 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
985 }
986
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000987 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000988 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000989 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000990 }
991
Chris Lattner2188e402010-01-04 07:37:31 +0000992 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000993 // different. Try convert this to an indexed compare by looking through
994 // PHIs/casts.
995 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +0000996 }
997
998 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000999 if (GEPLHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +00001000 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +00001001 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +00001002
1003 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001004 if (GEPRHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +00001005 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
1006
Stuart Hastings66a82b92011-05-14 05:55:10 +00001007 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001008 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1009 // If the GEPs only differ by one index, compare it.
1010 unsigned NumDifferences = 0; // Keep track of # differences.
1011 unsigned DiffOperand = 0; // The operand that differs.
1012 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1013 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1014 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1015 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1016 // Irreconcilable differences.
1017 NumDifferences = 2;
1018 break;
1019 } else {
1020 if (NumDifferences++) break;
1021 DiffOperand = i;
1022 }
1023 }
1024
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001025 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001026 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001027 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001028
Stuart Hastings66a82b92011-05-14 05:55:10 +00001029 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001030 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1031 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1032 // Make sure we do a signed comparison here.
1033 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1034 }
1035 }
1036
1037 // Only lower this if the icmp is the only user of the GEP or if we expect
1038 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001039 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001040 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1041 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1042 Value *L = EmitGEPOffset(GEPLHS);
1043 Value *R = EmitGEPOffset(GEPRHS);
1044 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1045 }
1046 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001047
1048 // Try convert this to an indexed compare by looking through PHIs/casts as a
1049 // last resort.
1050 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001051}
1052
Hans Wennborgf1f36512015-10-07 00:20:07 +00001053Instruction *InstCombiner::FoldAllocaCmp(ICmpInst &ICI, AllocaInst *Alloca,
1054 Value *Other) {
1055 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1056
1057 // It would be tempting to fold away comparisons between allocas and any
1058 // pointer not based on that alloca (e.g. an argument). However, even
1059 // though such pointers cannot alias, they can still compare equal.
1060 //
1061 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1062 // doesn't escape we can argue that it's impossible to guess its value, and we
1063 // can therefore act as if any such guesses are wrong.
1064 //
1065 // The code below checks that the alloca doesn't escape, and that it's only
1066 // used in a comparison once (the current instruction). The
1067 // single-comparison-use condition ensures that we're trivially folding all
1068 // comparisons against the alloca consistently, and avoids the risk of
1069 // erroneously folding a comparison of the pointer with itself.
1070
1071 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1072
1073 SmallVector<Use *, 32> Worklist;
1074 for (Use &U : Alloca->uses()) {
1075 if (Worklist.size() >= MaxIter)
1076 return nullptr;
1077 Worklist.push_back(&U);
1078 }
1079
1080 unsigned NumCmps = 0;
1081 while (!Worklist.empty()) {
1082 assert(Worklist.size() <= MaxIter);
1083 Use *U = Worklist.pop_back_val();
1084 Value *V = U->getUser();
1085 --MaxIter;
1086
1087 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1088 isa<SelectInst>(V)) {
1089 // Track the uses.
1090 } else if (isa<LoadInst>(V)) {
1091 // Loading from the pointer doesn't escape it.
1092 continue;
1093 } else if (auto *SI = dyn_cast<StoreInst>(V)) {
1094 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1095 if (SI->getValueOperand() == U->get())
1096 return nullptr;
1097 continue;
1098 } else if (isa<ICmpInst>(V)) {
1099 if (NumCmps++)
1100 return nullptr; // Found more than one cmp.
1101 continue;
1102 } else if (auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1103 switch (Intrin->getIntrinsicID()) {
1104 // These intrinsics don't escape or compare the pointer. Memset is safe
1105 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1106 // we don't allow stores, so src cannot point to V.
1107 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1108 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1109 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1110 continue;
1111 default:
1112 return nullptr;
1113 }
1114 } else {
1115 return nullptr;
1116 }
1117 for (Use &U : V->uses()) {
1118 if (Worklist.size() >= MaxIter)
1119 return nullptr;
1120 Worklist.push_back(&U);
1121 }
1122 }
1123
1124 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001125 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001126 ICI,
1127 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1128}
1129
Chris Lattner2188e402010-01-04 07:37:31 +00001130/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00001131Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner2188e402010-01-04 07:37:31 +00001132 Value *X, ConstantInt *CI,
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00001133 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001134 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001135 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001136 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001137
Chris Lattner8c92b572010-01-08 17:48:19 +00001138 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001139 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1140 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1141 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001142 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001143 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001144 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1145 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001146
Chris Lattner2188e402010-01-04 07:37:31 +00001147 // (X+1) >u X --> X <u (0-1) --> X != 255
1148 // (X+2) >u X --> X <u (0-2) --> X <u 254
1149 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001150 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001151 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001152
Chris Lattner2188e402010-01-04 07:37:31 +00001153 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1154 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1155 APInt::getSignedMaxValue(BitWidth));
1156
1157 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1158 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1159 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1160 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1161 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1162 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001163 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001164 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001165
Chris Lattner2188e402010-01-04 07:37:31 +00001166 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1167 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1168 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1169 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1170 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1171 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001172
Chris Lattner2188e402010-01-04 07:37:31 +00001173 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001174 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001175 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1176}
1177
1178/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
1179/// and CmpRHS are both known to be integer constants.
1180Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
1181 ConstantInt *DivRHS) {
1182 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
1183 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001184
1185 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +00001186 // then don't attempt this transform. The code below doesn't have the
1187 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +00001188 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +00001189 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +00001190 // (x /u C1) <u C2. Simply casting the operands and result won't
1191 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +00001192 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +00001193 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
1194 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +00001195 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001196 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +00001197 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +00001198 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001199 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +00001200 if (DivRHS->isOne()) {
1201 // This eliminates some funny cases with INT_MIN.
1202 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
1203 return &ICI;
1204 }
Chris Lattner2188e402010-01-04 07:37:31 +00001205
1206 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +00001207 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
1208 // C2 (CI). By solving for X we can turn this into a range check
1209 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +00001210 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
1211
1212 // Determine if the product overflows by seeing if the product is
1213 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +00001214 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +00001215 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
1216 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
1217
1218 // Get the ICmp opcode
1219 ICmpInst::Predicate Pred = ICI.getPredicate();
1220
Chris Lattner98457102011-02-10 05:23:05 +00001221 /// If the division is known to be exact, then there is no remainder from the
1222 /// divide, so the covered range size is unit, otherwise it is the divisor.
1223 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001224
Chris Lattner2188e402010-01-04 07:37:31 +00001225 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +00001226 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +00001227 // Compute this interval based on the constants involved and the signedness of
1228 // the compare/divide. This computes a half-open interval, keeping track of
1229 // whether either value in the interval overflows. After analysis each
1230 // overflow variable is set to 0 if it's corresponding bound variable is valid
1231 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
1232 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001233 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +00001234
Chris Lattner2188e402010-01-04 07:37:31 +00001235 if (!DivIsSigned) { // udiv
1236 // e.g. X/5 op 3 --> [15, 20)
1237 LoBound = Prod;
1238 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +00001239 if (!HiOverflow) {
1240 // If this is not an exact divide, then many values in the range collapse
1241 // to the same result value.
1242 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
1243 }
Chris Lattner2188e402010-01-04 07:37:31 +00001244 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
1245 if (CmpRHSV == 0) { // (X / pos) op 0
1246 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +00001247 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
1248 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +00001249 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
1250 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
1251 HiOverflow = LoOverflow = ProdOV;
1252 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001253 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001254 } else { // (X / pos) op neg
1255 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
1256 HiBound = AddOne(Prod);
1257 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
1258 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +00001259 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001260 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +00001261 }
Chris Lattner2188e402010-01-04 07:37:31 +00001262 }
Chris Lattnerb1a15122011-07-15 06:08:15 +00001263 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +00001264 if (DivI->isExact())
1265 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001266 if (CmpRHSV == 0) { // (X / neg) op 0
1267 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +00001268 LoBound = AddOne(RangeSize);
1269 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001270 if (HiBound == DivRHS) { // -INTMIN = INTMIN
1271 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +00001272 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +00001273 }
1274 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
1275 // e.g. X/-5 op 3 --> [-19, -14)
1276 HiBound = AddOne(Prod);
1277 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
1278 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001279 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +00001280 } else { // (X / neg) op neg
1281 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
1282 LoOverflow = HiOverflow = ProdOV;
1283 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001284 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001285 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001286
Chris Lattner2188e402010-01-04 07:37:31 +00001287 // Dividing by a negative swaps the condition. LT <-> GT
1288 Pred = ICmpInst::getSwappedPredicate(Pred);
1289 }
1290
1291 Value *X = DivI->getOperand(0);
1292 switch (Pred) {
1293 default: llvm_unreachable("Unhandled icmp opcode!");
1294 case ICmpInst::ICMP_EQ:
1295 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001296 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +00001297 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001298 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1299 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001300 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001301 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1302 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001303 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner98457102011-02-10 05:23:05 +00001304 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +00001305 case ICmpInst::ICMP_NE:
1306 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001307 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +00001308 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001309 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1310 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001311 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001312 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1313 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001314 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner067459c2010-03-05 08:46:26 +00001315 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +00001316 case ICmpInst::ICMP_ULT:
1317 case ICmpInst::ICMP_SLT:
1318 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001319 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001320 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001321 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001322 return new ICmpInst(Pred, X, LoBound);
1323 case ICmpInst::ICMP_UGT:
1324 case ICmpInst::ICMP_SGT:
1325 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001326 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +00001327 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001328 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001329 if (Pred == ICmpInst::ICMP_UGT)
1330 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +00001331 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +00001332 }
1333}
1334
Chris Lattnerd369f572011-02-13 07:43:07 +00001335/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
1336Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
1337 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +00001338 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001339
Chris Lattnerd369f572011-02-13 07:43:07 +00001340 // Check that the shift amount is in range. If not, don't perform
1341 // undefined shifts. When the shift is visited it will be
1342 // simplified.
1343 uint32_t TypeBits = CmpRHSV.getBitWidth();
1344 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +00001345 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001346 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001347
Chris Lattner43273af2011-02-13 08:07:21 +00001348 if (!ICI.isEquality()) {
1349 // If we have an unsigned comparison and an ashr, we can't simplify this.
1350 // Similarly for signed comparisons with lshr.
1351 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +00001352 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001353
Eli Friedman865866e2011-05-25 23:26:20 +00001354 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1355 // by a power of 2. Since we already have logic to simplify these,
1356 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +00001357 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +00001358 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +00001359 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001360
Chris Lattner43273af2011-02-13 08:07:21 +00001361 // Revisit the shift (to delete it).
1362 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001363
Chris Lattner43273af2011-02-13 08:07:21 +00001364 Constant *DivCst =
1365 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001366
Chris Lattner43273af2011-02-13 08:07:21 +00001367 Value *Tmp =
1368 Shr->getOpcode() == Instruction::AShr ?
1369 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1370 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001371
Chris Lattner43273af2011-02-13 08:07:21 +00001372 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001373
Chris Lattner43273af2011-02-13 08:07:21 +00001374 // If the builder folded the binop, just return it.
1375 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +00001376 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +00001377 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001378
Chris Lattner43273af2011-02-13 08:07:21 +00001379 // Otherwise, fold this div/compare.
1380 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1381 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001382
Chris Lattner43273af2011-02-13 08:07:21 +00001383 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1384 assert(Res && "This div/cst should have folded!");
1385 return Res;
1386 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001387
Chris Lattnerd369f572011-02-13 07:43:07 +00001388 // If we are comparing against bits always shifted out, the
1389 // comparison cannot succeed.
1390 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001391 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001392 if (Shr->getOpcode() == Instruction::LShr)
1393 Comp = Comp.lshr(ShAmtVal);
1394 else
1395 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001396
Chris Lattnerd369f572011-02-13 07:43:07 +00001397 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1398 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001399 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00001400 return replaceInstUsesWith(ICI, Cst);
Chris Lattnerd369f572011-02-13 07:43:07 +00001401 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001402
Chris Lattnerd369f572011-02-13 07:43:07 +00001403 // Otherwise, check to see if the bits shifted out are known to be zero.
1404 // If so, we can compare against the unshifted value:
1405 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001406 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001407 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001408
Chris Lattnerd369f572011-02-13 07:43:07 +00001409 if (Shr->hasOneUse()) {
1410 // Otherwise strength reduce the shift into an and.
1411 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001412 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001413
Chris Lattnerd369f572011-02-13 07:43:07 +00001414 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1415 Mask, Shr->getName()+".mask");
1416 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1417 }
Craig Topperf40110f2014-04-25 05:29:35 +00001418 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001419}
1420
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001421/// FoldICmpCstShrCst - Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
1422/// (icmp eq/ne A, Log2(const2/const1)) ->
1423/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
1424Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
1425 ConstantInt *CI1,
1426 ConstantInt *CI2) {
1427 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1428
1429 auto getConstant = [&I, this](bool IsTrue) {
1430 if (I.getPredicate() == I.ICMP_NE)
1431 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001432 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001433 };
1434
1435 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1436 if (I.getPredicate() == I.ICMP_NE)
1437 Pred = CmpInst::getInversePredicate(Pred);
1438 return new ICmpInst(Pred, LHS, RHS);
1439 };
1440
1441 APInt AP1 = CI1->getValue();
1442 APInt AP2 = CI2->getValue();
1443
David Majnemer2abb8182014-10-25 07:13:13 +00001444 // Don't bother doing any work for cases which InstSimplify handles.
1445 if (AP2 == 0)
1446 return nullptr;
1447 bool IsAShr = isa<AShrOperator>(Op);
1448 if (IsAShr) {
1449 if (AP2.isAllOnesValue())
1450 return nullptr;
1451 if (AP2.isNegative() != AP1.isNegative())
1452 return nullptr;
1453 if (AP2.sgt(AP1))
1454 return nullptr;
1455 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001456
David Majnemerd2056022014-10-21 19:51:55 +00001457 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001458 // 'A' must be large enough to shift out the highest set bit.
1459 return getICmp(I.ICMP_UGT, A,
1460 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001461
David Majnemerd2056022014-10-21 19:51:55 +00001462 if (AP1 == AP2)
1463 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001464
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001465 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001466 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001467 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001468 else
David Majnemere5977eb2015-09-19 00:48:26 +00001469 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001470
David Majnemerd2056022014-10-21 19:51:55 +00001471 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001472 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1473 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001474 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001475 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1476 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001477 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001478 } else if (AP1 == AP2.lshr(Shift)) {
1479 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1480 }
David Majnemerd2056022014-10-21 19:51:55 +00001481 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001482 // Shifting const2 will never be equal to const1.
1483 return getConstant(false);
1484}
Chris Lattner2188e402010-01-04 07:37:31 +00001485
David Majnemer59939ac2014-10-19 08:23:08 +00001486/// FoldICmpCstShlCst - Handle "(icmp eq/ne (shl const2, A), const1)" ->
1487/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
1488Instruction *InstCombiner::FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
1489 ConstantInt *CI1,
1490 ConstantInt *CI2) {
1491 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1492
1493 auto getConstant = [&I, this](bool IsTrue) {
1494 if (I.getPredicate() == I.ICMP_NE)
1495 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001496 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
David Majnemer59939ac2014-10-19 08:23:08 +00001497 };
1498
1499 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1500 if (I.getPredicate() == I.ICMP_NE)
1501 Pred = CmpInst::getInversePredicate(Pred);
1502 return new ICmpInst(Pred, LHS, RHS);
1503 };
1504
1505 APInt AP1 = CI1->getValue();
1506 APInt AP2 = CI2->getValue();
1507
David Majnemer2abb8182014-10-25 07:13:13 +00001508 // Don't bother doing any work for cases which InstSimplify handles.
1509 if (AP2 == 0)
1510 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001511
1512 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1513
1514 if (!AP1 && AP2TrailingZeros != 0)
1515 return getICmp(I.ICMP_UGE, A,
1516 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1517
1518 if (AP1 == AP2)
1519 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1520
1521 // Get the distance between the lowest bits that are set.
1522 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1523
1524 if (Shift > 0 && AP2.shl(Shift) == AP1)
1525 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1526
1527 // Shifting const2 will never be equal to const1.
1528 return getConstant(false);
1529}
1530
Chris Lattner2188e402010-01-04 07:37:31 +00001531/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1532///
1533Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1534 Instruction *LHSI,
1535 ConstantInt *RHS) {
1536 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001537
Chris Lattner2188e402010-01-04 07:37:31 +00001538 switch (LHSI->getOpcode()) {
1539 case Instruction::Trunc:
Sanjoy Dase5f48892015-09-16 20:41:29 +00001540 if (RHS->isOne() && RHSV.getBitWidth() > 1) {
1541 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1542 Value *V = nullptr;
1543 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1544 match(LHSI->getOperand(0), m_Signum(m_Value(V))))
1545 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1546 ConstantInt::get(V->getType(), 1));
1547 }
Chris Lattner2188e402010-01-04 07:37:31 +00001548 if (ICI.isEquality() && LHSI->hasOneUse()) {
1549 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1550 // of the high bits truncated out of x are known.
1551 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1552 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001553 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001554 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001555
Chris Lattner2188e402010-01-04 07:37:31 +00001556 // If all the high bits are known, we can do this xform.
1557 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1558 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001559 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001560 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001561 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001562 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001563 }
1564 }
1565 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001566
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001567 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1568 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001569 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1570 // fold the xor.
1571 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1572 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1573 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001574
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001575 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001576 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001577 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001578 ICI.setOperand(0, CompareVal);
1579 Worklist.Add(LHSI);
1580 return &ICI;
1581 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001582
Chris Lattner2188e402010-01-04 07:37:31 +00001583 // Was the old condition true if the operand is positive?
1584 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001585
Chris Lattner2188e402010-01-04 07:37:31 +00001586 // If so, the new one isn't.
1587 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001588
Chris Lattner2188e402010-01-04 07:37:31 +00001589 if (isTrueIfPositive)
1590 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1591 SubOne(RHS));
1592 else
1593 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1594 AddOne(RHS));
1595 }
1596
1597 if (LHSI->hasOneUse()) {
1598 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001599 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1600 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001601 ICmpInst::Predicate Pred = ICI.isSigned()
1602 ? ICI.getUnsignedPredicate()
1603 : ICI.getSignedPredicate();
1604 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001605 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001606 }
1607
1608 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001609 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1610 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001611 ICmpInst::Predicate Pred = ICI.isSigned()
1612 ? ICI.getUnsignedPredicate()
1613 : ICI.getSignedPredicate();
1614 Pred = ICI.getSwappedPredicate(Pred);
1615 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001616 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001617 }
1618 }
David Majnemer72d76272013-07-09 09:20:58 +00001619
1620 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1621 // iff -C is a power of 2
1622 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001623 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1624 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001625
1626 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1627 // iff -C is a power of 2
1628 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001629 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1630 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001631 }
1632 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001633 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001634 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1635 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001636 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001637
Chris Lattner2188e402010-01-04 07:37:31 +00001638 // If the LHS is an AND of a truncating cast, we can widen the
1639 // and/compare to be the input width without changing the value
1640 // produced, eliminating a cast.
1641 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1642 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001643 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001644 // Extending a relational comparison when we're checking the sign
1645 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001646 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001647 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001648 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001649 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001650 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001651 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001652 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001653 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001654 }
1655 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001656
1657 // If the LHS is an AND of a zext, and we have an equality compare, we can
1658 // shrink the and/compare to the smaller type, eliminating the cast.
1659 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001660 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001661 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1662 // should fold the icmp to true/false in that case.
1663 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1664 Value *NewAnd =
1665 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001666 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001667 NewAnd->takeName(LHSI);
1668 return new ICmpInst(ICI.getPredicate(), NewAnd,
1669 ConstantExpr::getTrunc(RHS, Ty));
1670 }
1671 }
1672
Chris Lattner2188e402010-01-04 07:37:31 +00001673 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1674 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1675 // happens a LOT in code produced by the C front-end, for bitfield
1676 // access.
1677 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1678 if (Shift && !Shift->isShift())
Craig Topperf40110f2014-04-25 05:29:35 +00001679 Shift = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001680
Chris Lattner2188e402010-01-04 07:37:31 +00001681 ConstantInt *ShAmt;
Craig Topperf40110f2014-04-25 05:29:35 +00001682 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001683
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001684 // This seemingly simple opportunity to fold away a shift turns out to
1685 // be rather complicated. See PR17827
1686 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001687 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001688 bool CanFold = false;
1689 unsigned ShiftOpcode = Shift->getOpcode();
1690 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001691 // There may be some constraints that make this possible,
1692 // but nothing simple has been discovered yet.
1693 CanFold = false;
1694 } else if (ShiftOpcode == Instruction::Shl) {
1695 // For a left shift, we can fold if the comparison is not signed.
1696 // We can also fold a signed comparison if the mask value and
1697 // comparison value are not negative. These constraints may not be
1698 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001699 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001700 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001701 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001702 } else if (ShiftOpcode == Instruction::LShr) {
1703 // For a logical right shift, we can fold if the comparison is not
1704 // signed. We can also fold a signed comparison if the shifted mask
1705 // value and the shifted comparison value are not negative.
1706 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001707 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001708 if (!ICI.isSigned())
1709 CanFold = true;
1710 else {
1711 ConstantInt *ShiftedAndCst =
1712 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1713 ConstantInt *ShiftedRHSCst =
1714 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1715
1716 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1717 CanFold = true;
1718 }
Chris Lattner2188e402010-01-04 07:37:31 +00001719 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001720
Chris Lattner2188e402010-01-04 07:37:31 +00001721 if (CanFold) {
1722 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001723 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001724 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1725 else
1726 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001727
Chris Lattner2188e402010-01-04 07:37:31 +00001728 // Check to see if we are shifting out any of the bits being
1729 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001730 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001731 // If we shifted bits out, the fold is not going to work out.
1732 // As a special case, check to see if this means that the
1733 // result is always true or false now.
1734 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00001735 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001736 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Sanjay Patel4b198802016-02-01 22:23:39 +00001737 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001738 } else {
1739 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001740 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001741 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001742 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001743 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001744 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1745 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001746 LHSI->setOperand(0, Shift->getOperand(0));
1747 Worklist.Add(Shift); // Shift is dead.
1748 return &ICI;
1749 }
1750 }
1751 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001752
Chris Lattner2188e402010-01-04 07:37:31 +00001753 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1754 // preferable because it allows the C<<Y expression to be hoisted out
1755 // of a loop if Y is invariant and X is not.
1756 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1757 ICI.isEquality() && !Shift->isArithmeticShift() &&
1758 !isa<Constant>(Shift->getOperand(0))) {
1759 // Compute C << Y.
1760 Value *NS;
1761 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001762 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001763 } else {
1764 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001765 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001766 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001767
Chris Lattner2188e402010-01-04 07:37:31 +00001768 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001769 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001770 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001771
Chris Lattner2188e402010-01-04 07:37:31 +00001772 ICI.setOperand(0, NewAnd);
1773 return &ICI;
1774 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001775
David Majnemer0ffccf72014-08-24 09:10:57 +00001776 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1777 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1778 //
1779 // iff pred isn't signed
1780 {
1781 Value *X, *Y, *LShr;
1782 if (!ICI.isSigned() && RHSV == 0) {
1783 if (match(LHSI->getOperand(1), m_One())) {
1784 Constant *One = cast<Constant>(LHSI->getOperand(1));
1785 Value *Or = LHSI->getOperand(0);
1786 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1787 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1788 unsigned UsesRemoved = 0;
1789 if (LHSI->hasOneUse())
1790 ++UsesRemoved;
1791 if (Or->hasOneUse())
1792 ++UsesRemoved;
1793 if (LShr->hasOneUse())
1794 ++UsesRemoved;
1795 Value *NewOr = nullptr;
1796 // Compute X & ((1 << Y) | 1)
1797 if (auto *C = dyn_cast<Constant>(Y)) {
1798 if (UsesRemoved >= 1)
1799 NewOr =
1800 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1801 } else {
1802 if (UsesRemoved >= 3)
1803 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1804 LShr->getName(),
1805 /*HasNUW=*/true),
1806 One, Or->getName());
1807 }
1808 if (NewOr) {
1809 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1810 ICI.setOperand(0, NewAnd);
1811 return &ICI;
1812 }
1813 }
1814 }
1815 }
1816 }
1817
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001818 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1819 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001820 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001821 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1822 if ((NTZ < AndCst->getBitWidth()) &&
1823 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001824 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1825 Constant::getNullValue(RHS->getType()));
1826 }
Chris Lattner2188e402010-01-04 07:37:31 +00001827 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001828
Chris Lattner2188e402010-01-04 07:37:31 +00001829 // Try to optimize things like "A[i]&42 == 0" to index computations.
1830 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1831 if (GetElementPtrInst *GEP =
1832 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1833 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1834 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1835 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1836 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1837 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1838 return Res;
1839 }
1840 }
David Majnemer414d4e52013-07-09 08:09:32 +00001841
1842 // X & -C == -C -> X > u ~C
1843 // X & -C != -C -> X <= u ~C
1844 // iff C is a power of 2
1845 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1846 return new ICmpInst(
1847 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1848 : ICmpInst::ICMP_ULE,
1849 LHSI->getOperand(0), SubOne(RHS));
David Majnemerdfa3b092015-08-16 07:09:17 +00001850
1851 // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1852 // iff C is a power of 2
1853 if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) {
1854 if (auto *CI = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1855 const APInt &AI = CI->getValue();
1856 int32_t ExactLogBase2 = AI.exactLogBase2();
1857 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1858 Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1);
1859 Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy);
1860 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1861 ? ICmpInst::ICMP_SGE
1862 : ICmpInst::ICMP_SLT,
1863 Trunc, Constant::getNullValue(NTy));
1864 }
1865 }
1866 }
Chris Lattner2188e402010-01-04 07:37:31 +00001867 break;
1868
1869 case Instruction::Or: {
Sanjoy Dase5f48892015-09-16 20:41:29 +00001870 if (RHS->isOne()) {
1871 // icmp slt signum(V) 1 --> icmp slt V, 1
1872 Value *V = nullptr;
1873 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1874 match(LHSI, m_Signum(m_Value(V))))
1875 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1876 ConstantInt::get(V->getType(), 1));
1877 }
1878
Chris Lattner2188e402010-01-04 07:37:31 +00001879 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1880 break;
1881 Value *P, *Q;
1882 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1883 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1884 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001885 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1886 Constant::getNullValue(P->getType()));
1887 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1888 Constant::getNullValue(Q->getType()));
1889 Instruction *Op;
1890 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1891 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1892 else
1893 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1894 return Op;
1895 }
1896 break;
1897 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001898
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001899 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1900 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1901 if (!Val) break;
1902
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001903 // If this is a signed comparison to 0 and the mul is sign preserving,
1904 // use the mul LHS operand instead.
1905 ICmpInst::Predicate pred = ICI.getPredicate();
1906 if (isSignTest(pred, RHS) && !Val->isZero() &&
1907 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1908 return new ICmpInst(Val->isNegative() ?
1909 ICmpInst::getSwappedPredicate(pred) : pred,
1910 LHSI->getOperand(0),
1911 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001912
1913 break;
1914 }
1915
Chris Lattner2188e402010-01-04 07:37:31 +00001916 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001917 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001918 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1919 if (!ShAmt) {
1920 Value *X;
1921 // (1 << X) pred P2 -> X pred Log2(P2)
1922 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1923 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1924 ICmpInst::Predicate Pred = ICI.getPredicate();
1925 if (ICI.isUnsigned()) {
1926 if (!RHSVIsPowerOf2) {
1927 // (1 << X) < 30 -> X <= 4
1928 // (1 << X) <= 30 -> X <= 4
1929 // (1 << X) >= 30 -> X > 4
1930 // (1 << X) > 30 -> X > 4
1931 if (Pred == ICmpInst::ICMP_ULT)
1932 Pred = ICmpInst::ICMP_ULE;
1933 else if (Pred == ICmpInst::ICMP_UGE)
1934 Pred = ICmpInst::ICMP_UGT;
1935 }
1936 unsigned RHSLog2 = RHSV.logBase2();
1937
1938 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
David Majnemerb889e402013-06-28 23:42:03 +00001939 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1940 if (RHSLog2 == TypeBits-1) {
1941 if (Pred == ICmpInst::ICMP_UGE)
1942 Pred = ICmpInst::ICMP_EQ;
David Majnemerb889e402013-06-28 23:42:03 +00001943 else if (Pred == ICmpInst::ICMP_ULT)
1944 Pred = ICmpInst::ICMP_NE;
1945 }
1946
1947 return new ICmpInst(Pred, X,
1948 ConstantInt::get(RHS->getType(), RHSLog2));
1949 } else if (ICI.isSigned()) {
1950 if (RHSV.isAllOnesValue()) {
1951 // (1 << X) <= -1 -> X == 31
1952 if (Pred == ICmpInst::ICMP_SLE)
1953 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1954 ConstantInt::get(RHS->getType(), TypeBits-1));
1955
1956 // (1 << X) > -1 -> X != 31
1957 if (Pred == ICmpInst::ICMP_SGT)
1958 return new ICmpInst(ICmpInst::ICMP_NE, X,
1959 ConstantInt::get(RHS->getType(), TypeBits-1));
1960 } else if (!RHSV) {
1961 // (1 << X) < 0 -> X == 31
1962 // (1 << X) <= 0 -> X == 31
1963 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1964 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1965 ConstantInt::get(RHS->getType(), TypeBits-1));
1966
1967 // (1 << X) >= 0 -> X != 31
1968 // (1 << X) > 0 -> X != 31
1969 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1970 return new ICmpInst(ICmpInst::ICMP_NE, X,
1971 ConstantInt::get(RHS->getType(), TypeBits-1));
1972 }
1973 } else if (ICI.isEquality()) {
1974 if (RHSVIsPowerOf2)
1975 return new ICmpInst(
1976 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
David Majnemerb889e402013-06-28 23:42:03 +00001977 }
1978 }
1979 break;
1980 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001981
Chris Lattner2188e402010-01-04 07:37:31 +00001982 // Check that the shift amount is in range. If not, don't perform
1983 // undefined shifts. When the shift is visited it will be
1984 // simplified.
1985 if (ShAmt->uge(TypeBits))
1986 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001987
Chris Lattner2188e402010-01-04 07:37:31 +00001988 if (ICI.isEquality()) {
1989 // If we are comparing against bits always shifted out, the
1990 // comparison cannot succeed.
1991 Constant *Comp =
1992 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1993 ShAmt);
1994 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1995 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001996 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00001997 return replaceInstUsesWith(ICI, Cst);
Chris Lattner2188e402010-01-04 07:37:31 +00001998 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001999
Chris Lattner98457102011-02-10 05:23:05 +00002000 // If the shift is NUW, then it is just shifting out zeros, no need for an
2001 // AND.
2002 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
2003 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2004 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002005
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002006 // If the shift is NSW and we compare to 0, then it is just shifting out
2007 // sign bits, no need for an AND either.
2008 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
2009 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2010 ConstantExpr::getLShr(RHS, ShAmt));
2011
Chris Lattner2188e402010-01-04 07:37:31 +00002012 if (LHSI->hasOneUse()) {
2013 // Otherwise strength reduce the shift into an and.
2014 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00002015 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
2016 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002017
Chris Lattner2188e402010-01-04 07:37:31 +00002018 Value *And =
2019 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
2020 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00002021 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00002022 }
2023 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002024
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002025 // If this is a signed comparison to 0 and the shift is sign preserving,
2026 // use the shift LHS operand instead.
2027 ICmpInst::Predicate pred = ICI.getPredicate();
2028 if (isSignTest(pred, RHS) &&
2029 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
2030 return new ICmpInst(pred,
2031 LHSI->getOperand(0),
2032 Constant::getNullValue(RHS->getType()));
2033
Chris Lattner2188e402010-01-04 07:37:31 +00002034 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2035 bool TrueIfSigned = false;
2036 if (LHSI->hasOneUse() &&
2037 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
2038 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00002039 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00002040 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00002041 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002042 Value *And =
2043 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
2044 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2045 And, Constant::getNullValue(And->getType()));
2046 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002047
2048 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00002049 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
2050 // 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 +00002051 // This enables to get rid of the shift in favor of a trunc which can be
2052 // free on the target. It has the additional benefit of comparing to a
2053 // smaller constant, which will be target friendly.
2054 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00002055 if (LHSI->hasOneUse() &&
2056 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002057 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
2058 Constant *NCI = ConstantExpr::getTrunc(
2059 ConstantExpr::getAShr(RHS,
2060 ConstantInt::get(RHS->getType(), Amt)),
2061 NTy);
2062 return new ICmpInst(ICI.getPredicate(),
2063 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00002064 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002065 }
2066
Chris Lattner2188e402010-01-04 07:37:31 +00002067 break;
2068 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002069
Chris Lattner2188e402010-01-04 07:37:31 +00002070 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00002071 case Instruction::AShr: {
2072 // Handle equality comparisons of shift-by-constant.
2073 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
2074 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2075 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00002076 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00002077 }
2078
2079 // Handle exact shr's.
2080 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
2081 if (RHSV.isMinValue())
2082 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
2083 }
Chris Lattner2188e402010-01-04 07:37:31 +00002084 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00002085 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002086
Chris Lattner2188e402010-01-04 07:37:31 +00002087 case Instruction::SDiv:
2088 case Instruction::UDiv:
2089 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00002090 // Fold this div into the comparison, producing a range check.
2091 // Determine, based on the divide type, what the range is being
2092 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00002093 // it, otherwise compute the range [low, hi) bounding the new value.
2094 // See: InsertRangeTest above for the kinds of replacements possible.
2095 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
2096 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
2097 DivRHS))
2098 return R;
2099 break;
2100
David Majnemerf2a9a512013-07-09 07:50:59 +00002101 case Instruction::Sub: {
2102 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
2103 if (!LHSC) break;
2104 const APInt &LHSV = LHSC->getValue();
2105
2106 // C1-X <u C2 -> (X|(C2-1)) == C1
2107 // iff C1 & (C2-1) == C2-1
2108 // C2 is a power of 2
2109 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
2110 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
2111 return new ICmpInst(ICmpInst::ICMP_EQ,
2112 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
2113 LHSC);
2114
David Majnemereeed73b2013-07-09 09:24:35 +00002115 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00002116 // iff C1 & C2 == C2
2117 // C2+1 is a power of 2
2118 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2119 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
2120 return new ICmpInst(ICmpInst::ICMP_NE,
2121 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
2122 break;
2123 }
2124
Chris Lattner2188e402010-01-04 07:37:31 +00002125 case Instruction::Add:
2126 // Fold: icmp pred (add X, C1), C2
2127 if (!ICI.isEquality()) {
2128 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
2129 if (!LHSC) break;
2130 const APInt &LHSV = LHSC->getValue();
2131
2132 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
2133 .subtract(LHSV);
2134
2135 if (ICI.isSigned()) {
2136 if (CR.getLower().isSignBit()) {
2137 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002138 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00002139 } else if (CR.getUpper().isSignBit()) {
2140 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002141 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00002142 }
2143 } else {
2144 if (CR.getLower().isMinValue()) {
2145 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002146 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00002147 } else if (CR.getUpper().isMinValue()) {
2148 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002149 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00002150 }
2151 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00002152
David Majnemerbafa5372013-07-09 07:58:32 +00002153 // X-C1 <u C2 -> (X & -C2) == C1
2154 // iff C1 & (C2-1) == 0
2155 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00002156 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00002157 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00002158 return new ICmpInst(ICmpInst::ICMP_EQ,
2159 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
2160 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00002161
David Majnemereeed73b2013-07-09 09:24:35 +00002162 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00002163 // iff C1 & C2 == 0
2164 // C2+1 is a power of 2
2165 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2166 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
2167 return new ICmpInst(ICmpInst::ICMP_NE,
2168 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
2169 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00002170 }
2171 break;
2172 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002173
Chris Lattner2188e402010-01-04 07:37:31 +00002174 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
2175 if (ICI.isEquality()) {
2176 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002177
2178 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner2188e402010-01-04 07:37:31 +00002179 // the second operand is a constant, simplify a bit.
2180 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
2181 switch (BO->getOpcode()) {
2182 case Instruction::SRem:
2183 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2184 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
2185 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohman4ce1fb12010-04-08 23:03:40 +00002186 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner2188e402010-01-04 07:37:31 +00002187 Value *NewRem =
2188 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
2189 BO->getName());
2190 return new ICmpInst(ICI.getPredicate(), NewRem,
2191 Constant::getNullValue(BO->getType()));
2192 }
2193 }
2194 break;
2195 case Instruction::Add:
2196 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2197 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2198 if (BO->hasOneUse())
2199 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2200 ConstantExpr::getSub(RHS, BOp1C));
2201 } else if (RHSV == 0) {
2202 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2203 // efficiently invertible, or if the add has just this one use.
2204 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002205
Chris Lattner2188e402010-01-04 07:37:31 +00002206 if (Value *NegVal = dyn_castNegVal(BOp1))
2207 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner31b106d2011-04-26 20:02:45 +00002208 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner2188e402010-01-04 07:37:31 +00002209 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner31b106d2011-04-26 20:02:45 +00002210 if (BO->hasOneUse()) {
Chris Lattner2188e402010-01-04 07:37:31 +00002211 Value *Neg = Builder->CreateNeg(BOp1);
2212 Neg->takeName(BO);
2213 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
2214 }
2215 }
2216 break;
2217 case Instruction::Xor:
David Majnemer0f0abc72016-02-12 18:12:38 +00002218 if (BO->hasOneUse()) {
2219 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
2220 // For the xor case, we can xor two constants together, eliminating
2221 // the explicit xor.
2222 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2223 ConstantExpr::getXor(RHS, BOC));
2224 } else if (RHSV == 0) {
2225 // Replace ((xor A, B) != 0) with (A != B)
2226 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2227 BO->getOperand(1));
2228 }
Benjamin Kramerc9708492011-06-13 15:24:24 +00002229 }
Chris Lattner2188e402010-01-04 07:37:31 +00002230 break;
Benjamin Kramerc9708492011-06-13 15:24:24 +00002231 case Instruction::Sub:
David Majnemer0f0abc72016-02-12 18:12:38 +00002232 if (BO->hasOneUse()) {
2233 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
2234 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
Benjamin Kramerc9708492011-06-13 15:24:24 +00002235 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
David Majnemer0f0abc72016-02-12 18:12:38 +00002236 ConstantExpr::getSub(BOp0C, RHS));
2237 } else if (RHSV == 0) {
2238 // Replace ((sub A, B) != 0) with (A != B)
2239 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2240 BO->getOperand(1));
2241 }
Benjamin Kramerc9708492011-06-13 15:24:24 +00002242 }
2243 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002244 case Instruction::Or:
2245 // If bits are being or'd in that are not present in the constant we
2246 // are comparing against, then the comparison could never succeed!
Eli Friedman0428a612010-07-29 18:03:33 +00002247 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002248 Constant *NotCI = ConstantExpr::getNot(RHS);
2249 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002250 return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Sanjay Patele998b912016-04-14 20:17:40 +00002251
2252 // Comparing if all bits outside of a constant mask are set?
2253 // Replace (X | C) == -1 with (X & ~C) == ~C.
2254 // This removes the -1 constant.
2255 if (BO->hasOneUse() && RHS->isAllOnesValue()) {
2256 Constant *NotBOC = ConstantExpr::getNot(BOC);
2257 Value *And = Builder->CreateAnd(BO->getOperand(0), NotBOC);
2258 return new ICmpInst(ICI.getPredicate(), And, NotBOC);
2259 }
Chris Lattner2188e402010-01-04 07:37:31 +00002260 }
2261 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002262
Chris Lattner2188e402010-01-04 07:37:31 +00002263 case Instruction::And:
2264 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2265 // If bits are being compared against that are and'd out, then the
2266 // comparison can never succeed!
2267 if ((RHSV & ~BOC->getValue()) != 0)
Sanjay Patel4b198802016-02-01 22:23:39 +00002268 return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002269
Chris Lattner2188e402010-01-04 07:37:31 +00002270 // If we have ((X & C) == C), turn it into ((X & C) != 0).
2271 if (RHS == BOC && RHSV.isPowerOf2())
2272 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
2273 ICmpInst::ICMP_NE, LHSI,
2274 Constant::getNullValue(RHS->getType()));
Benjamin Kramer9eca5fe2011-07-04 20:16:36 +00002275
2276 // Don't perform the following transforms if the AND has multiple uses
2277 if (!BO->hasOneUse())
2278 break;
2279
Chris Lattner2188e402010-01-04 07:37:31 +00002280 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
2281 if (BOC->getValue().isSignBit()) {
2282 Value *X = BO->getOperand(0);
2283 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002284 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00002285 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
2286 return new ICmpInst(pred, X, Zero);
2287 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002288
Chris Lattner2188e402010-01-04 07:37:31 +00002289 // ((X & ~7) == 0) --> X < 8
2290 if (RHSV == 0 && isHighOnes(BOC)) {
2291 Value *X = BO->getOperand(0);
2292 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002293 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00002294 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
2295 return new ICmpInst(pred, X, NegX);
2296 }
2297 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002298 break;
2299 case Instruction::Mul:
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00002300 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002301 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2302 // The trivial case (mul X, 0) is handled by InstSimplify
2303 // General case : (mul X, C) != 0 iff X != 0
2304 // (mul X, C) == 0 iff X == 0
2305 if (!BOC->isZero())
2306 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
2307 Constant::getNullValue(RHS->getType()));
2308 }
2309 }
2310 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002311 default: break;
2312 }
2313 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
2314 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner54f4e392010-01-05 18:09:56 +00002315 switch (II->getIntrinsicID()) {
2316 case Intrinsic::bswap:
Chris Lattner2188e402010-01-04 07:37:31 +00002317 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00002318 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszakbddea112013-06-06 20:18:46 +00002319 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner2188e402010-01-04 07:37:31 +00002320 return &ICI;
Chris Lattner54f4e392010-01-05 18:09:56 +00002321 case Intrinsic::ctlz:
2322 case Intrinsic::cttz:
2323 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
2324 if (RHSV == RHS->getType()->getBitWidth()) {
2325 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00002326 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00002327 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
2328 return &ICI;
2329 }
2330 break;
2331 case Intrinsic::ctpop:
2332 // popcount(A) == 0 -> A == 0 and likewise for !=
2333 if (RHS->isZero()) {
2334 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00002335 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00002336 ICI.setOperand(1, RHS);
2337 return &ICI;
2338 }
2339 break;
2340 default:
Duncan Sands41b4a6b2010-07-12 08:16:59 +00002341 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002342 }
2343 }
2344 }
Craig Topperf40110f2014-04-25 05:29:35 +00002345 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002346}
2347
2348/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
2349/// We only handle extending casts so far.
2350///
2351Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
2352 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
2353 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002354 Type *SrcTy = LHSCIOp->getType();
2355 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002356 Value *RHSCIOp;
2357
Jim Grosbach129c52a2011-09-30 18:09:53 +00002358 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002359 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002360 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2361 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002362 Value *RHSOp = nullptr;
Michael Liaod266b922015-02-13 04:51:26 +00002363 if (PtrToIntOperator *RHSC = dyn_cast<PtrToIntOperator>(ICI.getOperand(1))) {
2364 Value *RHSCIOp = RHSC->getOperand(0);
2365 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2366 LHSCIOp->getType()->getPointerAddressSpace()) {
2367 RHSOp = RHSC->getOperand(0);
2368 // If the pointer types don't match, insert a bitcast.
2369 if (LHSCIOp->getType() != RHSOp->getType())
2370 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2371 }
2372 } else if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1)))
Chris Lattner2188e402010-01-04 07:37:31 +00002373 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002374
2375 if (RHSOp)
2376 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
2377 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002378
Chris Lattner2188e402010-01-04 07:37:31 +00002379 // The code below only handles extension cast instructions, so far.
2380 // Enforce this.
2381 if (LHSCI->getOpcode() != Instruction::ZExt &&
2382 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002383 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002384
2385 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
2386 bool isSignedCmp = ICI.isSigned();
2387
2388 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
2389 // Not an extension from the same type?
2390 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002391 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002392 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002393
Chris Lattner2188e402010-01-04 07:37:31 +00002394 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2395 // and the other is a zext), then we can't handle this.
2396 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002397 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002398
2399 // Deal with equality cases early.
2400 if (ICI.isEquality())
2401 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
2402
2403 // A signed comparison of sign extended values simplifies into a
2404 // signed comparison.
2405 if (isSignedCmp && isSignedExt)
2406 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
2407
2408 // The other three cases all fold into an unsigned comparison.
2409 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
2410 }
2411
2412 // If we aren't dealing with a constant on the RHS, exit early
2413 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
2414 if (!CI)
Craig Topperf40110f2014-04-25 05:29:35 +00002415 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002416
2417 // Compute the constant that would happen if we truncated to SrcTy then
2418 // reextended to DestTy.
2419 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
2420 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
2421 Res1, DestTy);
2422
2423 // If the re-extended constant didn't change...
2424 if (Res2 == CI) {
2425 // Deal with equality cases early.
2426 if (ICI.isEquality())
2427 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
2428
2429 // A signed comparison of sign extended values simplifies into a
2430 // signed comparison.
2431 if (isSignedExt && isSignedCmp)
2432 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
2433
2434 // The other three cases all fold into an unsigned comparison.
2435 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
2436 }
2437
Jim Grosbach129c52a2011-09-30 18:09:53 +00002438 // The re-extended constant changed so the constant cannot be represented
Chris Lattner2188e402010-01-04 07:37:31 +00002439 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002440 // All the cases that fold to true or false will have already been handled
2441 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002442
Duncan Sands8fb2c382011-01-20 13:21:55 +00002443 if (isSignedCmp || !isSignedExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002444 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002445
2446 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2447 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002448
2449 // We're performing an unsigned comp with a sign extended value.
2450 // This is true if the input is >= 0. [aka >s -1]
2451 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
2452 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002453
2454 // Finally, return the value computed.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002455 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Sanjay Patel4b198802016-02-01 22:23:39 +00002456 return replaceInstUsesWith(ICI, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002457
Duncan Sands8fb2c382011-01-20 13:21:55 +00002458 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002459 return BinaryOperator::CreateNot(Result);
2460}
2461
Chris Lattneree61c1d2010-12-19 17:52:50 +00002462/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
2463/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002464/// If this is of the form:
2465/// sum = a + b
2466/// if (sum+128 >u 255)
2467/// Then replace it with llvm.sadd.with.overflow.i8.
2468///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002469static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2470 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002471 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002472 // The transformation we're trying to do here is to transform this into an
2473 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2474 // with a narrower add, and discard the add-with-constant that is part of the
2475 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002476
Chris Lattnerf29562d2010-12-19 17:59:02 +00002477 // In order to eliminate the add-with-constant, the compare can be its only
2478 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002479 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002480 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002481
Chris Lattnerc56c8452010-12-19 18:22:06 +00002482 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002483 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002484 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002485 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002486
Chris Lattnerc56c8452010-12-19 18:22:06 +00002487 // The width of the new add formed is 1 more than the bias.
2488 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002489
Chris Lattnerc56c8452010-12-19 18:22:06 +00002490 // Check to see that CI1 is an all-ones value with NewWidth bits.
2491 if (CI1->getBitWidth() == NewWidth ||
2492 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002493 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002494
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002495 // This is only really a signed overflow check if the inputs have been
2496 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2497 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2498 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002499 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2500 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002501 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002502
Jim Grosbach129c52a2011-09-30 18:09:53 +00002503 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002504 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2505 // and truncates that discard the high bits of the add. Verify that this is
2506 // the case.
2507 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002508 for (User *U : OrigAdd->users()) {
2509 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002510
Chris Lattnerc56c8452010-12-19 18:22:06 +00002511 // Only accept truncates for now. We would really like a nice recursive
2512 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2513 // chain to see which bits of a value are actually demanded. If the
2514 // original add had another add which was then immediately truncated, we
2515 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002516 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002517 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2518 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002519 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002520
Chris Lattneree61c1d2010-12-19 17:52:50 +00002521 // If the pattern matches, truncate the inputs to the narrower type and
2522 // use the sadd_with_overflow intrinsic to efficiently compute both the
2523 // result and the overflow bit.
Jay Foadb804a2b2011-07-12 14:06:48 +00002524 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002525 Value *F = Intrinsic::getDeclaration(I.getModule(),
2526 Intrinsic::sadd_with_overflow, NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002527
Chris Lattnerce2995a2010-12-19 18:38:44 +00002528 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002529
Chris Lattner79874562010-12-19 18:35:09 +00002530 // Put the new code above the original add, in case there are any uses of the
2531 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002532 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002533
Chris Lattner79874562010-12-19 18:35:09 +00002534 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2535 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002536 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002537 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2538 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002539
Chris Lattneree61c1d2010-12-19 17:52:50 +00002540 // The inner add was the result of the narrow add, zero extended to the
2541 // wider type. Replace it with the result computed by the intrinsic.
Sanjay Patel4b198802016-02-01 22:23:39 +00002542 IC.replaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002543
Chris Lattner79874562010-12-19 18:35:09 +00002544 // The original icmp gets replaced with the overflow value.
2545 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002546}
Chris Lattner2188e402010-01-04 07:37:31 +00002547
Sanjoy Dasb0984472015-04-08 04:27:22 +00002548bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2549 Value *RHS, Instruction &OrigI,
2550 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002551 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2552 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002553
2554 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2555 Result = OpResult;
2556 Overflow = OverflowVal;
2557 if (ReuseName)
2558 Result->takeName(&OrigI);
2559 return true;
2560 };
2561
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002562 // If the overflow check was an add followed by a compare, the insertion point
2563 // may be pointing to the compare. We want to insert the new instructions
2564 // before the add in case there are uses of the add between the add and the
2565 // compare.
2566 Builder->SetInsertPoint(&OrigI);
2567
Sanjoy Dasb0984472015-04-08 04:27:22 +00002568 switch (OCF) {
2569 case OCF_INVALID:
2570 llvm_unreachable("bad overflow check kind!");
2571
2572 case OCF_UNSIGNED_ADD: {
2573 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2574 if (OR == OverflowResult::NeverOverflows)
2575 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2576 true);
2577
2578 if (OR == OverflowResult::AlwaysOverflows)
2579 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
2580 }
2581 // FALL THROUGH uadd into sadd
2582 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002583 // X + 0 -> {X, false}
2584 if (match(RHS, m_Zero()))
2585 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002586
2587 // We can strength reduce this signed add into a regular add if we can prove
2588 // that it will never overflow.
2589 if (OCF == OCF_SIGNED_ADD)
2590 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2591 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2592 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002593 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002594 }
2595
2596 case OCF_UNSIGNED_SUB:
2597 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002598 // X - 0 -> {X, false}
2599 if (match(RHS, m_Zero()))
2600 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002601
2602 if (OCF == OCF_SIGNED_SUB) {
2603 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2604 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2605 true);
2606 } else {
2607 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2608 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2609 true);
2610 }
2611 break;
2612 }
2613
2614 case OCF_UNSIGNED_MUL: {
2615 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2616 if (OR == OverflowResult::NeverOverflows)
2617 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2618 true);
2619 if (OR == OverflowResult::AlwaysOverflows)
2620 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
2621 } // FALL THROUGH
2622 case OCF_SIGNED_MUL:
2623 // X * undef -> undef
2624 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002625 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002626
David Majnemer27e89ba2015-05-21 23:04:21 +00002627 // X * 0 -> {0, false}
2628 if (match(RHS, m_Zero()))
2629 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002630
David Majnemer27e89ba2015-05-21 23:04:21 +00002631 // X * 1 -> {X, false}
2632 if (match(RHS, m_One()))
2633 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002634
2635 if (OCF == OCF_SIGNED_MUL)
2636 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2637 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2638 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002639 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002640 }
2641
2642 return false;
2643}
2644
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002645/// \brief Recognize and process idiom involving test for multiplication
2646/// overflow.
2647///
2648/// The caller has matched a pattern of the form:
2649/// I = cmp u (mul(zext A, zext B), V
2650/// The function checks if this is a test for overflow and if so replaces
2651/// multiplication with call to 'mul.with.overflow' intrinsic.
2652///
2653/// \param I Compare instruction.
2654/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2655/// the compare instruction. Must be of integer type.
2656/// \param OtherVal The other argument of compare instruction.
2657/// \returns Instruction which must replace the compare instruction, NULL if no
2658/// replacement required.
2659static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2660 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002661 // Don't bother doing this transformation for pointers, don't do it for
2662 // vectors.
2663 if (!isa<IntegerType>(MulVal->getType()))
2664 return nullptr;
2665
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002666 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2667 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002668 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2669 if (!MulInstr)
2670 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002671 assert(MulInstr->getOpcode() == Instruction::Mul);
2672
David Majnemer634ca232014-11-01 23:46:05 +00002673 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2674 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002675 assert(LHS->getOpcode() == Instruction::ZExt);
2676 assert(RHS->getOpcode() == Instruction::ZExt);
2677 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2678
2679 // Calculate type and width of the result produced by mul.with.overflow.
2680 Type *TyA = A->getType(), *TyB = B->getType();
2681 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2682 WidthB = TyB->getPrimitiveSizeInBits();
2683 unsigned MulWidth;
2684 Type *MulType;
2685 if (WidthB > WidthA) {
2686 MulWidth = WidthB;
2687 MulType = TyB;
2688 } else {
2689 MulWidth = WidthA;
2690 MulType = TyA;
2691 }
2692
2693 // In order to replace the original mul with a narrower mul.with.overflow,
2694 // all uses must ignore upper bits of the product. The number of used low
2695 // bits must be not greater than the width of mul.with.overflow.
2696 if (MulVal->hasNUsesOrMore(2))
2697 for (User *U : MulVal->users()) {
2698 if (U == &I)
2699 continue;
2700 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2701 // Check if truncation ignores bits above MulWidth.
2702 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2703 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002704 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002705 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2706 // Check if AND ignores bits above MulWidth.
2707 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002708 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002709 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2710 const APInt &CVal = CI->getValue();
2711 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002712 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002713 }
2714 } else {
2715 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002716 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002717 }
2718 }
2719
2720 // Recognize patterns
2721 switch (I.getPredicate()) {
2722 case ICmpInst::ICMP_EQ:
2723 case ICmpInst::ICMP_NE:
2724 // Recognize pattern:
2725 // mulval = mul(zext A, zext B)
2726 // cmp eq/neq mulval, zext trunc mulval
2727 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2728 if (Zext->hasOneUse()) {
2729 Value *ZextArg = Zext->getOperand(0);
2730 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2731 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2732 break; //Recognized
2733 }
2734
2735 // Recognize pattern:
2736 // mulval = mul(zext A, zext B)
2737 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2738 ConstantInt *CI;
2739 Value *ValToMask;
2740 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2741 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002742 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002743 const APInt &CVal = CI->getValue() + 1;
2744 if (CVal.isPowerOf2()) {
2745 unsigned MaskWidth = CVal.logBase2();
2746 if (MaskWidth == MulWidth)
2747 break; // Recognized
2748 }
2749 }
Craig Topperf40110f2014-04-25 05:29:35 +00002750 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002751
2752 case ICmpInst::ICMP_UGT:
2753 // Recognize pattern:
2754 // mulval = mul(zext A, zext B)
2755 // cmp ugt mulval, max
2756 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2757 APInt MaxVal = APInt::getMaxValue(MulWidth);
2758 MaxVal = MaxVal.zext(CI->getBitWidth());
2759 if (MaxVal.eq(CI->getValue()))
2760 break; // Recognized
2761 }
Craig Topperf40110f2014-04-25 05:29:35 +00002762 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002763
2764 case ICmpInst::ICMP_UGE:
2765 // Recognize pattern:
2766 // mulval = mul(zext A, zext B)
2767 // cmp uge mulval, max+1
2768 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2769 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2770 if (MaxVal.eq(CI->getValue()))
2771 break; // Recognized
2772 }
Craig Topperf40110f2014-04-25 05:29:35 +00002773 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002774
2775 case ICmpInst::ICMP_ULE:
2776 // Recognize pattern:
2777 // mulval = mul(zext A, zext B)
2778 // cmp ule mulval, max
2779 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2780 APInt MaxVal = APInt::getMaxValue(MulWidth);
2781 MaxVal = MaxVal.zext(CI->getBitWidth());
2782 if (MaxVal.eq(CI->getValue()))
2783 break; // Recognized
2784 }
Craig Topperf40110f2014-04-25 05:29:35 +00002785 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002786
2787 case ICmpInst::ICMP_ULT:
2788 // Recognize pattern:
2789 // mulval = mul(zext A, zext B)
2790 // cmp ule mulval, max + 1
2791 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002792 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002793 if (MaxVal.eq(CI->getValue()))
2794 break; // Recognized
2795 }
Craig Topperf40110f2014-04-25 05:29:35 +00002796 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002797
2798 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002799 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002800 }
2801
2802 InstCombiner::BuilderTy *Builder = IC.Builder;
2803 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002804
2805 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2806 Value *MulA = A, *MulB = B;
2807 if (WidthA < MulWidth)
2808 MulA = Builder->CreateZExt(A, MulType);
2809 if (WidthB < MulWidth)
2810 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002811 Value *F = Intrinsic::getDeclaration(I.getModule(),
2812 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002813 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002814 IC.Worklist.Add(MulInstr);
2815
2816 // If there are uses of mul result other than the comparison, we know that
2817 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002818 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002819 if (MulVal->hasNUsesOrMore(2)) {
2820 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2821 for (User *U : MulVal->users()) {
2822 if (U == &I || U == OtherVal)
2823 continue;
2824 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2825 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00002826 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002827 else
2828 TI->setOperand(0, Mul);
2829 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2830 assert(BO->getOpcode() == Instruction::And);
2831 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2832 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2833 APInt ShortMask = CI->getValue().trunc(MulWidth);
2834 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2835 Instruction *Zext =
2836 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2837 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00002838 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002839 } else {
2840 llvm_unreachable("Unexpected Binary operation");
2841 }
2842 IC.Worklist.Add(cast<Instruction>(U));
2843 }
2844 }
2845 if (isa<Instruction>(OtherVal))
2846 IC.Worklist.Add(cast<Instruction>(OtherVal));
2847
2848 // The original icmp gets replaced with the overflow value, maybe inverted
2849 // depending on predicate.
2850 bool Inverse = false;
2851 switch (I.getPredicate()) {
2852 case ICmpInst::ICMP_NE:
2853 break;
2854 case ICmpInst::ICMP_EQ:
2855 Inverse = true;
2856 break;
2857 case ICmpInst::ICMP_UGT:
2858 case ICmpInst::ICMP_UGE:
2859 if (I.getOperand(0) == MulVal)
2860 break;
2861 Inverse = true;
2862 break;
2863 case ICmpInst::ICMP_ULT:
2864 case ICmpInst::ICMP_ULE:
2865 if (I.getOperand(1) == MulVal)
2866 break;
2867 Inverse = true;
2868 break;
2869 default:
2870 llvm_unreachable("Unexpected predicate");
2871 }
2872 if (Inverse) {
2873 Value *Res = Builder->CreateExtractValue(Call, 1);
2874 return BinaryOperator::CreateNot(Res);
2875 }
2876
2877 return ExtractValueInst::Create(Call, 1);
2878}
2879
Owen Andersond490c2d2011-01-11 00:36:45 +00002880// DemandedBitsLHSMask - When performing a comparison against a constant,
2881// it is possible that not all the bits in the LHS are demanded. This helper
2882// method computes the mask that IS demanded.
2883static APInt DemandedBitsLHSMask(ICmpInst &I,
2884 unsigned BitWidth, bool isSignCheck) {
2885 if (isSignCheck)
2886 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002887
Owen Andersond490c2d2011-01-11 00:36:45 +00002888 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2889 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002890 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002891
Owen Andersond490c2d2011-01-11 00:36:45 +00002892 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002893 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002894 // correspond to the trailing ones of the comparand. The value of these
2895 // bits doesn't impact the outcome of the comparison, because any value
2896 // greater than the RHS must differ in a bit higher than these due to carry.
2897 case ICmpInst::ICMP_UGT: {
2898 unsigned trailingOnes = RHS.countTrailingOnes();
2899 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2900 return ~lowBitsSet;
2901 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002902
Owen Andersond490c2d2011-01-11 00:36:45 +00002903 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2904 // Any value less than the RHS must differ in a higher bit because of carries.
2905 case ICmpInst::ICMP_ULT: {
2906 unsigned trailingZeros = RHS.countTrailingZeros();
2907 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2908 return ~lowBitsSet;
2909 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002910
Owen Andersond490c2d2011-01-11 00:36:45 +00002911 default:
2912 return APInt::getAllOnesValue(BitWidth);
2913 }
Owen Andersond490c2d2011-01-11 00:36:45 +00002914}
Chris Lattner2188e402010-01-04 07:37:31 +00002915
Quentin Colombet5ab55552013-09-09 20:56:48 +00002916/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2917/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002918/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002919/// as subtract operands and their positions in those instructions.
2920/// The rational is that several architectures use the same instruction for
2921/// both subtract and cmp, thus it is better if the order of those operands
2922/// match.
2923/// \return true if Op0 and Op1 should be swapped.
2924static bool swapMayExposeCSEOpportunities(const Value * Op0,
2925 const Value * Op1) {
2926 // Filter out pointer value as those cannot appears directly in subtract.
2927 // FIXME: we may want to go through inttoptrs or bitcasts.
2928 if (Op0->getType()->isPointerTy())
2929 return false;
2930 // Count every uses of both Op0 and Op1 in a subtract.
2931 // Each time Op0 is the first operand, count -1: swapping is bad, the
2932 // subtract has already the same layout as the compare.
2933 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002934 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002935 // At the end, if the benefit is greater than 0, Op0 should come second to
2936 // expose more CSE opportunities.
2937 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002938 for (const User *U : Op0->users()) {
2939 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002940 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2941 continue;
2942 // If Op0 is the first argument, this is not beneficial to swap the
2943 // arguments.
2944 int LocalSwapBenefits = -1;
2945 unsigned Op1Idx = 1;
2946 if (BinOp->getOperand(Op1Idx) == Op0) {
2947 Op1Idx = 0;
2948 LocalSwapBenefits = 1;
2949 }
2950 if (BinOp->getOperand(Op1Idx) != Op1)
2951 continue;
2952 GlobalSwapBenefits += LocalSwapBenefits;
2953 }
2954 return GlobalSwapBenefits > 0;
2955}
2956
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002957/// \brief Check that one use is in the same block as the definition and all
2958/// other uses are in blocks dominated by a given block
2959///
2960/// \param DI Definition
2961/// \param UI Use
2962/// \param DB Block that must dominate all uses of \p DI outside
2963/// the parent block
2964/// \return true when \p UI is the only use of \p DI in the parent block
2965/// and all other uses of \p DI are in blocks dominated by \p DB.
2966///
2967bool InstCombiner::dominatesAllUses(const Instruction *DI,
2968 const Instruction *UI,
2969 const BasicBlock *DB) const {
2970 assert(DI && UI && "Instruction not defined\n");
2971 // ignore incomplete definitions
2972 if (!DI->getParent())
2973 return false;
2974 // DI and UI must be in the same block
2975 if (DI->getParent() != UI->getParent())
2976 return false;
2977 // Protect from self-referencing blocks
2978 if (DI->getParent() == DB)
2979 return false;
2980 // DominatorTree available?
2981 if (!DT)
2982 return false;
2983 for (const User *U : DI->users()) {
2984 auto *Usr = cast<Instruction>(U);
2985 if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
2986 return false;
2987 }
2988 return true;
2989}
2990
2991///
2992/// true when the instruction sequence within a block is select-cmp-br.
2993///
2994static bool isChainSelectCmpBranch(const SelectInst *SI) {
2995 const BasicBlock *BB = SI->getParent();
2996 if (!BB)
2997 return false;
2998 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
2999 if (!BI || BI->getNumSuccessors() != 2)
3000 return false;
3001 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3002 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3003 return false;
3004 return true;
3005}
3006
3007///
3008/// \brief True when a select result is replaced by one of its operands
3009/// in select-icmp sequence. This will eventually result in the elimination
3010/// of the select.
3011///
3012/// \param SI Select instruction
3013/// \param Icmp Compare instruction
3014/// \param SIOpd Operand that replaces the select
3015///
3016/// Notes:
3017/// - The replacement is global and requires dominator information
3018/// - The caller is responsible for the actual replacement
3019///
3020/// Example:
3021///
3022/// entry:
3023/// %4 = select i1 %3, %C* %0, %C* null
3024/// %5 = icmp eq %C* %4, null
3025/// br i1 %5, label %9, label %7
3026/// ...
3027/// ; <label>:7 ; preds = %entry
3028/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3029/// ...
3030///
3031/// can be transformed to
3032///
3033/// %5 = icmp eq %C* %0, null
3034/// %6 = select i1 %3, i1 %5, i1 true
3035/// br i1 %6, label %9, label %7
3036/// ...
3037/// ; <label>:7 ; preds = %entry
3038/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3039///
3040/// Similar when the first operand of the select is a constant or/and
3041/// the compare is for not equal rather than equal.
3042///
3043/// NOTE: The function is only called when the select and compare constants
3044/// are equal, the optimization can work only for EQ predicates. This is not a
3045/// major restriction since a NE compare should be 'normalized' to an equal
3046/// compare, which usually happens in the combiner and test case
3047/// select-cmp-br.ll
3048/// checks for it.
3049bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3050 const ICmpInst *Icmp,
3051 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003052 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003053 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3054 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3055 // The check for the unique predecessor is not the best that can be
3056 // done. But it protects efficiently against cases like when SI's
3057 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3058 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3059 // replaced can be reached on either path. So the uniqueness check
3060 // guarantees that the path all uses of SI (outside SI's parent) are on
3061 // is disjoint from all other paths out of SI. But that information
3062 // is more expensive to compute, and the trade-off here is in favor
3063 // of compile-time.
3064 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3065 NumSel++;
3066 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3067 return true;
3068 }
3069 }
3070 return false;
3071}
3072
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003073/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3074/// it into the appropriate icmp lt or icmp gt instruction. This transform
3075/// allows them to be folded in visitICmpInst.
3076static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I,
3077 InstCombiner::BuilderTy &Builder) {
3078 Value *Op0 = I.getOperand(0);
3079 Value *Op1 = I.getOperand(1);
3080
3081 if (auto *Op1C = dyn_cast<ConstantInt>(Op1)) {
3082 // For scalars, SimplifyICmpInst has already handled the edge cases for us,
3083 // so we just assert on them.
3084 APInt Op1Val = Op1C->getValue();
3085 switch (I.getPredicate()) {
3086 case ICmpInst::ICMP_ULE:
3087 assert(!Op1C->isMaxValue(false)); // A <=u MAX -> TRUE
3088 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, Builder.getInt(Op1Val + 1));
3089 case ICmpInst::ICMP_SLE:
3090 assert(!Op1C->isMaxValue(true)); // A <=s MAX -> TRUE
3091 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Builder.getInt(Op1Val + 1));
3092 case ICmpInst::ICMP_UGE:
3093 assert(!Op1C->isMinValue(false)); // A >=u MIN -> TRUE
3094 return new ICmpInst(ICmpInst::ICMP_UGT, Op0, Builder.getInt(Op1Val - 1));
3095 case ICmpInst::ICMP_SGE:
3096 assert(!Op1C->isMinValue(true)); // A >=s MIN -> TRUE
3097 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, Builder.getInt(Op1Val - 1));
3098 default:
3099 break;
3100 }
3101 }
3102
3103 // TODO: Handle vectors.
3104
3105 return nullptr;
3106}
3107
Chris Lattner2188e402010-01-04 07:37:31 +00003108Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3109 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003111 unsigned Op0Cplxity = getComplexity(Op0);
3112 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003113
Chris Lattner2188e402010-01-04 07:37:31 +00003114 /// Orders the operands of the compare so that they are listed from most
3115 /// complex to least complex. This puts constants before unary operators,
3116 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003117 if (Op0Cplxity < Op1Cplxity ||
3118 (Op0Cplxity == Op1Cplxity &&
3119 swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003120 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003121 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003122 Changed = true;
3123 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003124
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003125 if (Value *V =
3126 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003127 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003128
Pete Cooperbc5c5242011-12-01 03:58:40 +00003129 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003130 // ie, abs(val) != 0 -> val != 0
Pete Cooperbc5c5242011-12-01 03:58:40 +00003131 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
3132 {
Pete Cooperfdddc272011-12-01 19:13:26 +00003133 Value *Cond, *SelectTrue, *SelectFalse;
3134 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003135 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003136 if (Value *V = dyn_castNegVal(SelectTrue)) {
3137 if (V == SelectFalse)
3138 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3139 }
3140 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3141 if (V == SelectTrue)
3142 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003143 }
3144 }
3145 }
3146
Chris Lattner229907c2011-07-18 04:54:35 +00003147 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003148
3149 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sands9dff9be2010-02-15 16:12:20 +00003150 if (Ty->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003151 switch (I.getPredicate()) {
3152 default: llvm_unreachable("Invalid icmp instruction!");
3153 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3154 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
3155 return BinaryOperator::CreateNot(Xor);
3156 }
3157 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
3158 return BinaryOperator::CreateXor(Op0, Op1);
3159
3160 case ICmpInst::ICMP_UGT:
3161 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
3162 // FALL THROUGH
3163 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3164 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
3165 return BinaryOperator::CreateAnd(Not, Op1);
3166 }
3167 case ICmpInst::ICMP_SGT:
3168 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
3169 // FALL THROUGH
3170 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
3171 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
3172 return BinaryOperator::CreateAnd(Not, Op0);
3173 }
3174 case ICmpInst::ICMP_UGE:
3175 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
3176 // FALL THROUGH
3177 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3178 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
3179 return BinaryOperator::CreateOr(Not, Op1);
3180 }
3181 case ICmpInst::ICMP_SGE:
3182 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
3183 // FALL THROUGH
3184 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3185 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
3186 return BinaryOperator::CreateOr(Not, Op0);
3187 }
3188 }
3189 }
3190
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003191 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I, *Builder))
3192 return NewICmp;
3193
Chris Lattner2188e402010-01-04 07:37:31 +00003194 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003195 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00003196 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003197 else // Get pointer size.
3198 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003199
Chris Lattner2188e402010-01-04 07:37:31 +00003200 bool isSignBit = false;
3201
3202 // See if we are doing a comparison with a constant.
3203 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00003204 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003205
Owen Anderson1294ea72010-12-17 18:08:00 +00003206 // Match the following pattern, which is a common idiom when writing
3207 // overflow-safe integer arithmetic function. The source performs an
3208 // addition in wider type, and explicitly checks for overflow using
3209 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
3210 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00003211 //
3212 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00003213 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00003214 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003215 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00003216 // sum = a + b
3217 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00003218 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00003219 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00003220 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00003221 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00003222 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00003223 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00003224 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003225
Philip Reamesec8a8b52016-03-09 21:05:07 +00003226 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3227 if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3228 if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3229 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3230 if (SPR.Flavor == SPF_SMIN) {
Philip Reames8f12eba2016-03-09 21:31:47 +00003231 if (isKnownPositive(A, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003232 return new ICmpInst(I.getPredicate(), B, CI);
Philip Reames8f12eba2016-03-09 21:31:47 +00003233 if (isKnownPositive(B, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003234 return new ICmpInst(I.getPredicate(), A, CI);
3235 }
3236 }
3237
3238
David Majnemera0afb552015-01-14 19:26:56 +00003239 // The following transforms are only 'worth it' if the only user of the
3240 // subtraction is the icmp.
3241 if (Op0->hasOneUse()) {
3242 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3243 if (I.isEquality() && CI->isZero() &&
3244 match(Op0, m_Sub(m_Value(A), m_Value(B))))
3245 return new ICmpInst(I.getPredicate(), A, B);
3246
3247 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3248 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3249 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3250 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3251
3252 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3253 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3254 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3255 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3256
3257 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3258 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3259 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3260 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3261
3262 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3263 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3264 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3265 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00003266 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003267
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003268 if (I.isEquality()) {
3269 ConstantInt *CI2;
3270 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3271 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00003272 // (icmp eq/ne (ashr/lshr const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00003273 if (Instruction *Inst = FoldICmpCstShrCst(I, Op0, A, CI, CI2))
3274 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003275 }
David Majnemer59939ac2014-10-19 08:23:08 +00003276 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3277 // (icmp eq/ne (shl const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00003278 if (Instruction *Inst = FoldICmpCstShlCst(I, Op0, A, CI, CI2))
3279 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00003280 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003281 }
3282
Chris Lattner2188e402010-01-04 07:37:31 +00003283 // If this comparison is a normal comparison, it demands all
3284 // bits, if it is a sign bit comparison, it only demands the sign bit.
3285 bool UnusedBit;
3286 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
3287 }
3288
3289 // See if we can fold the comparison based on range information we can get
3290 // by checking whether bits are known to be zero or one in the input.
3291 if (BitWidth != 0) {
3292 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3293 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3294
3295 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00003296 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00003297 Op0KnownZero, Op0KnownOne, 0))
3298 return &I;
3299 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003300 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
3301 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00003302 return &I;
3303
3304 // Given the known and unknown bits, compute a range that the LHS could be
3305 // in. Compute the Min, Max and RHS values based on the known bits. For the
3306 // EQ and NE we use unsigned values.
3307 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3308 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3309 if (I.isSigned()) {
3310 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3311 Op0Min, Op0Max);
3312 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3313 Op1Min, Op1Max);
3314 } else {
3315 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3316 Op0Min, Op0Max);
3317 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3318 Op1Min, Op1Max);
3319 }
3320
3321 // If Min and Max are known to be the same, then SimplifyDemandedBits
3322 // figured out that the LHS is a constant. Just constant fold this now so
3323 // that code below can assume that Min != Max.
3324 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3325 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00003326 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003327 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3328 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00003329 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00003330
3331 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00003332 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00003333 switch (I.getPredicate()) {
3334 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00003335 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00003336 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003337 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003338
Chris Lattnerf7e89612010-11-21 06:44:42 +00003339 // If all bits are known zero except for one, then we know at most one
3340 // bit is set. If the comparison is against zero, then this is a check
3341 // to see if *that* bit is set.
3342 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003343 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003344 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003345 Value *LHS = nullptr;
3346 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003347 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3348 LHSC->getValue() != Op0KnownZeroInverted)
3349 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003350
Chris Lattnerf7e89612010-11-21 06:44:42 +00003351 // 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 +00003352 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003353 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00003354 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003355 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003356 APInt ValToCheck = Op0KnownZeroInverted;
3357 if (ValToCheck.isPowerOf2()) {
3358 unsigned CmpVal = ValToCheck.countTrailingZeros();
3359 return new ICmpInst(ICmpInst::ICMP_NE, X,
3360 ConstantInt::get(X->getType(), CmpVal));
3361 } else if ((++ValToCheck).isPowerOf2()) {
3362 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3363 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3364 ConstantInt::get(X->getType(), CmpVal));
3365 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003366 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003367
Chris Lattnerf7e89612010-11-21 06:44:42 +00003368 // 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 +00003369 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00003370 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003371 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003372 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003373 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00003374 ConstantInt::get(X->getType(),
3375 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003376 }
Chris Lattner2188e402010-01-04 07:37:31 +00003377 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003378 }
3379 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00003380 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003381 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003382
Chris Lattnerf7e89612010-11-21 06:44:42 +00003383 // If all bits are known zero except for one, then we know at most one
3384 // bit is set. If the comparison is against zero, then this is a check
3385 // to see if *that* bit is set.
3386 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003387 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003388 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003389 Value *LHS = nullptr;
3390 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003391 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3392 LHSC->getValue() != Op0KnownZeroInverted)
3393 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003394
Chris Lattnerf7e89612010-11-21 06:44:42 +00003395 // 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 +00003396 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003397 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00003398 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003399 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003400 APInt ValToCheck = Op0KnownZeroInverted;
3401 if (ValToCheck.isPowerOf2()) {
3402 unsigned CmpVal = ValToCheck.countTrailingZeros();
3403 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3404 ConstantInt::get(X->getType(), CmpVal));
3405 } else if ((++ValToCheck).isPowerOf2()) {
3406 unsigned CmpVal = ValToCheck.countTrailingZeros();
3407 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3408 ConstantInt::get(X->getType(), CmpVal));
3409 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003410 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003411
Chris Lattnerf7e89612010-11-21 06:44:42 +00003412 // 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 +00003413 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00003414 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003415 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003416 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003417 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00003418 ConstantInt::get(X->getType(),
3419 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003420 }
Chris Lattner2188e402010-01-04 07:37:31 +00003421 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003422 }
Chris Lattner2188e402010-01-04 07:37:31 +00003423 case ICmpInst::ICMP_ULT:
3424 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003425 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003426 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003427 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003428 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3429 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3430 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3431 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
3432 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003433 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003434
3435 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3436 if (CI->isMinValue(true))
3437 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3438 Constant::getAllOnesValue(Op0->getType()));
3439 }
3440 break;
3441 case ICmpInst::ICMP_UGT:
3442 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003443 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003444 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003445 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003446
3447 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3448 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3449 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3450 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
3451 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003452 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003453
3454 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3455 if (CI->isMaxValue(true))
3456 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3457 Constant::getNullValue(Op0->getType()));
3458 }
3459 break;
3460 case ICmpInst::ICMP_SLT:
3461 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003462 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003463 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003464 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003465 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3466 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3467 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3468 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3469 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003470 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003471 }
3472 break;
3473 case ICmpInst::ICMP_SGT:
3474 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003475 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003476 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003477 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003478
3479 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3480 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3481 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3482 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3483 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003484 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003485 }
3486 break;
3487 case ICmpInst::ICMP_SGE:
3488 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3489 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003490 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003491 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003492 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003493 break;
3494 case ICmpInst::ICMP_SLE:
3495 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3496 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003497 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003498 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003499 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003500 break;
3501 case ICmpInst::ICMP_UGE:
3502 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3503 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003504 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003505 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003506 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003507 break;
3508 case ICmpInst::ICMP_ULE:
3509 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3510 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003511 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003512 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003513 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003514 break;
3515 }
3516
3517 // Turn a signed comparison into an unsigned one if both operands
3518 // are known to have the same sign.
3519 if (I.isSigned() &&
3520 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3521 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3522 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3523 }
3524
3525 // Test if the ICmpInst instruction is used exclusively by a select as
3526 // part of a minimum or maximum operation. If so, refrain from doing
3527 // any other folding. This helps out other analyses which understand
3528 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3529 // and CodeGen. And in this case, at least one of the comparison
3530 // operands has at least one user besides the compare (the select),
3531 // which would often largely negate the benefit of folding anyway.
3532 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003533 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003534 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3535 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003536 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003537
3538 // See if we are doing a comparison between a constant and an instruction that
3539 // can be folded into the comparison.
3540 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003541 // Since the RHS is a ConstantInt (CI), if the left hand side is an
3542 // instruction, see if that instruction also has constants so that the
3543 // instruction can be folded into the icmp
Chris Lattner2188e402010-01-04 07:37:31 +00003544 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3545 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
3546 return Res;
3547 }
3548
3549 // Handle icmp with constant (but not simple integer constant) RHS
3550 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3551 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3552 switch (LHSI->getOpcode()) {
3553 case Instruction::GetElementPtr:
3554 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3555 if (RHSC->isNullValue() &&
3556 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3557 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3558 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3559 break;
3560 case Instruction::PHI:
3561 // Only fold icmp into the PHI if the phi and icmp are in the same
3562 // block. If in the same block, we're encouraging jump threading. If
3563 // not, we are just pessimizing the code by making an i1 phi.
3564 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003565 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003566 return NV;
3567 break;
3568 case Instruction::Select: {
3569 // If either operand of the select is a constant, we can fold the
3570 // comparison into the select arms, which will cause one to be
3571 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003572 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003573 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003574 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003575 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003576 CI = dyn_cast<ConstantInt>(Op1);
3577 }
3578 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003579 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003580 CI = dyn_cast<ConstantInt>(Op2);
3581 }
Chris Lattner2188e402010-01-04 07:37:31 +00003582
3583 // We only want to perform this transformation if it will not lead to
3584 // additional code. This is true if either both sides of the select
3585 // fold to a constant (in which case the icmp is replaced with a select
3586 // which will usually simplify) or this is the only user of the
3587 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003588 // select+icmp) or all uses of the select can be replaced based on
3589 // dominance information ("Global cases").
3590 bool Transform = false;
3591 if (Op1 && Op2)
3592 Transform = true;
3593 else if (Op1 || Op2) {
3594 // Local case
3595 if (LHSI->hasOneUse())
3596 Transform = true;
3597 // Global cases
3598 else if (CI && !CI->isZero())
3599 // When Op1 is constant try replacing select with second operand.
3600 // Otherwise Op2 is constant and try replacing select with first
3601 // operand.
3602 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3603 Op1 ? 2 : 1);
3604 }
3605 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003606 if (!Op1)
3607 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3608 RHSC, I.getName());
3609 if (!Op2)
3610 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3611 RHSC, I.getName());
3612 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3613 }
3614 break;
3615 }
Chris Lattner2188e402010-01-04 07:37:31 +00003616 case Instruction::IntToPtr:
3617 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003618 if (RHSC->isNullValue() &&
3619 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003620 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3621 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3622 break;
3623
3624 case Instruction::Load:
3625 // Try to optimize things like "A[i] > 4" to index computations.
3626 if (GetElementPtrInst *GEP =
3627 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3628 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3629 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3630 !cast<LoadInst>(LHSI)->isVolatile())
3631 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3632 return Res;
3633 }
3634 break;
3635 }
3636 }
3637
3638 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3639 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
3640 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
3641 return NI;
3642 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
3643 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
3644 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3645 return NI;
3646
Hans Wennborgf1f36512015-10-07 00:20:07 +00003647 // Try to optimize equality comparisons against alloca-based pointers.
3648 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3649 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3650 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
3651 if (Instruction *New = FoldAllocaCmp(I, Alloca, Op1))
3652 return New;
3653 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
3654 if (Instruction *New = FoldAllocaCmp(I, Alloca, Op0))
3655 return New;
3656 }
3657
Chris Lattner2188e402010-01-04 07:37:31 +00003658 // Test to see if the operands of the icmp are casted versions of other
3659 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3660 // now.
3661 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003662 if (Op0->getType()->isPointerTy() &&
3663 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003664 // We keep moving the cast from the left operand over to the right
3665 // operand, where it can often be eliminated completely.
3666 Op0 = CI->getOperand(0);
3667
3668 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3669 // so eliminate it as well.
3670 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3671 Op1 = CI2->getOperand(0);
3672
3673 // If Op1 is a constant, we can fold the cast into the constant.
3674 if (Op0->getType() != Op1->getType()) {
3675 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3676 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3677 } else {
3678 // Otherwise, cast the RHS right before the icmp
3679 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3680 }
3681 }
3682 return new ICmpInst(I.getPredicate(), Op0, Op1);
3683 }
3684 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003685
Chris Lattner2188e402010-01-04 07:37:31 +00003686 if (isa<CastInst>(Op0)) {
3687 // Handle the special case of: icmp (cast bool to X), <cst>
3688 // This comes up when you have code like
3689 // int X = A < B;
3690 // if (X) ...
3691 // For generality, we handle any zero-extension of any operand comparison
3692 // with a constant or another cast from the same type.
3693 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
3694 if (Instruction *R = visitICmpInstWithCastAndCast(I))
3695 return R;
3696 }
Chris Lattner2188e402010-01-04 07:37:31 +00003697
Duncan Sandse5220012011-02-17 07:46:37 +00003698 // Special logic for binary operators.
3699 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3700 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3701 if (BO0 || BO1) {
3702 CmpInst::Predicate Pred = I.getPredicate();
3703 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3704 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3705 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3706 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3707 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3708 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3709 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3710 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3711 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3712
3713 // Analyze the case when either Op0 or Op1 is an add instruction.
3714 // 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 +00003715 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003716 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3717 A = BO0->getOperand(0);
3718 B = BO0->getOperand(1);
3719 }
3720 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3721 C = BO1->getOperand(0);
3722 D = BO1->getOperand(1);
3723 }
Duncan Sandse5220012011-02-17 07:46:37 +00003724
David Majnemer549f4f22014-11-01 09:09:51 +00003725 // icmp (X+cst) < 0 --> X < -cst
3726 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3727 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3728 if (!RHSC->isMinValue(/*isSigned=*/true))
3729 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3730
Duncan Sandse5220012011-02-17 07:46:37 +00003731 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3732 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3733 return new ICmpInst(Pred, A == Op1 ? B : A,
3734 Constant::getNullValue(Op1->getType()));
3735
3736 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3737 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3738 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3739 C == Op0 ? D : C);
3740
Duncan Sands84653b32011-02-18 16:25:37 +00003741 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003742 if (A && C && (A == C || A == D || B == C || B == D) &&
3743 NoOp0WrapProblem && NoOp1WrapProblem &&
3744 // Try not to increase register pressure.
3745 BO0->hasOneUse() && BO1->hasOneUse()) {
3746 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003747 Value *Y, *Z;
3748 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003749 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003750 Y = B;
3751 Z = D;
3752 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003753 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003754 Y = B;
3755 Z = C;
3756 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003757 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003758 Y = A;
3759 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003760 } else {
3761 assert(B == D);
3762 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003763 Y = A;
3764 Z = C;
3765 }
Duncan Sandse5220012011-02-17 07:46:37 +00003766 return new ICmpInst(Pred, Y, Z);
3767 }
3768
David Majnemerb81cd632013-04-11 20:05:46 +00003769 // icmp slt (X + -1), Y -> icmp sle X, Y
3770 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3771 match(B, m_AllOnes()))
3772 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3773
3774 // icmp sge (X + -1), Y -> icmp sgt X, Y
3775 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3776 match(B, m_AllOnes()))
3777 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3778
3779 // icmp sle (X + 1), Y -> icmp slt X, Y
3780 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3781 match(B, m_One()))
3782 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3783
3784 // icmp sgt (X + 1), Y -> icmp sge X, Y
3785 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3786 match(B, m_One()))
3787 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3788
Michael Liaoc65d3862015-10-19 22:08:14 +00003789 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3790 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3791 match(D, m_AllOnes()))
3792 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3793
3794 // icmp sle X, (Y + -1) -> icmp slt X, Y
3795 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3796 match(D, m_AllOnes()))
3797 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3798
3799 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3800 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3801 match(D, m_One()))
3802 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3803
3804 // icmp slt X, (Y + 1) -> icmp sle X, Y
3805 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3806 match(D, m_One()))
3807 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3808
David Majnemerb81cd632013-04-11 20:05:46 +00003809 // if C1 has greater magnitude than C2:
3810 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3811 // s.t. C3 = C1 - C2
3812 //
3813 // if C2 has greater magnitude than C1:
3814 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3815 // s.t. C3 = C2 - C1
3816 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3817 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3818 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3819 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3820 const APInt &AP1 = C1->getValue();
3821 const APInt &AP2 = C2->getValue();
3822 if (AP1.isNegative() == AP2.isNegative()) {
3823 APInt AP1Abs = C1->getValue().abs();
3824 APInt AP2Abs = C2->getValue().abs();
3825 if (AP1Abs.uge(AP2Abs)) {
3826 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3827 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3828 return new ICmpInst(Pred, NewAdd, C);
3829 } else {
3830 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3831 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3832 return new ICmpInst(Pred, A, NewAdd);
3833 }
3834 }
3835 }
3836
3837
Duncan Sandse5220012011-02-17 07:46:37 +00003838 // Analyze the case when either Op0 or Op1 is a sub instruction.
3839 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
Richard Trieu7a083812016-02-18 22:09:30 +00003840 A = nullptr;
3841 B = nullptr;
3842 C = nullptr;
3843 D = nullptr;
3844 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3845 A = BO0->getOperand(0);
3846 B = BO0->getOperand(1);
3847 }
3848 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3849 C = BO1->getOperand(0);
3850 D = BO1->getOperand(1);
3851 }
Duncan Sandse5220012011-02-17 07:46:37 +00003852
Duncan Sands84653b32011-02-18 16:25:37 +00003853 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3854 if (A == Op1 && NoOp0WrapProblem)
3855 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3856
3857 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3858 if (C == Op0 && NoOp1WrapProblem)
3859 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3860
3861 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003862 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3863 // Try not to increase register pressure.
3864 BO0->hasOneUse() && BO1->hasOneUse())
3865 return new ICmpInst(Pred, A, C);
3866
Duncan Sands84653b32011-02-18 16:25:37 +00003867 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3868 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3869 // Try not to increase register pressure.
3870 BO0->hasOneUse() && BO1->hasOneUse())
3871 return new ICmpInst(Pred, D, B);
3872
David Majnemer186c9422014-05-15 00:02:20 +00003873 // icmp (0-X) < cst --> x > -cst
3874 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3875 Value *X;
3876 if (match(BO0, m_Neg(m_Value(X))))
3877 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3878 if (!RHSC->isMinValue(/*isSigned=*/true))
3879 return new ICmpInst(I.getSwappedPredicate(), X,
3880 ConstantExpr::getNeg(RHSC));
3881 }
3882
Craig Topperf40110f2014-04-25 05:29:35 +00003883 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003884 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00003885 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3886 Op1 == BO0->getOperand(1))
3887 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003888 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00003889 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3890 Op0 == BO1->getOperand(1))
3891 SRem = BO1;
3892 if (SRem) {
3893 // We don't check hasOneUse to avoid increasing register pressure because
3894 // the value we use is the same value this instruction was already using.
3895 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3896 default: break;
3897 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00003898 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003899 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00003900 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003901 case ICmpInst::ICMP_SGT:
3902 case ICmpInst::ICMP_SGE:
3903 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3904 Constant::getAllOnesValue(SRem->getType()));
3905 case ICmpInst::ICMP_SLT:
3906 case ICmpInst::ICMP_SLE:
3907 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3908 Constant::getNullValue(SRem->getType()));
3909 }
3910 }
3911
Duncan Sandse5220012011-02-17 07:46:37 +00003912 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
3913 BO0->hasOneUse() && BO1->hasOneUse() &&
3914 BO0->getOperand(1) == BO1->getOperand(1)) {
3915 switch (BO0->getOpcode()) {
3916 default: break;
3917 case Instruction::Add:
3918 case Instruction::Sub:
3919 case Instruction::Xor:
3920 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3921 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3922 BO1->getOperand(0));
3923 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
3924 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3925 if (CI->getValue().isSignBit()) {
3926 ICmpInst::Predicate Pred = I.isSigned()
3927 ? I.getUnsignedPredicate()
3928 : I.getSignedPredicate();
3929 return new ICmpInst(Pred, BO0->getOperand(0),
3930 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00003931 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003932
David Majnemerf8853ae2016-02-01 17:37:56 +00003933 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00003934 ICmpInst::Predicate Pred = I.isSigned()
3935 ? I.getUnsignedPredicate()
3936 : I.getSignedPredicate();
3937 Pred = I.getSwappedPredicate(Pred);
3938 return new ICmpInst(Pred, BO0->getOperand(0),
3939 BO1->getOperand(0));
3940 }
Chris Lattner2188e402010-01-04 07:37:31 +00003941 }
Duncan Sandse5220012011-02-17 07:46:37 +00003942 break;
3943 case Instruction::Mul:
3944 if (!I.isEquality())
3945 break;
3946
3947 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3948 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
3949 // Mask = -1 >> count-trailing-zeros(Cst).
3950 if (!CI->isZero() && !CI->isOne()) {
3951 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003952 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00003953 APInt::getLowBitsSet(AP.getBitWidth(),
3954 AP.getBitWidth() -
3955 AP.countTrailingZeros()));
3956 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
3957 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
3958 return new ICmpInst(I.getPredicate(), And1, And2);
3959 }
3960 }
3961 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00003962 case Instruction::UDiv:
3963 case Instruction::LShr:
3964 if (I.isSigned())
3965 break;
3966 // fall-through
3967 case Instruction::SDiv:
3968 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00003969 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00003970 break;
3971 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3972 BO1->getOperand(0));
3973 case Instruction::Shl: {
3974 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3975 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3976 if (!NUW && !NSW)
3977 break;
3978 if (!NSW && I.isSigned())
3979 break;
3980 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3981 BO1->getOperand(0));
3982 }
Chris Lattner2188e402010-01-04 07:37:31 +00003983 }
3984 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00003985
3986 if (BO0) {
3987 // Transform A & (L - 1) `ult` L --> L != 0
3988 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
3989 auto BitwiseAnd =
3990 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
3991
3992 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
3993 auto *Zero = Constant::getNullValue(BO0->getType());
3994 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
3995 }
3996 }
Chris Lattner2188e402010-01-04 07:37:31 +00003997 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003998
Chris Lattner2188e402010-01-04 07:37:31 +00003999 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004000 // Transform (A & ~B) == 0 --> (A & B) != 0
4001 // and (A & ~B) != 0 --> (A & B) == 0
4002 // if A is a power of 2.
4003 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004004 match(Op1, m_Zero()) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004005 isKnownToBeAPowerOfTwo(A, DL, false, 0, AC, &I, DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004006 return new ICmpInst(I.getInversePredicate(),
4007 Builder->CreateAnd(A, B),
4008 Op1);
4009
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004010 // ~x < ~y --> y < x
4011 // ~x < cst --> ~cst < x
4012 if (match(Op0, m_Not(m_Value(A)))) {
4013 if (match(Op1, m_Not(m_Value(B))))
4014 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004015 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004016 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4017 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004018
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004019 Instruction *AddI = nullptr;
4020 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4021 m_Instruction(AddI))) &&
4022 isa<IntegerType>(A->getType())) {
4023 Value *Result;
4024 Constant *Overflow;
4025 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4026 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004027 replaceInstUsesWith(*AddI, Result);
4028 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004029 }
4030 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004031
4032 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4033 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4034 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4035 return R;
4036 }
4037 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4038 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4039 return R;
4040 }
Chris Lattner2188e402010-01-04 07:37:31 +00004041 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004042
Chris Lattner2188e402010-01-04 07:37:31 +00004043 if (I.isEquality()) {
4044 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004045
Chris Lattner2188e402010-01-04 07:37:31 +00004046 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4047 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4048 Value *OtherVal = A == Op1 ? B : A;
4049 return new ICmpInst(I.getPredicate(), OtherVal,
4050 Constant::getNullValue(A->getType()));
4051 }
4052
4053 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4054 // A^c1 == C^c2 --> A == C^(c1^c2)
4055 ConstantInt *C1, *C2;
4056 if (match(B, m_ConstantInt(C1)) &&
4057 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004058 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004059 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004060 return new ICmpInst(I.getPredicate(), A, Xor);
4061 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004062
Chris Lattner2188e402010-01-04 07:37:31 +00004063 // A^B == A^D -> B == D
4064 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4065 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4066 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4067 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4068 }
4069 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004070
Chris Lattner2188e402010-01-04 07:37:31 +00004071 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4072 (A == Op0 || B == Op0)) {
4073 // A == (A^B) -> B == 0
4074 Value *OtherVal = A == Op0 ? B : A;
4075 return new ICmpInst(I.getPredicate(), OtherVal,
4076 Constant::getNullValue(A->getType()));
4077 }
4078
Chris Lattner2188e402010-01-04 07:37:31 +00004079 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004080 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004081 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004082 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004083
Chris Lattner2188e402010-01-04 07:37:31 +00004084 if (A == C) {
4085 X = B; Y = D; Z = A;
4086 } else if (A == D) {
4087 X = B; Y = C; Z = A;
4088 } else if (B == C) {
4089 X = A; Y = D; Z = B;
4090 } else if (B == D) {
4091 X = A; Y = C; Z = B;
4092 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004093
Chris Lattner2188e402010-01-04 07:37:31 +00004094 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004095 Op1 = Builder->CreateXor(X, Y);
4096 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004097 I.setOperand(0, Op1);
4098 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4099 return &I;
4100 }
4101 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004102
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004103 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004104 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004105 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004106 if ((Op0->hasOneUse() &&
4107 match(Op0, m_ZExt(m_Value(A))) &&
4108 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4109 (Op1->hasOneUse() &&
4110 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4111 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004112 APInt Pow2 = Cst1->getValue() + 1;
4113 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4114 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4115 return new ICmpInst(I.getPredicate(), A,
4116 Builder->CreateTrunc(B, A->getType()));
4117 }
4118
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004119 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4120 // For lshr and ashr pairs.
4121 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4122 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4123 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4124 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4125 unsigned TypeBits = Cst1->getBitWidth();
4126 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4127 if (ShAmt < TypeBits && ShAmt != 0) {
4128 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4129 ? ICmpInst::ICMP_UGE
4130 : ICmpInst::ICMP_ULT;
4131 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4132 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4133 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4134 }
4135 }
4136
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004137 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4138 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4139 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4140 unsigned TypeBits = Cst1->getBitWidth();
4141 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4142 if (ShAmt < TypeBits && ShAmt != 0) {
4143 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4144 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4145 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4146 I.getName() + ".mask");
4147 return new ICmpInst(I.getPredicate(), And,
4148 Constant::getNullValue(Cst1->getType()));
4149 }
4150 }
4151
Chris Lattner1b06c712011-04-26 20:18:20 +00004152 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4153 // "icmp (and X, mask), cst"
4154 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004155 if (Op0->hasOneUse() &&
4156 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4157 m_ConstantInt(ShAmt))))) &&
4158 match(Op1, m_ConstantInt(Cst1)) &&
4159 // Only do this when A has multiple uses. This is most important to do
4160 // when it exposes other optimizations.
4161 !A->hasOneUse()) {
4162 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004163
Chris Lattner1b06c712011-04-26 20:18:20 +00004164 if (ShAmt < ASize) {
4165 APInt MaskV =
4166 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4167 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004168
Chris Lattner1b06c712011-04-26 20:18:20 +00004169 APInt CmpV = Cst1->getValue().zext(ASize);
4170 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004171
Chris Lattner1b06c712011-04-26 20:18:20 +00004172 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4173 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4174 }
4175 }
Chris Lattner2188e402010-01-04 07:37:31 +00004176 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004177
David Majnemerc1eca5a2014-11-06 23:23:30 +00004178 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4179 // an i1 which indicates whether or not we successfully did the swap.
4180 //
4181 // Replace comparisons between the old value and the expected value with the
4182 // indicator that 'cmpxchg' returns.
4183 //
4184 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4185 // spuriously fail. In those cases, the old value may equal the expected
4186 // value but it is possible for the swap to not occur.
4187 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4188 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4189 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4190 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4191 !ACXI->isWeak())
4192 return ExtractValueInst::Create(ACXI, 1);
4193
Chris Lattner2188e402010-01-04 07:37:31 +00004194 {
4195 Value *X; ConstantInt *Cst;
4196 // icmp X+Cst, X
4197 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00004198 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004199
4200 // icmp X, X+Cst
4201 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00004202 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004203 }
Craig Topperf40110f2014-04-25 05:29:35 +00004204 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004205}
4206
Chris Lattner2188e402010-01-04 07:37:31 +00004207/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
Chris Lattner2188e402010-01-04 07:37:31 +00004208Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4209 Instruction *LHSI,
4210 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004211 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004212 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004213
Chris Lattner2188e402010-01-04 07:37:31 +00004214 // Get the width of the mantissa. We don't want to hack on conversions that
4215 // might lose information from the integer, e.g. "i64 -> float"
4216 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004217 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004218
Matt Arsenault55e73122015-01-06 15:50:59 +00004219 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4220
Chris Lattner2188e402010-01-04 07:37:31 +00004221 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004222
Matt Arsenault55e73122015-01-06 15:50:59 +00004223 if (I.isEquality()) {
4224 FCmpInst::Predicate P = I.getPredicate();
4225 bool IsExact = false;
4226 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4227 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4228
4229 // If the floating point constant isn't an integer value, we know if we will
4230 // ever compare equal / not equal to it.
4231 if (!IsExact) {
4232 // TODO: Can never be -0.0 and other non-representable values
4233 APFloat RHSRoundInt(RHS);
4234 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4235 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4236 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004237 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004238
4239 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004240 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004241 }
4242 }
4243
4244 // TODO: If the constant is exactly representable, is it always OK to do
4245 // equality compares as integer?
4246 }
4247
Arch D. Robison8ed08542015-09-15 17:51:59 +00004248 // Check to see that the input is converted from an integer type that is small
4249 // enough that preserves all bits. TODO: check here for "known" sign bits.
4250 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4251 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004252
Arch D. Robison8ed08542015-09-15 17:51:59 +00004253 // Following test does NOT adjust InputSize downwards for signed inputs,
4254 // because the most negative value still requires all the mantissa bits
4255 // to distinguish it from one less than that value.
4256 if ((int)InputSize > MantissaWidth) {
4257 // Conversion would lose accuracy. Check if loss can impact comparison.
4258 int Exp = ilogb(RHS);
4259 if (Exp == APFloat::IEK_Inf) {
4260 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
4261 if (MaxExponent < (int)InputSize - !LHSUnsigned)
4262 // Conversion could create infinity.
4263 return nullptr;
4264 } else {
4265 // Note that if RHS is zero or NaN, then Exp is negative
4266 // and first condition is trivially false.
4267 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
4268 // Conversion could affect comparison.
4269 return nullptr;
4270 }
4271 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004272
Chris Lattner2188e402010-01-04 07:37:31 +00004273 // Otherwise, we can potentially simplify the comparison. We know that it
4274 // will always come through as an integer value and we know the constant is
4275 // not a NAN (it would have been previously simplified).
4276 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004277
Chris Lattner2188e402010-01-04 07:37:31 +00004278 ICmpInst::Predicate Pred;
4279 switch (I.getPredicate()) {
4280 default: llvm_unreachable("Unexpected predicate!");
4281 case FCmpInst::FCMP_UEQ:
4282 case FCmpInst::FCMP_OEQ:
4283 Pred = ICmpInst::ICMP_EQ;
4284 break;
4285 case FCmpInst::FCMP_UGT:
4286 case FCmpInst::FCMP_OGT:
4287 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4288 break;
4289 case FCmpInst::FCMP_UGE:
4290 case FCmpInst::FCMP_OGE:
4291 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4292 break;
4293 case FCmpInst::FCMP_ULT:
4294 case FCmpInst::FCMP_OLT:
4295 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4296 break;
4297 case FCmpInst::FCMP_ULE:
4298 case FCmpInst::FCMP_OLE:
4299 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4300 break;
4301 case FCmpInst::FCMP_UNE:
4302 case FCmpInst::FCMP_ONE:
4303 Pred = ICmpInst::ICMP_NE;
4304 break;
4305 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004306 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004307 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004308 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004309 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004310
Chris Lattner2188e402010-01-04 07:37:31 +00004311 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004312
Chris Lattner2188e402010-01-04 07:37:31 +00004313 // See if the FP constant is too large for the integer. For example,
4314 // comparing an i8 to 300.0.
4315 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004316
Chris Lattner2188e402010-01-04 07:37:31 +00004317 if (!LHSUnsigned) {
4318 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4319 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004320 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004321 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4322 APFloat::rmNearestTiesToEven);
4323 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4324 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4325 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004326 return replaceInstUsesWith(I, Builder->getTrue());
4327 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004328 }
4329 } else {
4330 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4331 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004332 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004333 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4334 APFloat::rmNearestTiesToEven);
4335 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4336 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4337 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004338 return replaceInstUsesWith(I, Builder->getTrue());
4339 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004340 }
4341 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004342
Chris Lattner2188e402010-01-04 07:37:31 +00004343 if (!LHSUnsigned) {
4344 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004345 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004346 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4347 APFloat::rmNearestTiesToEven);
4348 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4349 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4350 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004351 return replaceInstUsesWith(I, Builder->getTrue());
4352 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004353 }
Devang Patel698452b2012-02-13 23:05:18 +00004354 } else {
4355 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004356 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004357 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4358 APFloat::rmNearestTiesToEven);
4359 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4360 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4361 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004362 return replaceInstUsesWith(I, Builder->getTrue());
4363 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004364 }
Chris Lattner2188e402010-01-04 07:37:31 +00004365 }
4366
4367 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4368 // [0, UMAX], but it may still be fractional. See if it is fractional by
4369 // casting the FP value to the integer value and back, checking for equality.
4370 // Don't do this for zero, because -0.0 is not fractional.
4371 Constant *RHSInt = LHSUnsigned
4372 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4373 : ConstantExpr::getFPToSI(RHSC, IntTy);
4374 if (!RHS.isZero()) {
4375 bool Equal = LHSUnsigned
4376 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4377 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4378 if (!Equal) {
4379 // If we had a comparison against a fractional value, we have to adjust
4380 // the compare predicate and sometimes the value. RHSC is rounded towards
4381 // zero at this point.
4382 switch (Pred) {
4383 default: llvm_unreachable("Unexpected integer comparison!");
4384 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004385 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004386 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004387 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004388 case ICmpInst::ICMP_ULE:
4389 // (float)int <= 4.4 --> int <= 4
4390 // (float)int <= -4.4 --> false
4391 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004392 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004393 break;
4394 case ICmpInst::ICMP_SLE:
4395 // (float)int <= 4.4 --> int <= 4
4396 // (float)int <= -4.4 --> int < -4
4397 if (RHS.isNegative())
4398 Pred = ICmpInst::ICMP_SLT;
4399 break;
4400 case ICmpInst::ICMP_ULT:
4401 // (float)int < -4.4 --> false
4402 // (float)int < 4.4 --> int <= 4
4403 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004404 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004405 Pred = ICmpInst::ICMP_ULE;
4406 break;
4407 case ICmpInst::ICMP_SLT:
4408 // (float)int < -4.4 --> int < -4
4409 // (float)int < 4.4 --> int <= 4
4410 if (!RHS.isNegative())
4411 Pred = ICmpInst::ICMP_SLE;
4412 break;
4413 case ICmpInst::ICMP_UGT:
4414 // (float)int > 4.4 --> int > 4
4415 // (float)int > -4.4 --> true
4416 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004417 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004418 break;
4419 case ICmpInst::ICMP_SGT:
4420 // (float)int > 4.4 --> int > 4
4421 // (float)int > -4.4 --> int >= -4
4422 if (RHS.isNegative())
4423 Pred = ICmpInst::ICMP_SGE;
4424 break;
4425 case ICmpInst::ICMP_UGE:
4426 // (float)int >= -4.4 --> true
4427 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004428 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004429 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004430 Pred = ICmpInst::ICMP_UGT;
4431 break;
4432 case ICmpInst::ICMP_SGE:
4433 // (float)int >= -4.4 --> int >= -4
4434 // (float)int >= 4.4 --> int > 4
4435 if (!RHS.isNegative())
4436 Pred = ICmpInst::ICMP_SGT;
4437 break;
4438 }
4439 }
4440 }
4441
4442 // Lower this FP comparison into an appropriate integer version of the
4443 // comparison.
4444 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4445}
4446
4447Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4448 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004449
Chris Lattner2188e402010-01-04 07:37:31 +00004450 /// Orders the operands of the compare so that they are listed from most
4451 /// complex to least complex. This puts constants before unary operators,
4452 /// before binary operators.
4453 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4454 I.swapOperands();
4455 Changed = true;
4456 }
4457
4458 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004459
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004460 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
4461 I.getFastMathFlags(), DL, TLI, DT, AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004462 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004463
4464 // Simplify 'fcmp pred X, X'
4465 if (Op0 == Op1) {
4466 switch (I.getPredicate()) {
4467 default: llvm_unreachable("Unknown predicate!");
4468 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4469 case FCmpInst::FCMP_ULT: // True if unordered or less than
4470 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4471 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4472 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4473 I.setPredicate(FCmpInst::FCMP_UNO);
4474 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4475 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004476
Chris Lattner2188e402010-01-04 07:37:31 +00004477 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4478 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4479 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4480 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4481 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4482 I.setPredicate(FCmpInst::FCMP_ORD);
4483 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4484 return &I;
4485 }
4486 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004487
James Molloy2b21a7c2015-05-20 18:41:25 +00004488 // Test if the FCmpInst instruction is used exclusively by a select as
4489 // part of a minimum or maximum operation. If so, refrain from doing
4490 // any other folding. This helps out other analyses which understand
4491 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4492 // and CodeGen. And in this case, at least one of the comparison
4493 // operands has at least one user besides the compare (the select),
4494 // which would often largely negate the benefit of folding anyway.
4495 if (I.hasOneUse())
4496 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4497 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4498 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4499 return nullptr;
4500
Chris Lattner2188e402010-01-04 07:37:31 +00004501 // Handle fcmp with constant RHS
4502 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4503 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4504 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004505 case Instruction::FPExt: {
4506 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4507 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4508 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4509 if (!RHSF)
4510 break;
4511
4512 const fltSemantics *Sem;
4513 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004514 if (LHSExt->getSrcTy()->isHalfTy())
4515 Sem = &APFloat::IEEEhalf;
4516 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004517 Sem = &APFloat::IEEEsingle;
4518 else if (LHSExt->getSrcTy()->isDoubleTy())
4519 Sem = &APFloat::IEEEdouble;
4520 else if (LHSExt->getSrcTy()->isFP128Ty())
4521 Sem = &APFloat::IEEEquad;
4522 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4523 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004524 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4525 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004526 else
4527 break;
4528
4529 bool Lossy;
4530 APFloat F = RHSF->getValueAPF();
4531 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4532
Jim Grosbach24ff8342011-09-30 18:45:50 +00004533 // Avoid lossy conversions and denormals. Zero is a special case
4534 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004535 APFloat Fabs = F;
4536 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004537 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004538 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4539 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004540
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004541 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4542 ConstantFP::get(RHSC->getContext(), F));
4543 break;
4544 }
Chris Lattner2188e402010-01-04 07:37:31 +00004545 case Instruction::PHI:
4546 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4547 // block. If in the same block, we're encouraging jump threading. If
4548 // not, we are just pessimizing the code by making an i1 phi.
4549 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004550 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004551 return NV;
4552 break;
4553 case Instruction::SIToFP:
4554 case Instruction::UIToFP:
4555 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
4556 return NV;
4557 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004558 case Instruction::FSub: {
4559 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4560 Value *Op;
4561 if (match(LHSI, m_FNeg(m_Value(Op))))
4562 return new FCmpInst(I.getSwappedPredicate(), Op,
4563 ConstantExpr::getFNeg(RHSC));
4564 break;
4565 }
Dan Gohman94732022010-02-24 06:46:09 +00004566 case Instruction::Load:
4567 if (GetElementPtrInst *GEP =
4568 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4569 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4570 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4571 !cast<LoadInst>(LHSI)->isVolatile())
4572 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
4573 return Res;
4574 }
4575 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004576 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004577 if (!RHSC->isNullValue())
4578 break;
4579
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004580 CallInst *CI = cast<CallInst>(LHSI);
David Majnemerb4b27232016-04-19 19:10:21 +00004581 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004582 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004583 break;
4584
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004585 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004586 switch (I.getPredicate()) {
4587 default:
4588 break;
4589 // fabs(x) < 0 --> false
4590 case FCmpInst::FCMP_OLT:
4591 llvm_unreachable("handled by SimplifyFCmpInst");
4592 // fabs(x) > 0 --> x != 0
4593 case FCmpInst::FCMP_OGT:
4594 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4595 // fabs(x) <= 0 --> x == 0
4596 case FCmpInst::FCMP_OLE:
4597 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4598 // fabs(x) >= 0 --> !isnan(x)
4599 case FCmpInst::FCMP_OGE:
4600 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4601 // fabs(x) == 0 --> x == 0
4602 // fabs(x) != 0 --> x != 0
4603 case FCmpInst::FCMP_OEQ:
4604 case FCmpInst::FCMP_UEQ:
4605 case FCmpInst::FCMP_ONE:
4606 case FCmpInst::FCMP_UNE:
4607 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004608 }
4609 }
Chris Lattner2188e402010-01-04 07:37:31 +00004610 }
Chris Lattner2188e402010-01-04 07:37:31 +00004611 }
4612
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004613 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004614 Value *X, *Y;
4615 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004616 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004617
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004618 // fcmp (fpext x), (fpext y) -> fcmp x, y
4619 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4620 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4621 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4622 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4623 RHSExt->getOperand(0));
4624
Craig Topperf40110f2014-04-25 05:29:35 +00004625 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004626}