blob: 381a687aca10400434e900edac4b4e73e51dc762 [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
14#include "InstCombine.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000015#include "llvm/ADT/Statistic.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000016#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000017#include "llvm/Analysis/InstructionSimplify.h"
18#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000019#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000021#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000023#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000024#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Target/TargetLibraryInfo.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000027
Chris Lattner2188e402010-01-04 07:37:31 +000028using namespace llvm;
29using namespace PatternMatch;
30
Chandler Carruth964daaa2014-04-22 02:55:47 +000031#define DEBUG_TYPE "instcombine"
32
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000033// How many times is a select replaced by one of its operands?
34STATISTIC(NumSel, "Number of select opts");
35
36// Initialization Routines
37
Chris Lattner98457102011-02-10 05:23:05 +000038static ConstantInt *getOne(Constant *C) {
39 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
40}
41
Chris Lattner2188e402010-01-04 07:37:31 +000042static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
43 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
44}
45
46static bool HasAddOverflow(ConstantInt *Result,
47 ConstantInt *In1, ConstantInt *In2,
48 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000049 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000050 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000051
52 if (In2->isNegative())
53 return Result->getValue().sgt(In1->getValue());
54 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000055}
56
57/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
58/// overflowed for this type.
59static bool AddWithOverflow(Constant *&Result, Constant *In1,
60 Constant *In2, bool IsSigned = false) {
61 Result = ConstantExpr::getAdd(In1, In2);
62
Chris Lattner229907c2011-07-18 04:54:35 +000063 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000064 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
65 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
66 if (HasAddOverflow(ExtractElement(Result, Idx),
67 ExtractElement(In1, Idx),
68 ExtractElement(In2, Idx),
69 IsSigned))
70 return true;
71 }
72 return false;
73 }
74
75 return HasAddOverflow(cast<ConstantInt>(Result),
76 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
77 IsSigned);
78}
79
80static bool HasSubOverflow(ConstantInt *Result,
81 ConstantInt *In1, ConstantInt *In2,
82 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000083 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000084 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000085
Chris Lattnerb1a15122011-07-15 06:08:15 +000086 if (In2->isNegative())
87 return Result->getValue().slt(In1->getValue());
88
89 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000090}
91
92/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
93/// overflowed for this type.
94static bool SubWithOverflow(Constant *&Result, Constant *In1,
95 Constant *In2, bool IsSigned = false) {
96 Result = ConstantExpr::getSub(In1, In2);
97
Chris Lattner229907c2011-07-18 04:54:35 +000098 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000099 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
100 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
101 if (HasSubOverflow(ExtractElement(Result, Idx),
102 ExtractElement(In1, Idx),
103 ExtractElement(In2, Idx),
104 IsSigned))
105 return true;
106 }
107 return false;
108 }
109
110 return HasSubOverflow(cast<ConstantInt>(Result),
111 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
112 IsSigned);
113}
114
115/// isSignBitCheck - Given an exploded icmp instruction, return true if the
116/// comparison only checks the sign bit. If it only checks the sign bit, set
117/// TrueIfSigned if the result of the comparison is true when the input value is
118/// signed.
119static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
120 bool &TrueIfSigned) {
121 switch (pred) {
122 case ICmpInst::ICMP_SLT: // True if LHS s< 0
123 TrueIfSigned = true;
124 return RHS->isZero();
125 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
126 TrueIfSigned = true;
127 return RHS->isAllOnesValue();
128 case ICmpInst::ICMP_SGT: // True if LHS s> -1
129 TrueIfSigned = false;
130 return RHS->isAllOnesValue();
131 case ICmpInst::ICMP_UGT:
132 // True if LHS u> RHS and RHS == high-bit-mask - 1
133 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000134 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000135 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000136 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
137 TrueIfSigned = true;
138 return RHS->getValue().isSignBit();
139 default:
140 return false;
141 }
142}
143
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000144/// Returns true if the exploded icmp can be expressed as a signed comparison
145/// to zero and updates the predicate accordingly.
146/// The signedness of the comparison is preserved.
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000147static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
148 if (!ICmpInst::isSigned(pred))
149 return false;
150
151 if (RHS->isZero())
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000152 return ICmpInst::isRelational(pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000153
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000154 if (RHS->isOne()) {
155 if (pred == ICmpInst::ICMP_SLT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000156 pred = ICmpInst::ICMP_SLE;
157 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000158 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000159 } else if (RHS->isAllOnesValue()) {
160 if (pred == ICmpInst::ICMP_SGT) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000161 pred = ICmpInst::ICMP_SGE;
162 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000163 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000164 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000165
166 return false;
167}
168
Chris Lattner2188e402010-01-04 07:37:31 +0000169// isHighOnes - Return true if the constant is of the form 1+0+.
170// This is the same as lowones(~X).
171static bool isHighOnes(const ConstantInt *CI) {
172 return (~CI->getValue() + 1).isPowerOf2();
173}
174
Jim Grosbach129c52a2011-09-30 18:09:53 +0000175/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
Chris Lattner2188e402010-01-04 07:37:31 +0000176/// set of known zero and one bits, compute the maximum and minimum values that
177/// could have the specified known zero and known one bits, returning them in
178/// min/max.
179static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
180 const APInt& KnownOne,
181 APInt& Min, APInt& Max) {
182 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
183 KnownZero.getBitWidth() == Min.getBitWidth() &&
184 KnownZero.getBitWidth() == Max.getBitWidth() &&
185 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
186 APInt UnknownBits = ~(KnownZero|KnownOne);
187
188 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
189 // bit if it is unknown.
190 Min = KnownOne;
191 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000192
Chris Lattner2188e402010-01-04 07:37:31 +0000193 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000194 Min.setBit(Min.getBitWidth()-1);
195 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000196 }
197}
198
199// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
200// a set of known zero and one bits, compute the maximum and minimum values that
201// could have the specified known zero and known one bits, returning them in
202// min/max.
203static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
204 const APInt &KnownOne,
205 APInt &Min, APInt &Max) {
206 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
207 KnownZero.getBitWidth() == Min.getBitWidth() &&
208 KnownZero.getBitWidth() == Max.getBitWidth() &&
209 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
210 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000211
Chris Lattner2188e402010-01-04 07:37:31 +0000212 // The minimum value is when the unknown bits are all zeros.
213 Min = KnownOne;
214 // The maximum value is when the unknown bits are all ones.
215 Max = KnownOne|UnknownBits;
216}
217
218
219
220/// 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) {
Matt Arsenault5aeae182013-08-19 21:40:31 +0000231 // We need TD information to know the pointer size unless this is inbounds.
Craig Topperf40110f2014-04-25 05:29:35 +0000232 if (!GEP->isInBounds() && !DL)
233 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000234
Chris Lattnerfe741762012-01-31 02:55:06 +0000235 Constant *Init = GV->getInitializer();
236 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000237 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000238
Chris Lattnerfe741762012-01-31 02:55:06 +0000239 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000240 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000241
Chris Lattner2188e402010-01-04 07:37:31 +0000242 // There are many forms of this optimization we can handle, for now, just do
243 // the simple index into a single-dimensional array.
244 //
245 // Require: GEP GV, 0, i {{, constant indices}}
246 if (GEP->getNumOperands() < 3 ||
247 !isa<ConstantInt>(GEP->getOperand(1)) ||
248 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
249 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000250 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000251
252 // Check that indices after the variable are constants and in-range for the
253 // type they index. Collect the indices. This is typically for arrays of
254 // structs.
255 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000256
Chris Lattnerfe741762012-01-31 02:55:06 +0000257 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000258 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
259 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000260 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000261
Chris Lattner2188e402010-01-04 07:37:31 +0000262 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000263 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000264
Chris Lattner229907c2011-07-18 04:54:35 +0000265 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000266 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000267 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000268 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000269 EltTy = ATy->getElementType();
270 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000271 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000272 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000273
Chris Lattner2188e402010-01-04 07:37:31 +0000274 LaterIndices.push_back(IdxVal);
275 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000276
Chris Lattner2188e402010-01-04 07:37:31 +0000277 enum { Overdefined = -3, Undefined = -2 };
278
279 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000280
Chris Lattner2188e402010-01-04 07:37:31 +0000281 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
282 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
283 // and 87 is the second (and last) index. FirstTrueElement is -2 when
284 // undefined, otherwise set to the first true element. SecondTrueElement is
285 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
286 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
287
288 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
289 // form "i != 47 & i != 87". Same state transitions as for true elements.
290 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000291
Chris Lattner2188e402010-01-04 07:37:31 +0000292 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
293 /// define a state machine that triggers for ranges of values that the index
294 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
295 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
296 /// index in the range (inclusive). We use -2 for undefined here because we
297 /// use relative comparisons and don't want 0-1 to match -1.
298 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000299
Chris Lattner2188e402010-01-04 07:37:31 +0000300 // MagicBitvector - This is a magic bitvector where we set a bit if the
301 // comparison is true for element 'i'. If there are 64 elements or less in
302 // the array, this will fully represent all the comparison results.
303 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000304
305
Chris Lattner2188e402010-01-04 07:37:31 +0000306 // Scan the array and see if one of our patterns matches.
307 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000308 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
309 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000310 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000311
Chris Lattner2188e402010-01-04 07:37:31 +0000312 // If this is indexing an array of structures, get the structure element.
313 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000314 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000315
Chris Lattner2188e402010-01-04 07:37:31 +0000316 // If the element is masked, handle it.
317 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000318
Chris Lattner2188e402010-01-04 07:37:31 +0000319 // Find out if the comparison would be true or false for the i'th element.
320 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000321 CompareRHS, DL, TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000322 // If the result is undef for this element, ignore it.
323 if (isa<UndefValue>(C)) {
324 // Extend range state machines to cover this element in case there is an
325 // undef in the middle of the range.
326 if (TrueRangeEnd == (int)i-1)
327 TrueRangeEnd = i;
328 if (FalseRangeEnd == (int)i-1)
329 FalseRangeEnd = i;
330 continue;
331 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000332
Chris Lattner2188e402010-01-04 07:37:31 +0000333 // If we can't compute the result for any of the elements, we have to give
334 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000335 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000336
Chris Lattner2188e402010-01-04 07:37:31 +0000337 // Otherwise, we know if the comparison is true or false for this element,
338 // update our state machines.
339 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000340
Chris Lattner2188e402010-01-04 07:37:31 +0000341 // State machine for single/double/range index comparison.
342 if (IsTrueForElt) {
343 // Update the TrueElement state machine.
344 if (FirstTrueElement == Undefined)
345 FirstTrueElement = TrueRangeEnd = i; // First true element.
346 else {
347 // Update double-compare state machine.
348 if (SecondTrueElement == Undefined)
349 SecondTrueElement = i;
350 else
351 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000352
Chris Lattner2188e402010-01-04 07:37:31 +0000353 // Update range state machine.
354 if (TrueRangeEnd == (int)i-1)
355 TrueRangeEnd = i;
356 else
357 TrueRangeEnd = Overdefined;
358 }
359 } else {
360 // Update the FalseElement state machine.
361 if (FirstFalseElement == Undefined)
362 FirstFalseElement = FalseRangeEnd = i; // First false element.
363 else {
364 // Update double-compare state machine.
365 if (SecondFalseElement == Undefined)
366 SecondFalseElement = i;
367 else
368 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000369
Chris Lattner2188e402010-01-04 07:37:31 +0000370 // Update range state machine.
371 if (FalseRangeEnd == (int)i-1)
372 FalseRangeEnd = i;
373 else
374 FalseRangeEnd = Overdefined;
375 }
376 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000377
378
Chris Lattner2188e402010-01-04 07:37:31 +0000379 // If this element is in range, update our magic bitvector.
380 if (i < 64 && IsTrueForElt)
381 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000382
Chris Lattner2188e402010-01-04 07:37:31 +0000383 // If all of our states become overdefined, bail out early. Since the
384 // predicate is expensive, only check it every 8 elements. This is only
385 // really useful for really huge arrays.
386 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
387 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
388 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000389 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000390 }
391
392 // Now that we've scanned the entire array, emit our new comparison(s). We
393 // order the state machines in complexity of the generated code.
394 Value *Idx = GEP->getOperand(2);
395
Matt Arsenault5aeae182013-08-19 21:40:31 +0000396 // If the index is larger than the pointer size of the target, truncate the
397 // index down like the GEP would do implicitly. We don't have to do this for
398 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000399 if (!GEP->isInBounds()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000400 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000401 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
402 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
403 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
404 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000405
Chris Lattner2188e402010-01-04 07:37:31 +0000406 // If the comparison is only true for one or two elements, emit direct
407 // comparisons.
408 if (SecondTrueElement != Overdefined) {
409 // None true -> false.
410 if (FirstTrueElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000411 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000412
Chris Lattner2188e402010-01-04 07:37:31 +0000413 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000414
Chris Lattner2188e402010-01-04 07:37:31 +0000415 // True for one element -> 'i == 47'.
416 if (SecondTrueElement == Undefined)
417 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000418
Chris Lattner2188e402010-01-04 07:37:31 +0000419 // True for two elements -> 'i == 47 | i == 72'.
420 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
421 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
422 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
423 return BinaryOperator::CreateOr(C1, C2);
424 }
425
426 // If the comparison is only false for one or two elements, emit direct
427 // comparisons.
428 if (SecondFalseElement != Overdefined) {
429 // None false -> true.
430 if (FirstFalseElement == Undefined)
Jakub Staszakbddea112013-06-06 20:18:46 +0000431 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000432
Chris Lattner2188e402010-01-04 07:37:31 +0000433 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
434
435 // False for one element -> 'i != 47'.
436 if (SecondFalseElement == Undefined)
437 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000438
Chris Lattner2188e402010-01-04 07:37:31 +0000439 // False for two elements -> 'i != 47 & i != 72'.
440 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
441 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
442 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
443 return BinaryOperator::CreateAnd(C1, C2);
444 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000445
Chris Lattner2188e402010-01-04 07:37:31 +0000446 // If the comparison can be replaced with a range comparison for the elements
447 // where it is true, emit the range check.
448 if (TrueRangeEnd != Overdefined) {
449 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000450
Chris Lattner2188e402010-01-04 07:37:31 +0000451 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
452 if (FirstTrueElement) {
453 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
454 Idx = Builder->CreateAdd(Idx, Offs);
455 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000456
Chris Lattner2188e402010-01-04 07:37:31 +0000457 Value *End = ConstantInt::get(Idx->getType(),
458 TrueRangeEnd-FirstTrueElement+1);
459 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
460 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000461
Chris Lattner2188e402010-01-04 07:37:31 +0000462 // False range check.
463 if (FalseRangeEnd != Overdefined) {
464 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
465 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
466 if (FirstFalseElement) {
467 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
468 Idx = Builder->CreateAdd(Idx, Offs);
469 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000470
Chris Lattner2188e402010-01-04 07:37:31 +0000471 Value *End = ConstantInt::get(Idx->getType(),
472 FalseRangeEnd-FirstFalseElement);
473 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
474 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000475
476
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000477 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000478 // of this load, replace it with computation that does:
479 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000480 {
Craig Topperf40110f2014-04-25 05:29:35 +0000481 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000482
483 // Look for an appropriate type:
484 // - The type of Idx if the magic fits
485 // - The smallest fitting legal type if we have a DataLayout
486 // - Default to i32
487 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
488 Ty = Idx->getType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000489 else if (DL)
490 Ty = DL->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000491 else if (ArrayElementCount <= 32)
Chris Lattner2188e402010-01-04 07:37:31 +0000492 Ty = Type::getInt32Ty(Init->getContext());
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000493
Craig Topperf40110f2014-04-25 05:29:35 +0000494 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000495 Value *V = Builder->CreateIntCast(Idx, Ty, false);
496 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
497 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
498 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
499 }
Chris Lattner2188e402010-01-04 07:37:31 +0000500 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000501
Craig Topperf40110f2014-04-25 05:29:35 +0000502 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000503}
504
505
506/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
507/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
508/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
509/// be complex, and scales are involved. The above expression would also be
510/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
511/// This later form is less amenable to optimization though, and we are allowed
512/// to generate the first by knowing that pointer arithmetic doesn't overflow.
513///
514/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000515///
Eli Friedman1754a252011-05-18 23:11:30 +0000516static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000517 const DataLayout &DL = *IC.getDataLayout();
Chris Lattner2188e402010-01-04 07:37:31 +0000518 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000519
Chris Lattner2188e402010-01-04 07:37:31 +0000520 // Check to see if this gep only has a single variable index. If so, and if
521 // any constant indices are a multiple of its scale, then we can compute this
522 // in terms of the scale of the variable index. For example, if the GEP
523 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
524 // because the expression will cross zero at the same point.
525 unsigned i, e = GEP->getNumOperands();
526 int64_t Offset = 0;
527 for (i = 1; i != e; ++i, ++GTI) {
528 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
529 // Compute the aggregate offset of constant indices.
530 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000531
Chris Lattner2188e402010-01-04 07:37:31 +0000532 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000533 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000534 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000535 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000536 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000537 Offset += Size*CI->getSExtValue();
538 }
539 } else {
540 // Found our variable index.
541 break;
542 }
543 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000544
Chris Lattner2188e402010-01-04 07:37:31 +0000545 // If there are no variable indices, we must have a constant offset, just
546 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000547 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000548
Chris Lattner2188e402010-01-04 07:37:31 +0000549 Value *VariableIdx = GEP->getOperand(i);
550 // Determine the scale factor of the variable element. For example, this is
551 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000552 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000553
Chris Lattner2188e402010-01-04 07:37:31 +0000554 // Verify that there are no other variable indices. If so, emit the hard way.
555 for (++i, ++GTI; i != e; ++i, ++GTI) {
556 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000557 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000558
Chris Lattner2188e402010-01-04 07:37:31 +0000559 // Compute the aggregate offset of constant indices.
560 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000561
Chris Lattner2188e402010-01-04 07:37:31 +0000562 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000563 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000564 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000565 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000566 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000567 Offset += Size*CI->getSExtValue();
568 }
569 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000570
Matt Arsenault745101d2013-08-21 19:53:10 +0000571
572
Chris Lattner2188e402010-01-04 07:37:31 +0000573 // Okay, we know we have a single variable index, which must be a
574 // pointer/array/vector index. If there is no offset, life is simple, return
575 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000576 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000577 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000578 if (Offset == 0) {
579 // Cast to intptrty in case a truncation occurs. If an extension is needed,
580 // we don't need to bother extending: the extension won't affect where the
581 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000582 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000583 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
584 }
Chris Lattner2188e402010-01-04 07:37:31 +0000585 return VariableIdx;
586 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000587
Chris Lattner2188e402010-01-04 07:37:31 +0000588 // Otherwise, there is an index. The computation we will do will be modulo
589 // the pointer size, so get it.
590 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000591
Chris Lattner2188e402010-01-04 07:37:31 +0000592 Offset &= PtrSizeMask;
593 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000594
Chris Lattner2188e402010-01-04 07:37:31 +0000595 // To do this transformation, any constant index must be a multiple of the
596 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
597 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
598 // multiple of the variable scale.
599 int64_t NewOffs = Offset / (int64_t)VariableScale;
600 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000601 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000602
Chris Lattner2188e402010-01-04 07:37:31 +0000603 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000604 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000605 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
606 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000607 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000608 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000609}
610
611/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
612/// else. At this point we know that the GEP is on the LHS of the comparison.
613Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
614 ICmpInst::Predicate Cond,
615 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000616 // Don't transform signed compares of GEPs into index compares. Even if the
617 // GEP is inbounds, the final add of the base pointer can have signed overflow
618 // and would change the result of the icmp.
619 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000620 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000621 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000622 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000623
Matt Arsenault44f60d02014-06-09 19:20:29 +0000624 // Look through bitcasts and addrspacecasts. We do not however want to remove
625 // 0 GEPs.
626 if (!isa<GetElementPtrInst>(RHS))
627 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000628
629 Value *PtrBase = GEPLHS->getOperand(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000630 if (DL && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000631 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
632 // This transformation (ignoring the base and scales) is valid because we
633 // know pointers can't overflow since the gep is inbounds. See if we can
634 // output an optimized form.
Eli Friedman1754a252011-05-18 23:11:30 +0000635 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000636
Chris Lattner2188e402010-01-04 07:37:31 +0000637 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000638 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000639 Offset = EmitGEPOffset(GEPLHS);
640 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
641 Constant::getNullValue(Offset->getType()));
642 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
643 // If the base pointers are different, but the indices are the same, just
644 // compare the base pointer.
645 if (PtrBase != GEPRHS->getOperand(0)) {
646 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
647 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
648 GEPRHS->getOperand(0)->getType();
649 if (IndicesTheSame)
650 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
651 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
652 IndicesTheSame = false;
653 break;
654 }
655
656 // If all indices are the same, just compare the base pointers.
657 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000658 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000659
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000660 // If we're comparing GEPs with two base pointers that only differ in type
661 // and both GEPs have only constant indices or just one use, then fold
662 // the compare with the adjusted indices.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000663 if (DL && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000664 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
665 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
666 PtrBase->stripPointerCasts() ==
667 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000668 Value *LOffset = EmitGEPOffset(GEPLHS);
669 Value *ROffset = EmitGEPOffset(GEPRHS);
670
671 // If we looked through an addrspacecast between different sized address
672 // spaces, the LHS and RHS pointers are different sized
673 // integers. Truncate to the smaller one.
674 Type *LHSIndexTy = LOffset->getType();
675 Type *RHSIndexTy = ROffset->getType();
676 if (LHSIndexTy != RHSIndexTy) {
677 if (LHSIndexTy->getPrimitiveSizeInBits() <
678 RHSIndexTy->getPrimitiveSizeInBits()) {
679 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
680 } else
681 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
682 }
683
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000684 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000685 LOffset, ROffset);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000686 return ReplaceInstUsesWith(I, Cmp);
687 }
688
Chris Lattner2188e402010-01-04 07:37:31 +0000689 // Otherwise, the base pointers are different and the indices are
690 // different, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000691 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000692 }
693
694 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000695 if (GEPLHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +0000696 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +0000697 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +0000698
699 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000700 if (GEPRHS->hasAllZeroIndices())
Chris Lattner2188e402010-01-04 07:37:31 +0000701 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
702
Stuart Hastings66a82b92011-05-14 05:55:10 +0000703 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +0000704 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
705 // If the GEPs only differ by one index, compare it.
706 unsigned NumDifferences = 0; // Keep track of # differences.
707 unsigned DiffOperand = 0; // The operand that differs.
708 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
709 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
710 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
711 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
712 // Irreconcilable differences.
713 NumDifferences = 2;
714 break;
715 } else {
716 if (NumDifferences++) break;
717 DiffOperand = i;
718 }
719 }
720
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +0000721 if (NumDifferences == 0) // SAME GEP?
722 return ReplaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +0000723 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +0000724
Stuart Hastings66a82b92011-05-14 05:55:10 +0000725 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +0000726 Value *LHSV = GEPLHS->getOperand(DiffOperand);
727 Value *RHSV = GEPRHS->getOperand(DiffOperand);
728 // Make sure we do a signed comparison here.
729 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
730 }
731 }
732
733 // Only lower this if the icmp is the only user of the GEP or if we expect
734 // the result to fold to a constant!
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000735 if (DL &&
Stuart Hastings66a82b92011-05-14 05:55:10 +0000736 GEPsInBounds &&
Chris Lattner2188e402010-01-04 07:37:31 +0000737 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
738 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
739 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
740 Value *L = EmitGEPOffset(GEPLHS);
741 Value *R = EmitGEPOffset(GEPRHS);
742 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
743 }
744 }
Craig Topperf40110f2014-04-25 05:29:35 +0000745 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000746}
747
748/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000749Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
Chris Lattner2188e402010-01-04 07:37:31 +0000750 Value *X, ConstantInt *CI,
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000751 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000752 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000753 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +0000754 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000755
Chris Lattner8c92b572010-01-08 17:48:19 +0000756 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +0000757 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
758 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
759 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +0000760 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +0000761 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +0000762 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
763 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000764
Chris Lattner2188e402010-01-04 07:37:31 +0000765 // (X+1) >u X --> X <u (0-1) --> X != 255
766 // (X+2) >u X --> X <u (0-2) --> X <u 254
767 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +0000768 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +0000769 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000770
Chris Lattner2188e402010-01-04 07:37:31 +0000771 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
772 ConstantInt *SMax = ConstantInt::get(X->getContext(),
773 APInt::getSignedMaxValue(BitWidth));
774
775 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
776 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
777 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
778 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
779 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
780 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +0000781 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +0000782 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000783
Chris Lattner2188e402010-01-04 07:37:31 +0000784 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
785 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
786 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
787 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
788 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
789 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +0000790
Chris Lattner2188e402010-01-04 07:37:31 +0000791 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +0000792 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000793 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
794}
795
796/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
797/// and CmpRHS are both known to be integer constants.
798Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
799 ConstantInt *DivRHS) {
800 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
801 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000802
803 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +0000804 // then don't attempt this transform. The code below doesn't have the
805 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +0000806 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +0000807 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +0000808 // (x /u C1) <u C2. Simply casting the operands and result won't
809 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +0000810 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +0000811 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
812 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +0000813 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000814 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000815 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +0000816 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +0000817 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +0000818 if (DivRHS->isOne()) {
819 // This eliminates some funny cases with INT_MIN.
820 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
821 return &ICI;
822 }
Chris Lattner2188e402010-01-04 07:37:31 +0000823
824 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +0000825 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
826 // C2 (CI). By solving for X we can turn this into a range check
827 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +0000828 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
829
830 // Determine if the product overflows by seeing if the product is
831 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +0000832 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +0000833 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
834 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
835
836 // Get the ICmp opcode
837 ICmpInst::Predicate Pred = ICI.getPredicate();
838
Chris Lattner98457102011-02-10 05:23:05 +0000839 /// If the division is known to be exact, then there is no remainder from the
840 /// divide, so the covered range size is unit, otherwise it is the divisor.
841 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000842
Chris Lattner2188e402010-01-04 07:37:31 +0000843 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +0000844 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +0000845 // Compute this interval based on the constants involved and the signedness of
846 // the compare/divide. This computes a half-open interval, keeping track of
847 // whether either value in the interval overflows. After analysis each
848 // overflow variable is set to 0 if it's corresponding bound variable is valid
849 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
850 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000851 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +0000852
Chris Lattner2188e402010-01-04 07:37:31 +0000853 if (!DivIsSigned) { // udiv
854 // e.g. X/5 op 3 --> [15, 20)
855 LoBound = Prod;
856 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +0000857 if (!HiOverflow) {
858 // If this is not an exact divide, then many values in the range collapse
859 // to the same result value.
860 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
861 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000862
Chris Lattner2188e402010-01-04 07:37:31 +0000863 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
864 if (CmpRHSV == 0) { // (X / pos) op 0
865 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +0000866 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
867 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +0000868 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
869 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
870 HiOverflow = LoOverflow = ProdOV;
871 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000872 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000873 } else { // (X / pos) op neg
874 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
875 HiBound = AddOne(Prod);
876 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
877 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +0000878 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000879 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +0000880 }
Chris Lattner2188e402010-01-04 07:37:31 +0000881 }
Chris Lattnerb1a15122011-07-15 06:08:15 +0000882 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +0000883 if (DivI->isExact())
884 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000885 if (CmpRHSV == 0) { // (X / neg) op 0
886 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +0000887 LoBound = AddOne(RangeSize);
888 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +0000889 if (HiBound == DivRHS) { // -INTMIN = INTMIN
890 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +0000891 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +0000892 }
893 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
894 // e.g. X/-5 op 3 --> [-19, -14)
895 HiBound = AddOne(Prod);
896 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
897 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000898 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +0000899 } else { // (X / neg) op neg
900 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
901 LoOverflow = HiOverflow = ProdOV;
902 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +0000903 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +0000904 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000905
Chris Lattner2188e402010-01-04 07:37:31 +0000906 // Dividing by a negative swaps the condition. LT <-> GT
907 Pred = ICmpInst::getSwappedPredicate(Pred);
908 }
909
910 Value *X = DivI->getOperand(0);
911 switch (Pred) {
912 default: llvm_unreachable("Unhandled icmp opcode!");
913 case ICmpInst::ICMP_EQ:
914 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000915 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +0000916 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000917 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
918 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000919 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000920 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
921 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000922 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
923 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +0000924 case ICmpInst::ICMP_NE:
925 if (LoOverflow && HiOverflow)
Jakub Staszakbddea112013-06-06 20:18:46 +0000926 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +0000927 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000928 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
929 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000930 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +0000931 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
932 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner067459c2010-03-05 08:46:26 +0000933 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
934 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +0000935 case ICmpInst::ICMP_ULT:
936 case ICmpInst::ICMP_SLT:
937 if (LoOverflow == +1) // Low bound is greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000938 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000939 if (LoOverflow == -1) // Low bound is less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000940 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +0000941 return new ICmpInst(Pred, X, LoBound);
942 case ICmpInst::ICMP_UGT:
943 case ICmpInst::ICMP_SGT:
944 if (HiOverflow == +1) // High bound greater than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000945 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +0000946 if (HiOverflow == -1) // High bound less than input range.
Jakub Staszakbddea112013-06-06 20:18:46 +0000947 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +0000948 if (Pred == ICmpInst::ICMP_UGT)
949 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +0000950 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +0000951 }
952}
953
Chris Lattnerd369f572011-02-13 07:43:07 +0000954/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
955Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
956 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +0000957 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000958
Chris Lattnerd369f572011-02-13 07:43:07 +0000959 // Check that the shift amount is in range. If not, don't perform
960 // undefined shifts. When the shift is visited it will be
961 // simplified.
962 uint32_t TypeBits = CmpRHSV.getBitWidth();
963 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +0000964 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000965 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000966
Chris Lattner43273af2011-02-13 08:07:21 +0000967 if (!ICI.isEquality()) {
968 // If we have an unsigned comparison and an ashr, we can't simplify this.
969 // Similarly for signed comparisons with lshr.
970 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +0000971 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000972
Eli Friedman865866e2011-05-25 23:26:20 +0000973 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
974 // by a power of 2. Since we already have logic to simplify these,
975 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +0000976 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +0000977 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +0000978 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000979
Chris Lattner43273af2011-02-13 08:07:21 +0000980 // Revisit the shift (to delete it).
981 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000982
Chris Lattner43273af2011-02-13 08:07:21 +0000983 Constant *DivCst =
984 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +0000985
Chris Lattner43273af2011-02-13 08:07:21 +0000986 Value *Tmp =
987 Shr->getOpcode() == Instruction::AShr ?
988 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
989 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000990
Chris Lattner43273af2011-02-13 08:07:21 +0000991 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000992
Chris Lattner43273af2011-02-13 08:07:21 +0000993 // If the builder folded the binop, just return it.
994 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +0000995 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +0000996 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000997
Chris Lattner43273af2011-02-13 08:07:21 +0000998 // Otherwise, fold this div/compare.
999 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1000 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001001
Chris Lattner43273af2011-02-13 08:07:21 +00001002 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1003 assert(Res && "This div/cst should have folded!");
1004 return Res;
1005 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001006
1007
Chris Lattnerd369f572011-02-13 07:43:07 +00001008 // If we are comparing against bits always shifted out, the
1009 // comparison cannot succeed.
1010 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001011 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001012 if (Shr->getOpcode() == Instruction::LShr)
1013 Comp = Comp.lshr(ShAmtVal);
1014 else
1015 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001016
Chris Lattnerd369f572011-02-13 07:43:07 +00001017 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1018 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001019 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattnerd369f572011-02-13 07:43:07 +00001020 return ReplaceInstUsesWith(ICI, Cst);
1021 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001022
Chris Lattnerd369f572011-02-13 07:43:07 +00001023 // Otherwise, check to see if the bits shifted out are known to be zero.
1024 // If so, we can compare against the unshifted value:
1025 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001026 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001027 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001028
Chris Lattnerd369f572011-02-13 07:43:07 +00001029 if (Shr->hasOneUse()) {
1030 // Otherwise strength reduce the shift into an and.
1031 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001032 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001033
Chris Lattnerd369f572011-02-13 07:43:07 +00001034 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1035 Mask, Shr->getName()+".mask");
1036 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1037 }
Craig Topperf40110f2014-04-25 05:29:35 +00001038 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001039}
1040
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001041/// FoldICmpCstShrCst - Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
1042/// (icmp eq/ne A, Log2(const2/const1)) ->
1043/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
1044Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
1045 ConstantInt *CI1,
1046 ConstantInt *CI2) {
1047 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1048
1049 auto getConstant = [&I, this](bool IsTrue) {
1050 if (I.getPredicate() == I.ICMP_NE)
1051 IsTrue = !IsTrue;
1052 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
1053 };
1054
1055 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1056 if (I.getPredicate() == I.ICMP_NE)
1057 Pred = CmpInst::getInversePredicate(Pred);
1058 return new ICmpInst(Pred, LHS, RHS);
1059 };
1060
1061 APInt AP1 = CI1->getValue();
1062 APInt AP2 = CI2->getValue();
1063
David Majnemer2abb8182014-10-25 07:13:13 +00001064 // Don't bother doing any work for cases which InstSimplify handles.
1065 if (AP2 == 0)
1066 return nullptr;
1067 bool IsAShr = isa<AShrOperator>(Op);
1068 if (IsAShr) {
1069 if (AP2.isAllOnesValue())
1070 return nullptr;
1071 if (AP2.isNegative() != AP1.isNegative())
1072 return nullptr;
1073 if (AP2.sgt(AP1))
1074 return nullptr;
1075 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001076
David Majnemerd2056022014-10-21 19:51:55 +00001077 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001078 // 'A' must be large enough to shift out the highest set bit.
1079 return getICmp(I.ICMP_UGT, A,
1080 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001081
David Majnemerd2056022014-10-21 19:51:55 +00001082 if (AP1 == AP2)
1083 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001084
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001085 // Get the distance between the highest bit that's set.
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001086 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001087 // Both the constants are negative, take their positive to calculate log.
1088 if (IsAShr && AP1.isNegative())
Andrea Di Biagio458a6692014-10-09 12:41:49 +00001089 // Get the ones' complement of AP2 and AP1 when computing the distance.
1090 Shift = (~AP2).logBase2() - (~AP1).logBase2();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001091 else
1092 Shift = AP2.logBase2() - AP1.logBase2();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001093
David Majnemerd2056022014-10-21 19:51:55 +00001094 if (Shift > 0) {
1095 if (IsAShr ? AP1 == AP2.ashr(Shift) : AP1 == AP2.lshr(Shift))
1096 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1097 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001098 // Shifting const2 will never be equal to const1.
1099 return getConstant(false);
1100}
Chris Lattner2188e402010-01-04 07:37:31 +00001101
David Majnemer59939ac2014-10-19 08:23:08 +00001102/// FoldICmpCstShlCst - Handle "(icmp eq/ne (shl const2, A), const1)" ->
1103/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
1104Instruction *InstCombiner::FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
1105 ConstantInt *CI1,
1106 ConstantInt *CI2) {
1107 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1108
1109 auto getConstant = [&I, this](bool IsTrue) {
1110 if (I.getPredicate() == I.ICMP_NE)
1111 IsTrue = !IsTrue;
1112 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
1113 };
1114
1115 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1116 if (I.getPredicate() == I.ICMP_NE)
1117 Pred = CmpInst::getInversePredicate(Pred);
1118 return new ICmpInst(Pred, LHS, RHS);
1119 };
1120
1121 APInt AP1 = CI1->getValue();
1122 APInt AP2 = CI2->getValue();
1123
David Majnemer2abb8182014-10-25 07:13:13 +00001124 // Don't bother doing any work for cases which InstSimplify handles.
1125 if (AP2 == 0)
1126 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001127
1128 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1129
1130 if (!AP1 && AP2TrailingZeros != 0)
1131 return getICmp(I.ICMP_UGE, A,
1132 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1133
1134 if (AP1 == AP2)
1135 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1136
1137 // Get the distance between the lowest bits that are set.
1138 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1139
1140 if (Shift > 0 && AP2.shl(Shift) == AP1)
1141 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1142
1143 // Shifting const2 will never be equal to const1.
1144 return getConstant(false);
1145}
1146
Chris Lattner2188e402010-01-04 07:37:31 +00001147/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1148///
1149Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1150 Instruction *LHSI,
1151 ConstantInt *RHS) {
1152 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001153
Chris Lattner2188e402010-01-04 07:37:31 +00001154 switch (LHSI->getOpcode()) {
1155 case Instruction::Trunc:
1156 if (ICI.isEquality() && LHSI->hasOneUse()) {
1157 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1158 // of the high bits truncated out of x are known.
1159 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1160 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001161 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001162 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001163
Chris Lattner2188e402010-01-04 07:37:31 +00001164 // If all the high bits are known, we can do this xform.
1165 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1166 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001167 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001168 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001169 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001170 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001171 }
1172 }
1173 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001174
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001175 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1176 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001177 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1178 // fold the xor.
1179 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1180 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1181 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001182
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001183 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001184 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001185 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001186 ICI.setOperand(0, CompareVal);
1187 Worklist.Add(LHSI);
1188 return &ICI;
1189 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001190
Chris Lattner2188e402010-01-04 07:37:31 +00001191 // Was the old condition true if the operand is positive?
1192 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001193
Chris Lattner2188e402010-01-04 07:37:31 +00001194 // If so, the new one isn't.
1195 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001196
Chris Lattner2188e402010-01-04 07:37:31 +00001197 if (isTrueIfPositive)
1198 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1199 SubOne(RHS));
1200 else
1201 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1202 AddOne(RHS));
1203 }
1204
1205 if (LHSI->hasOneUse()) {
1206 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001207 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1208 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001209 ICmpInst::Predicate Pred = ICI.isSigned()
1210 ? ICI.getUnsignedPredicate()
1211 : ICI.getSignedPredicate();
1212 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001213 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001214 }
1215
1216 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001217 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1218 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001219 ICmpInst::Predicate Pred = ICI.isSigned()
1220 ? ICI.getUnsignedPredicate()
1221 : ICI.getSignedPredicate();
1222 Pred = ICI.getSwappedPredicate(Pred);
1223 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001224 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001225 }
1226 }
David Majnemer72d76272013-07-09 09:20:58 +00001227
1228 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1229 // iff -C is a power of 2
1230 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001231 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1232 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001233
1234 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1235 // iff -C is a power of 2
1236 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001237 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1238 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001239 }
1240 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001241 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001242 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1243 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001244 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001245
Chris Lattner2188e402010-01-04 07:37:31 +00001246 // If the LHS is an AND of a truncating cast, we can widen the
1247 // and/compare to be the input width without changing the value
1248 // produced, eliminating a cast.
1249 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1250 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001251 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001252 // Extending a relational comparison when we're checking the sign
1253 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001254 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001255 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001256 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001257 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001258 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001259 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001260 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001261 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001262 }
1263 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001264
1265 // If the LHS is an AND of a zext, and we have an equality compare, we can
1266 // shrink the and/compare to the smaller type, eliminating the cast.
1267 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001268 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001269 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1270 // should fold the icmp to true/false in that case.
1271 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1272 Value *NewAnd =
1273 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001274 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001275 NewAnd->takeName(LHSI);
1276 return new ICmpInst(ICI.getPredicate(), NewAnd,
1277 ConstantExpr::getTrunc(RHS, Ty));
1278 }
1279 }
1280
Chris Lattner2188e402010-01-04 07:37:31 +00001281 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1282 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1283 // happens a LOT in code produced by the C front-end, for bitfield
1284 // access.
1285 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1286 if (Shift && !Shift->isShift())
Craig Topperf40110f2014-04-25 05:29:35 +00001287 Shift = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001288
Chris Lattner2188e402010-01-04 07:37:31 +00001289 ConstantInt *ShAmt;
Craig Topperf40110f2014-04-25 05:29:35 +00001290 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001291
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001292 // This seemingly simple opportunity to fold away a shift turns out to
1293 // be rather complicated. See PR17827
1294 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001295 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001296 bool CanFold = false;
1297 unsigned ShiftOpcode = Shift->getOpcode();
1298 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001299 // There may be some constraints that make this possible,
1300 // but nothing simple has been discovered yet.
1301 CanFold = false;
1302 } else if (ShiftOpcode == Instruction::Shl) {
1303 // For a left shift, we can fold if the comparison is not signed.
1304 // We can also fold a signed comparison if the mask value and
1305 // comparison value are not negative. These constraints may not be
1306 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001307 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001308 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001309 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001310 } else if (ShiftOpcode == Instruction::LShr) {
1311 // For a logical right shift, we can fold if the comparison is not
1312 // signed. We can also fold a signed comparison if the shifted mask
1313 // value and the shifted comparison value are not negative.
1314 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001315 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001316 if (!ICI.isSigned())
1317 CanFold = true;
1318 else {
1319 ConstantInt *ShiftedAndCst =
1320 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1321 ConstantInt *ShiftedRHSCst =
1322 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1323
1324 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1325 CanFold = true;
1326 }
Chris Lattner2188e402010-01-04 07:37:31 +00001327 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001328
Chris Lattner2188e402010-01-04 07:37:31 +00001329 if (CanFold) {
1330 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001331 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001332 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1333 else
1334 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001335
Chris Lattner2188e402010-01-04 07:37:31 +00001336 // Check to see if we are shifting out any of the bits being
1337 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001338 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001339 // If we shifted bits out, the fold is not going to work out.
1340 // As a special case, check to see if this means that the
1341 // result is always true or false now.
1342 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Jakub Staszakbddea112013-06-06 20:18:46 +00001343 return ReplaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001344 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Jakub Staszakbddea112013-06-06 20:18:46 +00001345 return ReplaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001346 } else {
1347 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001348 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001349 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001350 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001351 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001352 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1353 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001354 LHSI->setOperand(0, Shift->getOperand(0));
1355 Worklist.Add(Shift); // Shift is dead.
1356 return &ICI;
1357 }
1358 }
1359 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001360
Chris Lattner2188e402010-01-04 07:37:31 +00001361 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1362 // preferable because it allows the C<<Y expression to be hoisted out
1363 // of a loop if Y is invariant and X is not.
1364 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1365 ICI.isEquality() && !Shift->isArithmeticShift() &&
1366 !isa<Constant>(Shift->getOperand(0))) {
1367 // Compute C << Y.
1368 Value *NS;
1369 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001370 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001371 } else {
1372 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001373 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001374 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001375
Chris Lattner2188e402010-01-04 07:37:31 +00001376 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001377 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001378 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001379
Chris Lattner2188e402010-01-04 07:37:31 +00001380 ICI.setOperand(0, NewAnd);
1381 return &ICI;
1382 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001383
David Majnemer0ffccf72014-08-24 09:10:57 +00001384 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1385 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1386 //
1387 // iff pred isn't signed
1388 {
1389 Value *X, *Y, *LShr;
1390 if (!ICI.isSigned() && RHSV == 0) {
1391 if (match(LHSI->getOperand(1), m_One())) {
1392 Constant *One = cast<Constant>(LHSI->getOperand(1));
1393 Value *Or = LHSI->getOperand(0);
1394 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1395 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1396 unsigned UsesRemoved = 0;
1397 if (LHSI->hasOneUse())
1398 ++UsesRemoved;
1399 if (Or->hasOneUse())
1400 ++UsesRemoved;
1401 if (LShr->hasOneUse())
1402 ++UsesRemoved;
1403 Value *NewOr = nullptr;
1404 // Compute X & ((1 << Y) | 1)
1405 if (auto *C = dyn_cast<Constant>(Y)) {
1406 if (UsesRemoved >= 1)
1407 NewOr =
1408 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1409 } else {
1410 if (UsesRemoved >= 3)
1411 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1412 LShr->getName(),
1413 /*HasNUW=*/true),
1414 One, Or->getName());
1415 }
1416 if (NewOr) {
1417 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1418 ICI.setOperand(0, NewAnd);
1419 return &ICI;
1420 }
1421 }
1422 }
1423 }
1424 }
1425
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001426 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1427 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001428 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001429 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1430 if ((NTZ < AndCst->getBitWidth()) &&
1431 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001432 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1433 Constant::getNullValue(RHS->getType()));
1434 }
Chris Lattner2188e402010-01-04 07:37:31 +00001435 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001436
Chris Lattner2188e402010-01-04 07:37:31 +00001437 // Try to optimize things like "A[i]&42 == 0" to index computations.
1438 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1439 if (GetElementPtrInst *GEP =
1440 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1441 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1442 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1443 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1444 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1445 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1446 return Res;
1447 }
1448 }
David Majnemer414d4e52013-07-09 08:09:32 +00001449
1450 // X & -C == -C -> X > u ~C
1451 // X & -C != -C -> X <= u ~C
1452 // iff C is a power of 2
1453 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1454 return new ICmpInst(
1455 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1456 : ICmpInst::ICMP_ULE,
1457 LHSI->getOperand(0), SubOne(RHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001458 break;
1459
1460 case Instruction::Or: {
1461 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1462 break;
1463 Value *P, *Q;
1464 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1465 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1466 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001467 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1468 Constant::getNullValue(P->getType()));
1469 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1470 Constant::getNullValue(Q->getType()));
1471 Instruction *Op;
1472 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1473 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1474 else
1475 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1476 return Op;
1477 }
1478 break;
1479 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001480
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001481 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1482 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1483 if (!Val) break;
1484
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001485 // If this is a signed comparison to 0 and the mul is sign preserving,
1486 // use the mul LHS operand instead.
1487 ICmpInst::Predicate pred = ICI.getPredicate();
1488 if (isSignTest(pred, RHS) && !Val->isZero() &&
1489 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1490 return new ICmpInst(Val->isNegative() ?
1491 ICmpInst::getSwappedPredicate(pred) : pred,
1492 LHSI->getOperand(0),
1493 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001494
1495 break;
1496 }
1497
Chris Lattner2188e402010-01-04 07:37:31 +00001498 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001499 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001500 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1501 if (!ShAmt) {
1502 Value *X;
1503 // (1 << X) pred P2 -> X pred Log2(P2)
1504 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1505 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1506 ICmpInst::Predicate Pred = ICI.getPredicate();
1507 if (ICI.isUnsigned()) {
1508 if (!RHSVIsPowerOf2) {
1509 // (1 << X) < 30 -> X <= 4
1510 // (1 << X) <= 30 -> X <= 4
1511 // (1 << X) >= 30 -> X > 4
1512 // (1 << X) > 30 -> X > 4
1513 if (Pred == ICmpInst::ICMP_ULT)
1514 Pred = ICmpInst::ICMP_ULE;
1515 else if (Pred == ICmpInst::ICMP_UGE)
1516 Pred = ICmpInst::ICMP_UGT;
1517 }
1518 unsigned RHSLog2 = RHSV.logBase2();
1519
1520 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
David Majnemerb889e402013-06-28 23:42:03 +00001521 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1522 if (RHSLog2 == TypeBits-1) {
1523 if (Pred == ICmpInst::ICMP_UGE)
1524 Pred = ICmpInst::ICMP_EQ;
David Majnemerb889e402013-06-28 23:42:03 +00001525 else if (Pred == ICmpInst::ICMP_ULT)
1526 Pred = ICmpInst::ICMP_NE;
1527 }
1528
1529 return new ICmpInst(Pred, X,
1530 ConstantInt::get(RHS->getType(), RHSLog2));
1531 } else if (ICI.isSigned()) {
1532 if (RHSV.isAllOnesValue()) {
1533 // (1 << X) <= -1 -> X == 31
1534 if (Pred == ICmpInst::ICMP_SLE)
1535 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1536 ConstantInt::get(RHS->getType(), TypeBits-1));
1537
1538 // (1 << X) > -1 -> X != 31
1539 if (Pred == ICmpInst::ICMP_SGT)
1540 return new ICmpInst(ICmpInst::ICMP_NE, X,
1541 ConstantInt::get(RHS->getType(), TypeBits-1));
1542 } else if (!RHSV) {
1543 // (1 << X) < 0 -> X == 31
1544 // (1 << X) <= 0 -> X == 31
1545 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1546 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1547 ConstantInt::get(RHS->getType(), TypeBits-1));
1548
1549 // (1 << X) >= 0 -> X != 31
1550 // (1 << X) > 0 -> X != 31
1551 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1552 return new ICmpInst(ICmpInst::ICMP_NE, X,
1553 ConstantInt::get(RHS->getType(), TypeBits-1));
1554 }
1555 } else if (ICI.isEquality()) {
1556 if (RHSVIsPowerOf2)
1557 return new ICmpInst(
1558 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
David Majnemerb889e402013-06-28 23:42:03 +00001559 }
1560 }
1561 break;
1562 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001563
Chris Lattner2188e402010-01-04 07:37:31 +00001564 // Check that the shift amount is in range. If not, don't perform
1565 // undefined shifts. When the shift is visited it will be
1566 // simplified.
1567 if (ShAmt->uge(TypeBits))
1568 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001569
Chris Lattner2188e402010-01-04 07:37:31 +00001570 if (ICI.isEquality()) {
1571 // If we are comparing against bits always shifted out, the
1572 // comparison cannot succeed.
1573 Constant *Comp =
1574 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1575 ShAmt);
1576 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1577 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001578 Constant *Cst = Builder->getInt1(IsICMP_NE);
Chris Lattner2188e402010-01-04 07:37:31 +00001579 return ReplaceInstUsesWith(ICI, Cst);
1580 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001581
Chris Lattner98457102011-02-10 05:23:05 +00001582 // If the shift is NUW, then it is just shifting out zeros, no need for an
1583 // AND.
1584 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1585 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1586 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001587
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001588 // If the shift is NSW and we compare to 0, then it is just shifting out
1589 // sign bits, no need for an AND either.
1590 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1591 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1592 ConstantExpr::getLShr(RHS, ShAmt));
1593
Chris Lattner2188e402010-01-04 07:37:31 +00001594 if (LHSI->hasOneUse()) {
1595 // Otherwise strength reduce the shift into an and.
1596 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00001597 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1598 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001599
Chris Lattner2188e402010-01-04 07:37:31 +00001600 Value *And =
1601 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1602 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00001603 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00001604 }
1605 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001606
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001607 // If this is a signed comparison to 0 and the shift is sign preserving,
1608 // use the shift LHS operand instead.
1609 ICmpInst::Predicate pred = ICI.getPredicate();
1610 if (isSignTest(pred, RHS) &&
1611 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1612 return new ICmpInst(pred,
1613 LHSI->getOperand(0),
1614 Constant::getNullValue(RHS->getType()));
1615
Chris Lattner2188e402010-01-04 07:37:31 +00001616 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1617 bool TrueIfSigned = false;
1618 if (LHSI->hasOneUse() &&
1619 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1620 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00001621 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00001622 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00001623 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00001624 Value *And =
1625 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1626 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1627 And, Constant::getNullValue(And->getType()));
1628 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001629
1630 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001631 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1632 // 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 +00001633 // This enables to get rid of the shift in favor of a trunc which can be
1634 // free on the target. It has the additional benefit of comparing to a
1635 // smaller constant, which will be target friendly.
1636 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00001637 if (LHSI->hasOneUse() &&
1638 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001639 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1640 Constant *NCI = ConstantExpr::getTrunc(
1641 ConstantExpr::getAShr(RHS,
1642 ConstantInt::get(RHS->getType(), Amt)),
1643 NTy);
1644 return new ICmpInst(ICI.getPredicate(),
1645 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00001646 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00001647 }
1648
Chris Lattner2188e402010-01-04 07:37:31 +00001649 break;
1650 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001651
Chris Lattner2188e402010-01-04 07:37:31 +00001652 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00001653 case Instruction::AShr: {
1654 // Handle equality comparisons of shift-by-constant.
1655 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1656 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1657 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00001658 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00001659 }
1660
1661 // Handle exact shr's.
1662 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1663 if (RHSV.isMinValue())
1664 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1665 }
Chris Lattner2188e402010-01-04 07:37:31 +00001666 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00001667 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001668
Chris Lattner2188e402010-01-04 07:37:31 +00001669 case Instruction::SDiv:
1670 case Instruction::UDiv:
1671 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00001672 // Fold this div into the comparison, producing a range check.
1673 // Determine, based on the divide type, what the range is being
1674 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00001675 // it, otherwise compute the range [low, hi) bounding the new value.
1676 // See: InsertRangeTest above for the kinds of replacements possible.
1677 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1678 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1679 DivRHS))
1680 return R;
1681 break;
1682
David Majnemerf2a9a512013-07-09 07:50:59 +00001683 case Instruction::Sub: {
1684 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1685 if (!LHSC) break;
1686 const APInt &LHSV = LHSC->getValue();
1687
1688 // C1-X <u C2 -> (X|(C2-1)) == C1
1689 // iff C1 & (C2-1) == C2-1
1690 // C2 is a power of 2
1691 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1692 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1693 return new ICmpInst(ICmpInst::ICMP_EQ,
1694 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1695 LHSC);
1696
David Majnemereeed73b2013-07-09 09:24:35 +00001697 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00001698 // iff C1 & C2 == C2
1699 // C2+1 is a power of 2
1700 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1701 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1702 return new ICmpInst(ICmpInst::ICMP_NE,
1703 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1704 break;
1705 }
1706
Chris Lattner2188e402010-01-04 07:37:31 +00001707 case Instruction::Add:
1708 // Fold: icmp pred (add X, C1), C2
1709 if (!ICI.isEquality()) {
1710 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1711 if (!LHSC) break;
1712 const APInt &LHSV = LHSC->getValue();
1713
1714 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1715 .subtract(LHSV);
1716
1717 if (ICI.isSigned()) {
1718 if (CR.getLower().isSignBit()) {
1719 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001720 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001721 } else if (CR.getUpper().isSignBit()) {
1722 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001723 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001724 }
1725 } else {
1726 if (CR.getLower().isMinValue()) {
1727 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001728 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00001729 } else if (CR.getUpper().isMinValue()) {
1730 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001731 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00001732 }
1733 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00001734
David Majnemerbafa5372013-07-09 07:58:32 +00001735 // X-C1 <u C2 -> (X & -C2) == C1
1736 // iff C1 & (C2-1) == 0
1737 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00001738 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00001739 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00001740 return new ICmpInst(ICmpInst::ICMP_EQ,
1741 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1742 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00001743
David Majnemereeed73b2013-07-09 09:24:35 +00001744 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00001745 // iff C1 & C2 == 0
1746 // C2+1 is a power of 2
1747 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1748 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1749 return new ICmpInst(ICmpInst::ICMP_NE,
1750 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1751 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00001752 }
1753 break;
1754 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001755
Chris Lattner2188e402010-01-04 07:37:31 +00001756 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1757 if (ICI.isEquality()) {
1758 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001759
1760 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
Chris Lattner2188e402010-01-04 07:37:31 +00001761 // the second operand is a constant, simplify a bit.
1762 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1763 switch (BO->getOpcode()) {
1764 case Instruction::SRem:
1765 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1766 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1767 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
Dan Gohman4ce1fb12010-04-08 23:03:40 +00001768 if (V.sgt(1) && V.isPowerOf2()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001769 Value *NewRem =
1770 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1771 BO->getName());
1772 return new ICmpInst(ICI.getPredicate(), NewRem,
1773 Constant::getNullValue(BO->getType()));
1774 }
1775 }
1776 break;
1777 case Instruction::Add:
1778 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1779 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1780 if (BO->hasOneUse())
1781 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1782 ConstantExpr::getSub(RHS, BOp1C));
1783 } else if (RHSV == 0) {
1784 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1785 // efficiently invertible, or if the add has just this one use.
1786 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001787
Chris Lattner2188e402010-01-04 07:37:31 +00001788 if (Value *NegVal = dyn_castNegVal(BOp1))
1789 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Chris Lattner31b106d2011-04-26 20:02:45 +00001790 if (Value *NegVal = dyn_castNegVal(BOp0))
Chris Lattner2188e402010-01-04 07:37:31 +00001791 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner31b106d2011-04-26 20:02:45 +00001792 if (BO->hasOneUse()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001793 Value *Neg = Builder->CreateNeg(BOp1);
1794 Neg->takeName(BO);
1795 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1796 }
1797 }
1798 break;
1799 case Instruction::Xor:
1800 // For the xor case, we can xor two constants together, eliminating
1801 // the explicit xor.
Benjamin Kramerc9708492011-06-13 15:24:24 +00001802 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1803 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner2188e402010-01-04 07:37:31 +00001804 ConstantExpr::getXor(RHS, BOC));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001805 } else if (RHSV == 0) {
1806 // Replace ((xor A, B) != 0) with (A != B)
Chris Lattner2188e402010-01-04 07:37:31 +00001807 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1808 BO->getOperand(1));
Benjamin Kramerc9708492011-06-13 15:24:24 +00001809 }
Chris Lattner2188e402010-01-04 07:37:31 +00001810 break;
Benjamin Kramerc9708492011-06-13 15:24:24 +00001811 case Instruction::Sub:
1812 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1813 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1814 if (BO->hasOneUse())
1815 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1816 ConstantExpr::getSub(BOp0C, RHS));
1817 } else if (RHSV == 0) {
1818 // Replace ((sub A, B) != 0) with (A != B)
1819 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1820 BO->getOperand(1));
1821 }
1822 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001823 case Instruction::Or:
1824 // If bits are being or'd in that are not present in the constant we
1825 // are comparing against, then the comparison could never succeed!
Eli Friedman0428a612010-07-29 18:03:33 +00001826 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001827 Constant *NotCI = ConstantExpr::getNot(RHS);
1828 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Jakub Staszakbddea112013-06-06 20:18:46 +00001829 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Chris Lattner2188e402010-01-04 07:37:31 +00001830 }
1831 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001832
Chris Lattner2188e402010-01-04 07:37:31 +00001833 case Instruction::And:
1834 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1835 // If bits are being compared against that are and'd out, then the
1836 // comparison can never succeed!
1837 if ((RHSV & ~BOC->getValue()) != 0)
Jakub Staszakbddea112013-06-06 20:18:46 +00001838 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001839
Chris Lattner2188e402010-01-04 07:37:31 +00001840 // If we have ((X & C) == C), turn it into ((X & C) != 0).
1841 if (RHS == BOC && RHSV.isPowerOf2())
1842 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1843 ICmpInst::ICMP_NE, LHSI,
1844 Constant::getNullValue(RHS->getType()));
Benjamin Kramer9eca5fe2011-07-04 20:16:36 +00001845
1846 // Don't perform the following transforms if the AND has multiple uses
1847 if (!BO->hasOneUse())
1848 break;
1849
Chris Lattner2188e402010-01-04 07:37:31 +00001850 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1851 if (BOC->getValue().isSignBit()) {
1852 Value *X = BO->getOperand(0);
1853 Constant *Zero = Constant::getNullValue(X->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001854 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001855 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1856 return new ICmpInst(pred, X, Zero);
1857 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001858
Chris Lattner2188e402010-01-04 07:37:31 +00001859 // ((X & ~7) == 0) --> X < 8
1860 if (RHSV == 0 && isHighOnes(BOC)) {
1861 Value *X = BO->getOperand(0);
1862 Constant *NegX = ConstantExpr::getNeg(BOC);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001863 ICmpInst::Predicate pred = isICMP_NE ?
Chris Lattner2188e402010-01-04 07:37:31 +00001864 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1865 return new ICmpInst(pred, X, NegX);
1866 }
1867 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001868 break;
1869 case Instruction::Mul:
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001870 if (RHSV == 0 && BO->hasNoSignedWrap()) {
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001871 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1872 // The trivial case (mul X, 0) is handled by InstSimplify
1873 // General case : (mul X, C) != 0 iff X != 0
1874 // (mul X, C) == 0 iff X == 0
1875 if (!BOC->isZero())
1876 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1877 Constant::getNullValue(RHS->getType()));
1878 }
1879 }
1880 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001881 default: break;
1882 }
1883 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1884 // Handle icmp {eq|ne} <intrinsic>, intcst.
Chris Lattner54f4e392010-01-05 18:09:56 +00001885 switch (II->getIntrinsicID()) {
1886 case Intrinsic::bswap:
Chris Lattner2188e402010-01-04 07:37:31 +00001887 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001888 ICI.setOperand(0, II->getArgOperand(0));
Jakub Staszakbddea112013-06-06 20:18:46 +00001889 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
Chris Lattner2188e402010-01-04 07:37:31 +00001890 return &ICI;
Chris Lattner54f4e392010-01-05 18:09:56 +00001891 case Intrinsic::ctlz:
1892 case Intrinsic::cttz:
1893 // ctz(A) == bitwidth(a) -> A == 0 and likewise for !=
1894 if (RHSV == RHS->getType()->getBitWidth()) {
1895 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001896 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001897 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1898 return &ICI;
1899 }
1900 break;
1901 case Intrinsic::ctpop:
1902 // popcount(A) == 0 -> A == 0 and likewise for !=
1903 if (RHS->isZero()) {
1904 Worklist.Add(II);
Gabor Greif7ccec092010-06-24 16:11:44 +00001905 ICI.setOperand(0, II->getArgOperand(0));
Chris Lattner54f4e392010-01-05 18:09:56 +00001906 ICI.setOperand(1, RHS);
1907 return &ICI;
1908 }
1909 break;
1910 default:
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001911 break;
Chris Lattner2188e402010-01-04 07:37:31 +00001912 }
1913 }
1914 }
Craig Topperf40110f2014-04-25 05:29:35 +00001915 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001916}
1917
1918/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1919/// We only handle extending casts so far.
1920///
1921Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1922 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1923 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001924 Type *SrcTy = LHSCIOp->getType();
1925 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00001926 Value *RHSCIOp;
1927
Jim Grosbach129c52a2011-09-30 18:09:53 +00001928 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00001929 // integer type is the same size as the pointer type.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001930 if (DL && LHSCI->getOpcode() == Instruction::PtrToInt &&
1931 DL->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001932 Value *RHSOp = nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001933 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1934 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1935 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1936 RHSOp = RHSC->getOperand(0);
1937 // If the pointer types don't match, insert a bitcast.
1938 if (LHSCIOp->getType() != RHSOp->getType())
1939 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1940 }
1941
1942 if (RHSOp)
1943 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1944 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001945
Chris Lattner2188e402010-01-04 07:37:31 +00001946 // The code below only handles extension cast instructions, so far.
1947 // Enforce this.
1948 if (LHSCI->getOpcode() != Instruction::ZExt &&
1949 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00001950 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001951
1952 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1953 bool isSignedCmp = ICI.isSigned();
1954
1955 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1956 // Not an extension from the same type?
1957 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001958 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001959 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001960
Chris Lattner2188e402010-01-04 07:37:31 +00001961 // If the signedness of the two casts doesn't agree (i.e. one is a sext
1962 // and the other is a zext), then we can't handle this.
1963 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00001964 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001965
1966 // Deal with equality cases early.
1967 if (ICI.isEquality())
1968 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1969
1970 // A signed comparison of sign extended values simplifies into a
1971 // signed comparison.
1972 if (isSignedCmp && isSignedExt)
1973 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1974
1975 // The other three cases all fold into an unsigned comparison.
1976 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1977 }
1978
1979 // If we aren't dealing with a constant on the RHS, exit early
1980 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1981 if (!CI)
Craig Topperf40110f2014-04-25 05:29:35 +00001982 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001983
1984 // Compute the constant that would happen if we truncated to SrcTy then
1985 // reextended to DestTy.
1986 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1987 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1988 Res1, DestTy);
1989
1990 // If the re-extended constant didn't change...
1991 if (Res2 == CI) {
1992 // Deal with equality cases early.
1993 if (ICI.isEquality())
1994 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1995
1996 // A signed comparison of sign extended values simplifies into a
1997 // signed comparison.
1998 if (isSignedExt && isSignedCmp)
1999 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
2000
2001 // The other three cases all fold into an unsigned comparison.
2002 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
2003 }
2004
Jim Grosbach129c52a2011-09-30 18:09:53 +00002005 // The re-extended constant changed so the constant cannot be represented
Chris Lattner2188e402010-01-04 07:37:31 +00002006 // in the shorter type. Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002007 // All the cases that fold to true or false will have already been handled
2008 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002009
Duncan Sands8fb2c382011-01-20 13:21:55 +00002010 if (isSignedCmp || !isSignedExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002011 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002012
2013 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2014 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002015
2016 // We're performing an unsigned comp with a sign extended value.
2017 // This is true if the input is >= 0. [aka >s -1]
2018 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
2019 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002020
2021 // Finally, return the value computed.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002022 if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
Chris Lattner2188e402010-01-04 07:37:31 +00002023 return ReplaceInstUsesWith(ICI, Result);
2024
Duncan Sands8fb2c382011-01-20 13:21:55 +00002025 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002026 return BinaryOperator::CreateNot(Result);
2027}
2028
Chris Lattneree61c1d2010-12-19 17:52:50 +00002029/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
2030/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002031/// If this is of the form:
2032/// sum = a + b
2033/// if (sum+128 >u 255)
2034/// Then replace it with llvm.sadd.with.overflow.i8.
2035///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002036static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2037 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002038 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002039 // The transformation we're trying to do here is to transform this into an
2040 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2041 // with a narrower add, and discard the add-with-constant that is part of the
2042 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002043
Chris Lattnerf29562d2010-12-19 17:59:02 +00002044 // In order to eliminate the add-with-constant, the compare can be its only
2045 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002046 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002047 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002048
Chris Lattnerc56c8452010-12-19 18:22:06 +00002049 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002050 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002051 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002052 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002053
Chris Lattnerc56c8452010-12-19 18:22:06 +00002054 // The width of the new add formed is 1 more than the bias.
2055 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002056
Chris Lattnerc56c8452010-12-19 18:22:06 +00002057 // Check to see that CI1 is an all-ones value with NewWidth bits.
2058 if (CI1->getBitWidth() == NewWidth ||
2059 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002060 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002061
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002062 // This is only really a signed overflow check if the inputs have been
2063 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2064 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2065 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002066 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2067 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002068 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002069
Jim Grosbach129c52a2011-09-30 18:09:53 +00002070 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002071 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2072 // and truncates that discard the high bits of the add. Verify that this is
2073 // the case.
2074 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002075 for (User *U : OrigAdd->users()) {
2076 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002077
Chris Lattnerc56c8452010-12-19 18:22:06 +00002078 // Only accept truncates for now. We would really like a nice recursive
2079 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2080 // chain to see which bits of a value are actually demanded. If the
2081 // original add had another add which was then immediately truncated, we
2082 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002083 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002084 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2085 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002086 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002087
Chris Lattneree61c1d2010-12-19 17:52:50 +00002088 // If the pattern matches, truncate the inputs to the narrower type and
2089 // use the sadd_with_overflow intrinsic to efficiently compute both the
2090 // result and the overflow bit.
Chris Lattner79874562010-12-19 18:35:09 +00002091 Module *M = I.getParent()->getParent()->getParent();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002092
Jay Foadb804a2b2011-07-12 14:06:48 +00002093 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Chris Lattner79874562010-12-19 18:35:09 +00002094 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
Benjamin Kramere6e19332011-07-14 17:45:39 +00002095 NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002096
Chris Lattnerce2995a2010-12-19 18:38:44 +00002097 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002098
Chris Lattner79874562010-12-19 18:35:09 +00002099 // Put the new code above the original add, in case there are any uses of the
2100 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002101 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002102
Chris Lattner79874562010-12-19 18:35:09 +00002103 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2104 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
2105 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
2106 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2107 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002108
Chris Lattneree61c1d2010-12-19 17:52:50 +00002109 // The inner add was the result of the narrow add, zero extended to the
2110 // wider type. Replace it with the result computed by the intrinsic.
Chris Lattnerce2995a2010-12-19 18:38:44 +00002111 IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002112
Chris Lattner79874562010-12-19 18:35:09 +00002113 // The original icmp gets replaced with the overflow value.
2114 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002115}
Chris Lattner2188e402010-01-04 07:37:31 +00002116
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002117static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
2118 InstCombiner &IC) {
2119 // Don't bother doing this transformation for pointers, don't do it for
2120 // vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00002121 if (!isa<IntegerType>(OrigAddV->getType())) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002122
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002123 // If the add is a constant expr, then we don't bother transforming it.
2124 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
Craig Topperf40110f2014-04-25 05:29:35 +00002125 if (!OrigAdd) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002126
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002127 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002128
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002129 // Put the new code above the original add, in case there are any uses of the
2130 // add between the add and the compare.
2131 InstCombiner::BuilderTy *Builder = IC.Builder;
2132 Builder->SetInsertPoint(OrigAdd);
2133
2134 Module *M = I.getParent()->getParent()->getParent();
Jay Foadb804a2b2011-07-12 14:06:48 +00002135 Type *Ty = LHS->getType();
Benjamin Kramere6e19332011-07-14 17:45:39 +00002136 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002137 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
2138 Value *Add = Builder->CreateExtractValue(Call, 0);
2139
2140 IC.ReplaceInstUsesWith(*OrigAdd, Add);
2141
2142 // The original icmp gets replaced with the overflow value.
2143 return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2144}
2145
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002146/// \brief Recognize and process idiom involving test for multiplication
2147/// overflow.
2148///
2149/// The caller has matched a pattern of the form:
2150/// I = cmp u (mul(zext A, zext B), V
2151/// The function checks if this is a test for overflow and if so replaces
2152/// multiplication with call to 'mul.with.overflow' intrinsic.
2153///
2154/// \param I Compare instruction.
2155/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2156/// the compare instruction. Must be of integer type.
2157/// \param OtherVal The other argument of compare instruction.
2158/// \returns Instruction which must replace the compare instruction, NULL if no
2159/// replacement required.
2160static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2161 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002162 // Don't bother doing this transformation for pointers, don't do it for
2163 // vectors.
2164 if (!isa<IntegerType>(MulVal->getType()))
2165 return nullptr;
2166
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002167 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2168 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002169 Instruction *MulInstr = cast<Instruction>(MulVal);
2170 assert(MulInstr->getOpcode() == Instruction::Mul);
2171
David Majnemer634ca232014-11-01 23:46:05 +00002172 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2173 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002174 assert(LHS->getOpcode() == Instruction::ZExt);
2175 assert(RHS->getOpcode() == Instruction::ZExt);
2176 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2177
2178 // Calculate type and width of the result produced by mul.with.overflow.
2179 Type *TyA = A->getType(), *TyB = B->getType();
2180 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2181 WidthB = TyB->getPrimitiveSizeInBits();
2182 unsigned MulWidth;
2183 Type *MulType;
2184 if (WidthB > WidthA) {
2185 MulWidth = WidthB;
2186 MulType = TyB;
2187 } else {
2188 MulWidth = WidthA;
2189 MulType = TyA;
2190 }
2191
2192 // In order to replace the original mul with a narrower mul.with.overflow,
2193 // all uses must ignore upper bits of the product. The number of used low
2194 // bits must be not greater than the width of mul.with.overflow.
2195 if (MulVal->hasNUsesOrMore(2))
2196 for (User *U : MulVal->users()) {
2197 if (U == &I)
2198 continue;
2199 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2200 // Check if truncation ignores bits above MulWidth.
2201 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2202 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002203 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002204 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2205 // Check if AND ignores bits above MulWidth.
2206 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002207 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002208 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2209 const APInt &CVal = CI->getValue();
2210 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002211 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002212 }
2213 } else {
2214 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002215 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002216 }
2217 }
2218
2219 // Recognize patterns
2220 switch (I.getPredicate()) {
2221 case ICmpInst::ICMP_EQ:
2222 case ICmpInst::ICMP_NE:
2223 // Recognize pattern:
2224 // mulval = mul(zext A, zext B)
2225 // cmp eq/neq mulval, zext trunc mulval
2226 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2227 if (Zext->hasOneUse()) {
2228 Value *ZextArg = Zext->getOperand(0);
2229 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2230 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2231 break; //Recognized
2232 }
2233
2234 // Recognize pattern:
2235 // mulval = mul(zext A, zext B)
2236 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2237 ConstantInt *CI;
2238 Value *ValToMask;
2239 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2240 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002241 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002242 const APInt &CVal = CI->getValue() + 1;
2243 if (CVal.isPowerOf2()) {
2244 unsigned MaskWidth = CVal.logBase2();
2245 if (MaskWidth == MulWidth)
2246 break; // Recognized
2247 }
2248 }
Craig Topperf40110f2014-04-25 05:29:35 +00002249 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002250
2251 case ICmpInst::ICMP_UGT:
2252 // Recognize pattern:
2253 // mulval = mul(zext A, zext B)
2254 // cmp ugt mulval, max
2255 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2256 APInt MaxVal = APInt::getMaxValue(MulWidth);
2257 MaxVal = MaxVal.zext(CI->getBitWidth());
2258 if (MaxVal.eq(CI->getValue()))
2259 break; // Recognized
2260 }
Craig Topperf40110f2014-04-25 05:29:35 +00002261 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002262
2263 case ICmpInst::ICMP_UGE:
2264 // Recognize pattern:
2265 // mulval = mul(zext A, zext B)
2266 // cmp uge mulval, max+1
2267 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2268 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2269 if (MaxVal.eq(CI->getValue()))
2270 break; // Recognized
2271 }
Craig Topperf40110f2014-04-25 05:29:35 +00002272 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002273
2274 case ICmpInst::ICMP_ULE:
2275 // Recognize pattern:
2276 // mulval = mul(zext A, zext B)
2277 // cmp ule mulval, max
2278 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2279 APInt MaxVal = APInt::getMaxValue(MulWidth);
2280 MaxVal = MaxVal.zext(CI->getBitWidth());
2281 if (MaxVal.eq(CI->getValue()))
2282 break; // Recognized
2283 }
Craig Topperf40110f2014-04-25 05:29:35 +00002284 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002285
2286 case ICmpInst::ICMP_ULT:
2287 // Recognize pattern:
2288 // mulval = mul(zext A, zext B)
2289 // cmp ule mulval, max + 1
2290 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002291 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002292 if (MaxVal.eq(CI->getValue()))
2293 break; // Recognized
2294 }
Craig Topperf40110f2014-04-25 05:29:35 +00002295 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002296
2297 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002298 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002299 }
2300
2301 InstCombiner::BuilderTy *Builder = IC.Builder;
2302 Builder->SetInsertPoint(MulInstr);
2303 Module *M = I.getParent()->getParent()->getParent();
2304
2305 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2306 Value *MulA = A, *MulB = B;
2307 if (WidthA < MulWidth)
2308 MulA = Builder->CreateZExt(A, MulType);
2309 if (WidthB < MulWidth)
2310 MulB = Builder->CreateZExt(B, MulType);
2311 Value *F =
2312 Intrinsic::getDeclaration(M, Intrinsic::umul_with_overflow, MulType);
2313 CallInst *Call = Builder->CreateCall2(F, MulA, MulB, "umul");
2314 IC.Worklist.Add(MulInstr);
2315
2316 // If there are uses of mul result other than the comparison, we know that
2317 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002318 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002319 if (MulVal->hasNUsesOrMore(2)) {
2320 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2321 for (User *U : MulVal->users()) {
2322 if (U == &I || U == OtherVal)
2323 continue;
2324 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2325 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
2326 IC.ReplaceInstUsesWith(*TI, Mul);
2327 else
2328 TI->setOperand(0, Mul);
2329 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2330 assert(BO->getOpcode() == Instruction::And);
2331 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2332 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2333 APInt ShortMask = CI->getValue().trunc(MulWidth);
2334 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2335 Instruction *Zext =
2336 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2337 IC.Worklist.Add(Zext);
2338 IC.ReplaceInstUsesWith(*BO, Zext);
2339 } else {
2340 llvm_unreachable("Unexpected Binary operation");
2341 }
2342 IC.Worklist.Add(cast<Instruction>(U));
2343 }
2344 }
2345 if (isa<Instruction>(OtherVal))
2346 IC.Worklist.Add(cast<Instruction>(OtherVal));
2347
2348 // The original icmp gets replaced with the overflow value, maybe inverted
2349 // depending on predicate.
2350 bool Inverse = false;
2351 switch (I.getPredicate()) {
2352 case ICmpInst::ICMP_NE:
2353 break;
2354 case ICmpInst::ICMP_EQ:
2355 Inverse = true;
2356 break;
2357 case ICmpInst::ICMP_UGT:
2358 case ICmpInst::ICMP_UGE:
2359 if (I.getOperand(0) == MulVal)
2360 break;
2361 Inverse = true;
2362 break;
2363 case ICmpInst::ICMP_ULT:
2364 case ICmpInst::ICMP_ULE:
2365 if (I.getOperand(1) == MulVal)
2366 break;
2367 Inverse = true;
2368 break;
2369 default:
2370 llvm_unreachable("Unexpected predicate");
2371 }
2372 if (Inverse) {
2373 Value *Res = Builder->CreateExtractValue(Call, 1);
2374 return BinaryOperator::CreateNot(Res);
2375 }
2376
2377 return ExtractValueInst::Create(Call, 1);
2378}
2379
Owen Andersond490c2d2011-01-11 00:36:45 +00002380// DemandedBitsLHSMask - When performing a comparison against a constant,
2381// it is possible that not all the bits in the LHS are demanded. This helper
2382// method computes the mask that IS demanded.
2383static APInt DemandedBitsLHSMask(ICmpInst &I,
2384 unsigned BitWidth, bool isSignCheck) {
2385 if (isSignCheck)
2386 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002387
Owen Andersond490c2d2011-01-11 00:36:45 +00002388 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2389 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002390 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002391
Owen Andersond490c2d2011-01-11 00:36:45 +00002392 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002393 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002394 // correspond to the trailing ones of the comparand. The value of these
2395 // bits doesn't impact the outcome of the comparison, because any value
2396 // greater than the RHS must differ in a bit higher than these due to carry.
2397 case ICmpInst::ICMP_UGT: {
2398 unsigned trailingOnes = RHS.countTrailingOnes();
2399 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2400 return ~lowBitsSet;
2401 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002402
Owen Andersond490c2d2011-01-11 00:36:45 +00002403 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2404 // Any value less than the RHS must differ in a higher bit because of carries.
2405 case ICmpInst::ICMP_ULT: {
2406 unsigned trailingZeros = RHS.countTrailingZeros();
2407 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2408 return ~lowBitsSet;
2409 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002410
Owen Andersond490c2d2011-01-11 00:36:45 +00002411 default:
2412 return APInt::getAllOnesValue(BitWidth);
2413 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002414
Owen Andersond490c2d2011-01-11 00:36:45 +00002415}
Chris Lattner2188e402010-01-04 07:37:31 +00002416
Quentin Colombet5ab55552013-09-09 20:56:48 +00002417/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2418/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002419/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002420/// as subtract operands and their positions in those instructions.
2421/// The rational is that several architectures use the same instruction for
2422/// both subtract and cmp, thus it is better if the order of those operands
2423/// match.
2424/// \return true if Op0 and Op1 should be swapped.
2425static bool swapMayExposeCSEOpportunities(const Value * Op0,
2426 const Value * Op1) {
2427 // Filter out pointer value as those cannot appears directly in subtract.
2428 // FIXME: we may want to go through inttoptrs or bitcasts.
2429 if (Op0->getType()->isPointerTy())
2430 return false;
2431 // Count every uses of both Op0 and Op1 in a subtract.
2432 // Each time Op0 is the first operand, count -1: swapping is bad, the
2433 // subtract has already the same layout as the compare.
2434 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002435 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002436 // At the end, if the benefit is greater than 0, Op0 should come second to
2437 // expose more CSE opportunities.
2438 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002439 for (const User *U : Op0->users()) {
2440 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002441 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2442 continue;
2443 // If Op0 is the first argument, this is not beneficial to swap the
2444 // arguments.
2445 int LocalSwapBenefits = -1;
2446 unsigned Op1Idx = 1;
2447 if (BinOp->getOperand(Op1Idx) == Op0) {
2448 Op1Idx = 0;
2449 LocalSwapBenefits = 1;
2450 }
2451 if (BinOp->getOperand(Op1Idx) != Op1)
2452 continue;
2453 GlobalSwapBenefits += LocalSwapBenefits;
2454 }
2455 return GlobalSwapBenefits > 0;
2456}
2457
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002458/// \brief Check that one use is in the same block as the definition and all
2459/// other uses are in blocks dominated by a given block
2460///
2461/// \param DI Definition
2462/// \param UI Use
2463/// \param DB Block that must dominate all uses of \p DI outside
2464/// the parent block
2465/// \return true when \p UI is the only use of \p DI in the parent block
2466/// and all other uses of \p DI are in blocks dominated by \p DB.
2467///
2468bool InstCombiner::dominatesAllUses(const Instruction *DI,
2469 const Instruction *UI,
2470 const BasicBlock *DB) const {
2471 assert(DI && UI && "Instruction not defined\n");
2472 // ignore incomplete definitions
2473 if (!DI->getParent())
2474 return false;
2475 // DI and UI must be in the same block
2476 if (DI->getParent() != UI->getParent())
2477 return false;
2478 // Protect from self-referencing blocks
2479 if (DI->getParent() == DB)
2480 return false;
2481 // DominatorTree available?
2482 if (!DT)
2483 return false;
2484 for (const User *U : DI->users()) {
2485 auto *Usr = cast<Instruction>(U);
2486 if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
2487 return false;
2488 }
2489 return true;
2490}
2491
2492///
2493/// true when the instruction sequence within a block is select-cmp-br.
2494///
2495static bool isChainSelectCmpBranch(const SelectInst *SI) {
2496 const BasicBlock *BB = SI->getParent();
2497 if (!BB)
2498 return false;
2499 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
2500 if (!BI || BI->getNumSuccessors() != 2)
2501 return false;
2502 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
2503 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
2504 return false;
2505 return true;
2506}
2507
2508///
2509/// \brief True when a select result is replaced by one of its operands
2510/// in select-icmp sequence. This will eventually result in the elimination
2511/// of the select.
2512///
2513/// \param SI Select instruction
2514/// \param Icmp Compare instruction
2515/// \param SIOpd Operand that replaces the select
2516///
2517/// Notes:
2518/// - The replacement is global and requires dominator information
2519/// - The caller is responsible for the actual replacement
2520///
2521/// Example:
2522///
2523/// entry:
2524/// %4 = select i1 %3, %C* %0, %C* null
2525/// %5 = icmp eq %C* %4, null
2526/// br i1 %5, label %9, label %7
2527/// ...
2528/// ; <label>:7 ; preds = %entry
2529/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
2530/// ...
2531///
2532/// can be transformed to
2533///
2534/// %5 = icmp eq %C* %0, null
2535/// %6 = select i1 %3, i1 %5, i1 true
2536/// br i1 %6, label %9, label %7
2537/// ...
2538/// ; <label>:7 ; preds = %entry
2539/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
2540///
2541/// Similar when the first operand of the select is a constant or/and
2542/// the compare is for not equal rather than equal.
2543///
2544/// NOTE: The function is only called when the select and compare constants
2545/// are equal, the optimization can work only for EQ predicates. This is not a
2546/// major restriction since a NE compare should be 'normalized' to an equal
2547/// compare, which usually happens in the combiner and test case
2548/// select-cmp-br.ll
2549/// checks for it.
2550bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
2551 const ICmpInst *Icmp,
2552 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00002553 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002554 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
2555 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
2556 // The check for the unique predecessor is not the best that can be
2557 // done. But it protects efficiently against cases like when SI's
2558 // home block has two successors, Succ and Succ1, and Succ1 predecessor
2559 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
2560 // replaced can be reached on either path. So the uniqueness check
2561 // guarantees that the path all uses of SI (outside SI's parent) are on
2562 // is disjoint from all other paths out of SI. But that information
2563 // is more expensive to compute, and the trade-off here is in favor
2564 // of compile-time.
2565 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
2566 NumSel++;
2567 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
2568 return true;
2569 }
2570 }
2571 return false;
2572}
2573
Chris Lattner2188e402010-01-04 07:37:31 +00002574Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2575 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00002576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002577 unsigned Op0Cplxity = getComplexity(Op0);
2578 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002579
Chris Lattner2188e402010-01-04 07:37:31 +00002580 /// Orders the operands of the compare so that they are listed from most
2581 /// complex to least complex. This puts constants before unary operators,
2582 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002583 if (Op0Cplxity < Op1Cplxity ||
2584 (Op0Cplxity == Op1Cplxity &&
2585 swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002586 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00002587 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002588 Changed = true;
2589 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002590
Hal Finkel60db0582014-09-07 18:57:58 +00002591 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AT))
Chris Lattner2188e402010-01-04 07:37:31 +00002592 return ReplaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002593
Pete Cooperbc5c5242011-12-01 03:58:40 +00002594 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00002595 // ie, abs(val) != 0 -> val != 0
Pete Cooperbc5c5242011-12-01 03:58:40 +00002596 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2597 {
Pete Cooperfdddc272011-12-01 19:13:26 +00002598 Value *Cond, *SelectTrue, *SelectFalse;
2599 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00002600 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00002601 if (Value *V = dyn_castNegVal(SelectTrue)) {
2602 if (V == SelectFalse)
2603 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2604 }
2605 else if (Value *V = dyn_castNegVal(SelectFalse)) {
2606 if (V == SelectTrue)
2607 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00002608 }
2609 }
2610 }
2611
Chris Lattner229907c2011-07-18 04:54:35 +00002612 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002613
2614 // icmp's with boolean values can always be turned into bitwise operations
Duncan Sands9dff9be2010-02-15 16:12:20 +00002615 if (Ty->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00002616 switch (I.getPredicate()) {
2617 default: llvm_unreachable("Invalid icmp instruction!");
2618 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
2619 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2620 return BinaryOperator::CreateNot(Xor);
2621 }
2622 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
2623 return BinaryOperator::CreateXor(Op0, Op1);
2624
2625 case ICmpInst::ICMP_UGT:
2626 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
2627 // FALL THROUGH
2628 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
2629 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2630 return BinaryOperator::CreateAnd(Not, Op1);
2631 }
2632 case ICmpInst::ICMP_SGT:
2633 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
2634 // FALL THROUGH
2635 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
2636 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2637 return BinaryOperator::CreateAnd(Not, Op0);
2638 }
2639 case ICmpInst::ICMP_UGE:
2640 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
2641 // FALL THROUGH
2642 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
2643 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2644 return BinaryOperator::CreateOr(Not, Op1);
2645 }
2646 case ICmpInst::ICMP_SGE:
2647 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
2648 // FALL THROUGH
2649 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
2650 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2651 return BinaryOperator::CreateOr(Not, Op0);
2652 }
2653 }
2654 }
2655
2656 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002657 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00002658 BitWidth = Ty->getScalarSizeInBits();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002659 else if (DL) // Pointers require DL info to get their size.
2660 BitWidth = DL->getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002661
Chris Lattner2188e402010-01-04 07:37:31 +00002662 bool isSignBit = false;
2663
2664 // See if we are doing a comparison with a constant.
2665 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002666 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002667
Owen Anderson1294ea72010-12-17 18:08:00 +00002668 // Match the following pattern, which is a common idiom when writing
2669 // overflow-safe integer arithmetic function. The source performs an
2670 // addition in wider type, and explicitly checks for overflow using
2671 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
2672 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00002673 //
2674 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00002675 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00002676 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00002677 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00002678 // sum = a + b
2679 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00002680 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00002681 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00002682 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00002683 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00002684 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00002685 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00002686 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002687
Chris Lattner2188e402010-01-04 07:37:31 +00002688 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2689 if (I.isEquality() && CI->isZero() &&
2690 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2691 // (icmp cond A B) if cond is equality
2692 return new ICmpInst(I.getPredicate(), A, B);
2693 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002694
David Majnemerf89dc3e2014-12-31 04:21:41 +00002695 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
2696 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
2697 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2698 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
2699
2700 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
2701 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
2702 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2703 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
2704
2705 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
2706 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
2707 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2708 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
2709
2710 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
2711 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
2712 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
2713 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
2714
Chris Lattner2188e402010-01-04 07:37:31 +00002715 // If we have an icmp le or icmp ge instruction, turn it into the
2716 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
2717 // them being folded in the code below. The SimplifyICmpInst code has
2718 // already handled the edge cases for us, so we just assert on them.
2719 switch (I.getPredicate()) {
2720 default: break;
2721 case ICmpInst::ICMP_ULE:
2722 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
2723 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002724 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002725 case ICmpInst::ICMP_SLE:
2726 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
2727 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002728 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002729 case ICmpInst::ICMP_UGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002730 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002731 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002732 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002733 case ICmpInst::ICMP_SGE:
Nick Lewycky6b4454192011-02-28 06:20:05 +00002734 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Chris Lattner2188e402010-01-04 07:37:31 +00002735 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002736 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002737 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002738
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00002739 if (I.isEquality()) {
2740 ConstantInt *CI2;
2741 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
2742 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00002743 // (icmp eq/ne (ashr/lshr const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00002744 if (Instruction *Inst = FoldICmpCstShrCst(I, Op0, A, CI, CI2))
2745 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00002746 }
David Majnemer59939ac2014-10-19 08:23:08 +00002747 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
2748 // (icmp eq/ne (shl const2, A), const1)
David Majnemer2abb8182014-10-25 07:13:13 +00002749 if (Instruction *Inst = FoldICmpCstShlCst(I, Op0, A, CI, CI2))
2750 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00002751 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00002752 }
2753
Chris Lattner2188e402010-01-04 07:37:31 +00002754 // If this comparison is a normal comparison, it demands all
2755 // bits, if it is a sign bit comparison, it only demands the sign bit.
2756 bool UnusedBit;
2757 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2758 }
2759
2760 // See if we can fold the comparison based on range information we can get
2761 // by checking whether bits are known to be zero or one in the input.
2762 if (BitWidth != 0) {
2763 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2764 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2765
2766 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00002767 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00002768 Op0KnownZero, Op0KnownOne, 0))
2769 return &I;
2770 if (SimplifyDemandedBits(I.getOperandUse(1),
2771 APInt::getAllOnesValue(BitWidth),
2772 Op1KnownZero, Op1KnownOne, 0))
2773 return &I;
2774
2775 // Given the known and unknown bits, compute a range that the LHS could be
2776 // in. Compute the Min, Max and RHS values based on the known bits. For the
2777 // EQ and NE we use unsigned values.
2778 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2779 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2780 if (I.isSigned()) {
2781 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2782 Op0Min, Op0Max);
2783 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2784 Op1Min, Op1Max);
2785 } else {
2786 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2787 Op0Min, Op0Max);
2788 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2789 Op1Min, Op1Max);
2790 }
2791
2792 // If Min and Max are known to be the same, then SimplifyDemandedBits
2793 // figured out that the LHS is a constant. Just constant fold this now so
2794 // that code below can assume that Min != Max.
2795 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2796 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00002797 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00002798 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2799 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00002800 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00002801
2802 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00002803 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00002804 switch (I.getPredicate()) {
2805 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00002806 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00002807 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002808 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002809
Chris Lattnerf7e89612010-11-21 06:44:42 +00002810 // If all bits are known zero except for one, then we know at most one
2811 // bit is set. If the comparison is against zero, then this is a check
2812 // to see if *that* bit is set.
2813 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002814 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00002815 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00002816 Value *LHS = nullptr;
2817 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002818 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2819 LHSC->getValue() != Op0KnownZeroInverted)
2820 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002821
Chris Lattnerf7e89612010-11-21 06:44:42 +00002822 // 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 +00002823 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002824 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00002825 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002826 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002827 APInt ValToCheck = Op0KnownZeroInverted;
2828 if (ValToCheck.isPowerOf2()) {
2829 unsigned CmpVal = ValToCheck.countTrailingZeros();
2830 return new ICmpInst(ICmpInst::ICMP_NE, X,
2831 ConstantInt::get(X->getType(), CmpVal));
2832 } else if ((++ValToCheck).isPowerOf2()) {
2833 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
2834 return new ICmpInst(ICmpInst::ICMP_UGT, X,
2835 ConstantInt::get(X->getType(), CmpVal));
2836 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00002837 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002838
Chris Lattnerf7e89612010-11-21 06:44:42 +00002839 // 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 +00002840 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00002841 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002842 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00002843 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00002844 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00002845 ConstantInt::get(X->getType(),
2846 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00002847 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002848
Chris Lattner2188e402010-01-04 07:37:31 +00002849 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002850 }
2851 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00002852 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Nick Lewycky92db8e82011-03-06 03:36:19 +00002853 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002854
Chris Lattnerf7e89612010-11-21 06:44:42 +00002855 // If all bits are known zero except for one, then we know at most one
2856 // bit is set. If the comparison is against zero, then this is a check
2857 // to see if *that* bit is set.
2858 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002859 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00002860 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00002861 Value *LHS = nullptr;
2862 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002863 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2864 LHSC->getValue() != Op0KnownZeroInverted)
2865 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002866
Chris Lattnerf7e89612010-11-21 06:44:42 +00002867 // 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 +00002868 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002869 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00002870 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002871 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00002872 APInt ValToCheck = Op0KnownZeroInverted;
2873 if (ValToCheck.isPowerOf2()) {
2874 unsigned CmpVal = ValToCheck.countTrailingZeros();
2875 return new ICmpInst(ICmpInst::ICMP_EQ, X,
2876 ConstantInt::get(X->getType(), CmpVal));
2877 } else if ((++ValToCheck).isPowerOf2()) {
2878 unsigned CmpVal = ValToCheck.countTrailingZeros();
2879 return new ICmpInst(ICmpInst::ICMP_ULT, X,
2880 ConstantInt::get(X->getType(), CmpVal));
2881 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00002882 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002883
Chris Lattnerf7e89612010-11-21 06:44:42 +00002884 // 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 +00002885 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00002886 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002887 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00002888 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00002889 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00002890 ConstantInt::get(X->getType(),
2891 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00002892 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002893
Chris Lattner2188e402010-01-04 07:37:31 +00002894 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00002895 }
Chris Lattner2188e402010-01-04 07:37:31 +00002896 case ICmpInst::ICMP_ULT:
2897 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002898 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002899 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002900 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002901 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
2902 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2903 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2904 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
2905 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002906 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002907
2908 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
2909 if (CI->isMinValue(true))
2910 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2911 Constant::getAllOnesValue(Op0->getType()));
2912 }
2913 break;
2914 case ICmpInst::ICMP_UGT:
2915 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002916 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002917 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002918 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002919
2920 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
2921 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2922 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2923 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
2924 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002925 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002926
2927 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
2928 if (CI->isMaxValue(true))
2929 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2930 Constant::getNullValue(Op0->getType()));
2931 }
2932 break;
2933 case ICmpInst::ICMP_SLT:
2934 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002935 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002936 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002937 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002938 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
2939 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2940 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2941 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
2942 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002943 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002944 }
2945 break;
2946 case ICmpInst::ICMP_SGT:
2947 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002948 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002949 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002950 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002951
2952 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
2953 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2954 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2955 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
2956 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00002957 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00002958 }
2959 break;
2960 case ICmpInst::ICMP_SGE:
2961 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2962 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002963 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002964 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002965 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002966 break;
2967 case ICmpInst::ICMP_SLE:
2968 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2969 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002970 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002971 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002972 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002973 break;
2974 case ICmpInst::ICMP_UGE:
2975 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2976 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002977 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002978 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002979 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002980 break;
2981 case ICmpInst::ICMP_ULE:
2982 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2983 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002984 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002985 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Nick Lewycky92db8e82011-03-06 03:36:19 +00002986 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002987 break;
2988 }
2989
2990 // Turn a signed comparison into an unsigned one if both operands
2991 // are known to have the same sign.
2992 if (I.isSigned() &&
2993 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2994 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2995 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2996 }
2997
2998 // Test if the ICmpInst instruction is used exclusively by a select as
2999 // part of a minimum or maximum operation. If so, refrain from doing
3000 // any other folding. This helps out other analyses which understand
3001 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3002 // and CodeGen. And in this case, at least one of the comparison
3003 // operands has at least one user besides the compare (the select),
3004 // which would often largely negate the benefit of folding anyway.
3005 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003006 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003007 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3008 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003009 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003010
3011 // See if we are doing a comparison between a constant and an instruction that
3012 // can be folded into the comparison.
3013 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003014 // Since the RHS is a ConstantInt (CI), if the left hand side is an
3015 // instruction, see if that instruction also has constants so that the
3016 // instruction can be folded into the icmp
Chris Lattner2188e402010-01-04 07:37:31 +00003017 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3018 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
3019 return Res;
3020 }
3021
3022 // Handle icmp with constant (but not simple integer constant) RHS
3023 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3024 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3025 switch (LHSI->getOpcode()) {
3026 case Instruction::GetElementPtr:
3027 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3028 if (RHSC->isNullValue() &&
3029 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3030 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3031 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3032 break;
3033 case Instruction::PHI:
3034 // Only fold icmp into the PHI if the phi and icmp are in the same
3035 // block. If in the same block, we're encouraging jump threading. If
3036 // not, we are just pessimizing the code by making an i1 phi.
3037 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003038 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003039 return NV;
3040 break;
3041 case Instruction::Select: {
3042 // If either operand of the select is a constant, we can fold the
3043 // comparison into the select arms, which will cause one to be
3044 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003045 Value *Op1 = nullptr, *Op2 = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003046 ConstantInt *CI = 0;
3047 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003048 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003049 CI = dyn_cast<ConstantInt>(Op1);
3050 }
3051 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003052 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003053 CI = dyn_cast<ConstantInt>(Op2);
3054 }
Chris Lattner2188e402010-01-04 07:37:31 +00003055
3056 // We only want to perform this transformation if it will not lead to
3057 // additional code. This is true if either both sides of the select
3058 // fold to a constant (in which case the icmp is replaced with a select
3059 // which will usually simplify) or this is the only user of the
3060 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003061 // select+icmp) or all uses of the select can be replaced based on
3062 // dominance information ("Global cases").
3063 bool Transform = false;
3064 if (Op1 && Op2)
3065 Transform = true;
3066 else if (Op1 || Op2) {
3067 // Local case
3068 if (LHSI->hasOneUse())
3069 Transform = true;
3070 // Global cases
3071 else if (CI && !CI->isZero())
3072 // When Op1 is constant try replacing select with second operand.
3073 // Otherwise Op2 is constant and try replacing select with first
3074 // operand.
3075 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3076 Op1 ? 2 : 1);
3077 }
3078 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003079 if (!Op1)
3080 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3081 RHSC, I.getName());
3082 if (!Op2)
3083 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3084 RHSC, I.getName());
3085 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3086 }
3087 break;
3088 }
Chris Lattner2188e402010-01-04 07:37:31 +00003089 case Instruction::IntToPtr:
3090 // icmp pred inttoptr(X), null -> icmp pred X, 0
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003091 if (RHSC->isNullValue() && DL &&
3092 DL->getIntPtrType(RHSC->getType()) ==
Chris Lattner2188e402010-01-04 07:37:31 +00003093 LHSI->getOperand(0)->getType())
3094 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3095 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3096 break;
3097
3098 case Instruction::Load:
3099 // Try to optimize things like "A[i] > 4" to index computations.
3100 if (GetElementPtrInst *GEP =
3101 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3102 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3103 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3104 !cast<LoadInst>(LHSI)->isVolatile())
3105 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3106 return Res;
3107 }
3108 break;
3109 }
3110 }
3111
3112 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3113 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
3114 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
3115 return NI;
3116 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
3117 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
3118 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3119 return NI;
3120
3121 // Test to see if the operands of the icmp are casted versions of other
3122 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3123 // now.
3124 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003125 if (Op0->getType()->isPointerTy() &&
3126 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003127 // We keep moving the cast from the left operand over to the right
3128 // operand, where it can often be eliminated completely.
3129 Op0 = CI->getOperand(0);
3130
3131 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3132 // so eliminate it as well.
3133 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3134 Op1 = CI2->getOperand(0);
3135
3136 // If Op1 is a constant, we can fold the cast into the constant.
3137 if (Op0->getType() != Op1->getType()) {
3138 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3139 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3140 } else {
3141 // Otherwise, cast the RHS right before the icmp
3142 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3143 }
3144 }
3145 return new ICmpInst(I.getPredicate(), Op0, Op1);
3146 }
3147 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003148
Chris Lattner2188e402010-01-04 07:37:31 +00003149 if (isa<CastInst>(Op0)) {
3150 // Handle the special case of: icmp (cast bool to X), <cst>
3151 // This comes up when you have code like
3152 // int X = A < B;
3153 // if (X) ...
3154 // For generality, we handle any zero-extension of any operand comparison
3155 // with a constant or another cast from the same type.
3156 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
3157 if (Instruction *R = visitICmpInstWithCastAndCast(I))
3158 return R;
3159 }
Chris Lattner2188e402010-01-04 07:37:31 +00003160
Duncan Sandse5220012011-02-17 07:46:37 +00003161 // Special logic for binary operators.
3162 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3163 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3164 if (BO0 || BO1) {
3165 CmpInst::Predicate Pred = I.getPredicate();
3166 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3167 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3168 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3169 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3170 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3171 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3172 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3173 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3174 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3175
3176 // Analyze the case when either Op0 or Op1 is an add instruction.
3177 // 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 +00003178 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandse5220012011-02-17 07:46:37 +00003179 if (BO0 && BO0->getOpcode() == Instruction::Add)
3180 A = BO0->getOperand(0), B = BO0->getOperand(1);
3181 if (BO1 && BO1->getOpcode() == Instruction::Add)
3182 C = BO1->getOperand(0), D = BO1->getOperand(1);
3183
David Majnemer549f4f22014-11-01 09:09:51 +00003184 // icmp (X+cst) < 0 --> X < -cst
3185 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3186 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3187 if (!RHSC->isMinValue(/*isSigned=*/true))
3188 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3189
Duncan Sandse5220012011-02-17 07:46:37 +00003190 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3191 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3192 return new ICmpInst(Pred, A == Op1 ? B : A,
3193 Constant::getNullValue(Op1->getType()));
3194
3195 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3196 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3197 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3198 C == Op0 ? D : C);
3199
Duncan Sands84653b32011-02-18 16:25:37 +00003200 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003201 if (A && C && (A == C || A == D || B == C || B == D) &&
3202 NoOp0WrapProblem && NoOp1WrapProblem &&
3203 // Try not to increase register pressure.
3204 BO0->hasOneUse() && BO1->hasOneUse()) {
3205 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003206 Value *Y, *Z;
3207 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003208 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003209 Y = B;
3210 Z = D;
3211 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003212 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003213 Y = B;
3214 Z = C;
3215 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003216 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003217 Y = A;
3218 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003219 } else {
3220 assert(B == D);
3221 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003222 Y = A;
3223 Z = C;
3224 }
Duncan Sandse5220012011-02-17 07:46:37 +00003225 return new ICmpInst(Pred, Y, Z);
3226 }
3227
David Majnemerb81cd632013-04-11 20:05:46 +00003228 // icmp slt (X + -1), Y -> icmp sle X, Y
3229 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3230 match(B, m_AllOnes()))
3231 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3232
3233 // icmp sge (X + -1), Y -> icmp sgt X, Y
3234 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3235 match(B, m_AllOnes()))
3236 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3237
3238 // icmp sle (X + 1), Y -> icmp slt X, Y
3239 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3240 match(B, m_One()))
3241 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3242
3243 // icmp sgt (X + 1), Y -> icmp sge X, Y
3244 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3245 match(B, m_One()))
3246 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3247
3248 // if C1 has greater magnitude than C2:
3249 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3250 // s.t. C3 = C1 - C2
3251 //
3252 // if C2 has greater magnitude than C1:
3253 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3254 // s.t. C3 = C2 - C1
3255 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3256 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3257 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3258 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3259 const APInt &AP1 = C1->getValue();
3260 const APInt &AP2 = C2->getValue();
3261 if (AP1.isNegative() == AP2.isNegative()) {
3262 APInt AP1Abs = C1->getValue().abs();
3263 APInt AP2Abs = C2->getValue().abs();
3264 if (AP1Abs.uge(AP2Abs)) {
3265 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3266 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3267 return new ICmpInst(Pred, NewAdd, C);
3268 } else {
3269 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3270 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3271 return new ICmpInst(Pred, A, NewAdd);
3272 }
3273 }
3274 }
3275
3276
Duncan Sandse5220012011-02-17 07:46:37 +00003277 // Analyze the case when either Op0 or Op1 is a sub instruction.
3278 // 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 +00003279 A = nullptr; B = nullptr; C = nullptr; D = nullptr;
Duncan Sandse5220012011-02-17 07:46:37 +00003280 if (BO0 && BO0->getOpcode() == Instruction::Sub)
3281 A = BO0->getOperand(0), B = BO0->getOperand(1);
3282 if (BO1 && BO1->getOpcode() == Instruction::Sub)
3283 C = BO1->getOperand(0), D = BO1->getOperand(1);
3284
Duncan Sands84653b32011-02-18 16:25:37 +00003285 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3286 if (A == Op1 && NoOp0WrapProblem)
3287 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3288
3289 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3290 if (C == Op0 && NoOp1WrapProblem)
3291 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3292
3293 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003294 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3295 // Try not to increase register pressure.
3296 BO0->hasOneUse() && BO1->hasOneUse())
3297 return new ICmpInst(Pred, A, C);
3298
Duncan Sands84653b32011-02-18 16:25:37 +00003299 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3300 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3301 // Try not to increase register pressure.
3302 BO0->hasOneUse() && BO1->hasOneUse())
3303 return new ICmpInst(Pred, D, B);
3304
David Majnemer186c9422014-05-15 00:02:20 +00003305 // icmp (0-X) < cst --> x > -cst
3306 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3307 Value *X;
3308 if (match(BO0, m_Neg(m_Value(X))))
3309 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3310 if (!RHSC->isMinValue(/*isSigned=*/true))
3311 return new ICmpInst(I.getSwappedPredicate(), X,
3312 ConstantExpr::getNeg(RHSC));
3313 }
3314
Craig Topperf40110f2014-04-25 05:29:35 +00003315 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003316 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00003317 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3318 Op1 == BO0->getOperand(1))
3319 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003320 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00003321 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3322 Op0 == BO1->getOperand(1))
3323 SRem = BO1;
3324 if (SRem) {
3325 // We don't check hasOneUse to avoid increasing register pressure because
3326 // the value we use is the same value this instruction was already using.
3327 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3328 default: break;
3329 case ICmpInst::ICMP_EQ:
Nick Lewycky92db8e82011-03-06 03:36:19 +00003330 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003331 case ICmpInst::ICMP_NE:
Nick Lewycky92db8e82011-03-06 03:36:19 +00003332 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003333 case ICmpInst::ICMP_SGT:
3334 case ICmpInst::ICMP_SGE:
3335 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
3336 Constant::getAllOnesValue(SRem->getType()));
3337 case ICmpInst::ICMP_SLT:
3338 case ICmpInst::ICMP_SLE:
3339 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
3340 Constant::getNullValue(SRem->getType()));
3341 }
3342 }
3343
Duncan Sandse5220012011-02-17 07:46:37 +00003344 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
3345 BO0->hasOneUse() && BO1->hasOneUse() &&
3346 BO0->getOperand(1) == BO1->getOperand(1)) {
3347 switch (BO0->getOpcode()) {
3348 default: break;
3349 case Instruction::Add:
3350 case Instruction::Sub:
3351 case Instruction::Xor:
3352 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
3353 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3354 BO1->getOperand(0));
3355 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
3356 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3357 if (CI->getValue().isSignBit()) {
3358 ICmpInst::Predicate Pred = I.isSigned()
3359 ? I.getUnsignedPredicate()
3360 : I.getSignedPredicate();
3361 return new ICmpInst(Pred, BO0->getOperand(0),
3362 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00003363 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003364
Chris Lattnerb1a15122011-07-15 06:08:15 +00003365 if (CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00003366 ICmpInst::Predicate Pred = I.isSigned()
3367 ? I.getUnsignedPredicate()
3368 : I.getSignedPredicate();
3369 Pred = I.getSwappedPredicate(Pred);
3370 return new ICmpInst(Pred, BO0->getOperand(0),
3371 BO1->getOperand(0));
3372 }
Chris Lattner2188e402010-01-04 07:37:31 +00003373 }
Duncan Sandse5220012011-02-17 07:46:37 +00003374 break;
3375 case Instruction::Mul:
3376 if (!I.isEquality())
3377 break;
3378
3379 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
3380 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
3381 // Mask = -1 >> count-trailing-zeros(Cst).
3382 if (!CI->isZero() && !CI->isOne()) {
3383 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003384 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00003385 APInt::getLowBitsSet(AP.getBitWidth(),
3386 AP.getBitWidth() -
3387 AP.countTrailingZeros()));
3388 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
3389 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
3390 return new ICmpInst(I.getPredicate(), And1, And2);
3391 }
3392 }
3393 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00003394 case Instruction::UDiv:
3395 case Instruction::LShr:
3396 if (I.isSigned())
3397 break;
3398 // fall-through
3399 case Instruction::SDiv:
3400 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00003401 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00003402 break;
3403 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3404 BO1->getOperand(0));
3405 case Instruction::Shl: {
3406 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
3407 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
3408 if (!NUW && !NSW)
3409 break;
3410 if (!NSW && I.isSigned())
3411 break;
3412 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
3413 BO1->getOperand(0));
3414 }
Chris Lattner2188e402010-01-04 07:37:31 +00003415 }
3416 }
3417 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003418
Chris Lattner2188e402010-01-04 07:37:31 +00003419 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00003420 // Transform (A & ~B) == 0 --> (A & B) != 0
3421 // and (A & ~B) != 0 --> (A & B) == 0
3422 // if A is a power of 2.
3423 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00003424 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A, false,
3425 0, AT, &I, DT) &&
3426 I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00003427 return new ICmpInst(I.getInversePredicate(),
3428 Builder->CreateAnd(A, B),
3429 Op1);
3430
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00003431 // ~x < ~y --> y < x
3432 // ~x < cst --> ~cst < x
3433 if (match(Op0, m_Not(m_Value(A)))) {
3434 if (match(Op1, m_Not(m_Value(B))))
3435 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00003436 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00003437 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
3438 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003439
3440 // (a+b) <u a --> llvm.uadd.with.overflow.
3441 // (a+b) <u b --> llvm.uadd.with.overflow.
3442 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
Jim Grosbach129c52a2011-09-30 18:09:53 +00003443 match(Op0, m_Add(m_Value(A), m_Value(B))) &&
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003444 (Op1 == A || Op1 == B))
3445 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
3446 return R;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003447
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003448 // a >u (a+b) --> llvm.uadd.with.overflow.
3449 // b >u (a+b) --> llvm.uadd.with.overflow.
3450 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
3451 match(Op1, m_Add(m_Value(A), m_Value(B))) &&
3452 (Op0 == A || Op0 == B))
3453 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
3454 return R;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00003455
3456 // (zext a) * (zext b) --> llvm.umul.with.overflow.
3457 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3458 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
3459 return R;
3460 }
3461 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
3462 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
3463 return R;
3464 }
Chris Lattner2188e402010-01-04 07:37:31 +00003465 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003466
Chris Lattner2188e402010-01-04 07:37:31 +00003467 if (I.isEquality()) {
3468 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00003469
Chris Lattner2188e402010-01-04 07:37:31 +00003470 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3471 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
3472 Value *OtherVal = A == Op1 ? B : A;
3473 return new ICmpInst(I.getPredicate(), OtherVal,
3474 Constant::getNullValue(A->getType()));
3475 }
3476
3477 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
3478 // A^c1 == C^c2 --> A == C^(c1^c2)
3479 ConstantInt *C1, *C2;
3480 if (match(B, m_ConstantInt(C1)) &&
3481 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00003482 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003483 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00003484 return new ICmpInst(I.getPredicate(), A, Xor);
3485 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003486
Chris Lattner2188e402010-01-04 07:37:31 +00003487 // A^B == A^D -> B == D
3488 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
3489 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
3490 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
3491 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
3492 }
3493 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003494
Chris Lattner2188e402010-01-04 07:37:31 +00003495 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3496 (A == Op0 || B == Op0)) {
3497 // A == (A^B) -> B == 0
3498 Value *OtherVal = A == Op0 ? B : A;
3499 return new ICmpInst(I.getPredicate(), OtherVal,
3500 Constant::getNullValue(A->getType()));
3501 }
3502
Chris Lattner2188e402010-01-04 07:37:31 +00003503 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00003504 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00003505 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00003506 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003507
Chris Lattner2188e402010-01-04 07:37:31 +00003508 if (A == C) {
3509 X = B; Y = D; Z = A;
3510 } else if (A == D) {
3511 X = B; Y = C; Z = A;
3512 } else if (B == C) {
3513 X = A; Y = D; Z = B;
3514 } else if (B == D) {
3515 X = A; Y = C; Z = B;
3516 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003517
Chris Lattner2188e402010-01-04 07:37:31 +00003518 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003519 Op1 = Builder->CreateXor(X, Y);
3520 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00003521 I.setOperand(0, Op1);
3522 I.setOperand(1, Constant::getNullValue(Op1->getType()));
3523 return &I;
3524 }
3525 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003526
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003527 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00003528 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003529 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00003530 if ((Op0->hasOneUse() &&
3531 match(Op0, m_ZExt(m_Value(A))) &&
3532 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
3533 (Op1->hasOneUse() &&
3534 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
3535 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00003536 APInt Pow2 = Cst1->getValue() + 1;
3537 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
3538 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
3539 return new ICmpInst(I.getPredicate(), A,
3540 Builder->CreateTrunc(B, A->getType()));
3541 }
3542
Benjamin Kramer03f3e242013-11-16 16:00:48 +00003543 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
3544 // For lshr and ashr pairs.
3545 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3546 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
3547 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
3548 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
3549 unsigned TypeBits = Cst1->getBitWidth();
3550 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
3551 if (ShAmt < TypeBits && ShAmt != 0) {
3552 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
3553 ? ICmpInst::ICMP_UGE
3554 : ICmpInst::ICMP_ULT;
3555 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
3556 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
3557 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
3558 }
3559 }
3560
Chris Lattner1b06c712011-04-26 20:18:20 +00003561 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
3562 // "icmp (and X, mask), cst"
3563 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00003564 if (Op0->hasOneUse() &&
3565 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
3566 m_ConstantInt(ShAmt))))) &&
3567 match(Op1, m_ConstantInt(Cst1)) &&
3568 // Only do this when A has multiple uses. This is most important to do
3569 // when it exposes other optimizations.
3570 !A->hasOneUse()) {
3571 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003572
Chris Lattner1b06c712011-04-26 20:18:20 +00003573 if (ShAmt < ASize) {
3574 APInt MaskV =
3575 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
3576 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003577
Chris Lattner1b06c712011-04-26 20:18:20 +00003578 APInt CmpV = Cst1->getValue().zext(ASize);
3579 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003580
Chris Lattner1b06c712011-04-26 20:18:20 +00003581 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
3582 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
3583 }
3584 }
Chris Lattner2188e402010-01-04 07:37:31 +00003585 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003586
David Majnemerc1eca5a2014-11-06 23:23:30 +00003587 // The 'cmpxchg' instruction returns an aggregate containing the old value and
3588 // an i1 which indicates whether or not we successfully did the swap.
3589 //
3590 // Replace comparisons between the old value and the expected value with the
3591 // indicator that 'cmpxchg' returns.
3592 //
3593 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
3594 // spuriously fail. In those cases, the old value may equal the expected
3595 // value but it is possible for the swap to not occur.
3596 if (I.getPredicate() == ICmpInst::ICMP_EQ)
3597 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
3598 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
3599 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
3600 !ACXI->isWeak())
3601 return ExtractValueInst::Create(ACXI, 1);
3602
Chris Lattner2188e402010-01-04 07:37:31 +00003603 {
3604 Value *X; ConstantInt *Cst;
3605 // icmp X+Cst, X
3606 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003607 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003608
3609 // icmp X, X+Cst
3610 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Benjamin Kramer0e2d1622013-09-20 22:12:42 +00003611 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00003612 }
Craig Topperf40110f2014-04-25 05:29:35 +00003613 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003614}
3615
Chris Lattner2188e402010-01-04 07:37:31 +00003616/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
Chris Lattner2188e402010-01-04 07:37:31 +00003617Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3618 Instruction *LHSI,
3619 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00003620 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003621 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003622
Chris Lattner2188e402010-01-04 07:37:31 +00003623 // Get the width of the mantissa. We don't want to hack on conversions that
3624 // might lose information from the integer, e.g. "i64 -> float"
3625 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00003626 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003627
Chris Lattner2188e402010-01-04 07:37:31 +00003628 // Check to see that the input is converted from an integer type that is small
3629 // enough that preserves all bits. TODO: check here for "known" sign bits.
3630 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3631 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003632
Chris Lattner2188e402010-01-04 07:37:31 +00003633 // If this is a uitofp instruction, we need an extra bit to hold the sign.
3634 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3635 if (LHSUnsigned)
3636 ++InputSize;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003637
Chris Lattner2188e402010-01-04 07:37:31 +00003638 // If the conversion would lose info, don't hack on this.
3639 if ((int)InputSize > MantissaWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00003640 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003641
Chris Lattner2188e402010-01-04 07:37:31 +00003642 // Otherwise, we can potentially simplify the comparison. We know that it
3643 // will always come through as an integer value and we know the constant is
3644 // not a NAN (it would have been previously simplified).
3645 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00003646
Chris Lattner2188e402010-01-04 07:37:31 +00003647 ICmpInst::Predicate Pred;
3648 switch (I.getPredicate()) {
3649 default: llvm_unreachable("Unexpected predicate!");
3650 case FCmpInst::FCMP_UEQ:
3651 case FCmpInst::FCMP_OEQ:
3652 Pred = ICmpInst::ICMP_EQ;
3653 break;
3654 case FCmpInst::FCMP_UGT:
3655 case FCmpInst::FCMP_OGT:
3656 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3657 break;
3658 case FCmpInst::FCMP_UGE:
3659 case FCmpInst::FCMP_OGE:
3660 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3661 break;
3662 case FCmpInst::FCMP_ULT:
3663 case FCmpInst::FCMP_OLT:
3664 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3665 break;
3666 case FCmpInst::FCMP_ULE:
3667 case FCmpInst::FCMP_OLE:
3668 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3669 break;
3670 case FCmpInst::FCMP_UNE:
3671 case FCmpInst::FCMP_ONE:
3672 Pred = ICmpInst::ICMP_NE;
3673 break;
3674 case FCmpInst::FCMP_ORD:
Jakub Staszakbddea112013-06-06 20:18:46 +00003675 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003676 case FCmpInst::FCMP_UNO:
Jakub Staszakbddea112013-06-06 20:18:46 +00003677 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003678 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003679
Chris Lattner229907c2011-07-18 04:54:35 +00003680 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003681
Chris Lattner2188e402010-01-04 07:37:31 +00003682 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003683
Chris Lattner2188e402010-01-04 07:37:31 +00003684 // See if the FP constant is too large for the integer. For example,
3685 // comparing an i8 to 300.0.
3686 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003687
Chris Lattner2188e402010-01-04 07:37:31 +00003688 if (!LHSUnsigned) {
3689 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
3690 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003691 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003692 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3693 APFloat::rmNearestTiesToEven);
3694 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
3695 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
3696 Pred == ICmpInst::ICMP_SLE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003697 return ReplaceInstUsesWith(I, Builder->getTrue());
3698 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003699 }
3700 } else {
3701 // If the RHS value is > UnsignedMax, fold the comparison. This handles
3702 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00003703 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003704 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3705 APFloat::rmNearestTiesToEven);
3706 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
3707 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
3708 Pred == ICmpInst::ICMP_ULE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003709 return ReplaceInstUsesWith(I, Builder->getTrue());
3710 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003711 }
3712 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003713
Chris Lattner2188e402010-01-04 07:37:31 +00003714 if (!LHSUnsigned) {
3715 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003716 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00003717 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3718 APFloat::rmNearestTiesToEven);
3719 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3720 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3721 Pred == ICmpInst::ICMP_SGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003722 return ReplaceInstUsesWith(I, Builder->getTrue());
3723 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003724 }
Devang Patel698452b2012-02-13 23:05:18 +00003725 } else {
3726 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00003727 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00003728 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3729 APFloat::rmNearestTiesToEven);
3730 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3731 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3732 Pred == ICmpInst::ICMP_UGE)
Jakub Staszakbddea112013-06-06 20:18:46 +00003733 return ReplaceInstUsesWith(I, Builder->getTrue());
3734 return ReplaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00003735 }
Chris Lattner2188e402010-01-04 07:37:31 +00003736 }
3737
3738 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3739 // [0, UMAX], but it may still be fractional. See if it is fractional by
3740 // casting the FP value to the integer value and back, checking for equality.
3741 // Don't do this for zero, because -0.0 is not fractional.
3742 Constant *RHSInt = LHSUnsigned
3743 ? ConstantExpr::getFPToUI(RHSC, IntTy)
3744 : ConstantExpr::getFPToSI(RHSC, IntTy);
3745 if (!RHS.isZero()) {
3746 bool Equal = LHSUnsigned
3747 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3748 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3749 if (!Equal) {
3750 // If we had a comparison against a fractional value, we have to adjust
3751 // the compare predicate and sometimes the value. RHSC is rounded towards
3752 // zero at this point.
3753 switch (Pred) {
3754 default: llvm_unreachable("Unexpected integer comparison!");
3755 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Jakub Staszakbddea112013-06-06 20:18:46 +00003756 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003757 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Jakub Staszakbddea112013-06-06 20:18:46 +00003758 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003759 case ICmpInst::ICMP_ULE:
3760 // (float)int <= 4.4 --> int <= 4
3761 // (float)int <= -4.4 --> false
3762 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003763 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003764 break;
3765 case ICmpInst::ICMP_SLE:
3766 // (float)int <= 4.4 --> int <= 4
3767 // (float)int <= -4.4 --> int < -4
3768 if (RHS.isNegative())
3769 Pred = ICmpInst::ICMP_SLT;
3770 break;
3771 case ICmpInst::ICMP_ULT:
3772 // (float)int < -4.4 --> false
3773 // (float)int < 4.4 --> int <= 4
3774 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003775 return ReplaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00003776 Pred = ICmpInst::ICMP_ULE;
3777 break;
3778 case ICmpInst::ICMP_SLT:
3779 // (float)int < -4.4 --> int < -4
3780 // (float)int < 4.4 --> int <= 4
3781 if (!RHS.isNegative())
3782 Pred = ICmpInst::ICMP_SLE;
3783 break;
3784 case ICmpInst::ICMP_UGT:
3785 // (float)int > 4.4 --> int > 4
3786 // (float)int > -4.4 --> true
3787 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003788 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003789 break;
3790 case ICmpInst::ICMP_SGT:
3791 // (float)int > 4.4 --> int > 4
3792 // (float)int > -4.4 --> int >= -4
3793 if (RHS.isNegative())
3794 Pred = ICmpInst::ICMP_SGE;
3795 break;
3796 case ICmpInst::ICMP_UGE:
3797 // (float)int >= -4.4 --> true
3798 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00003799 if (RHS.isNegative())
Jakub Staszakbddea112013-06-06 20:18:46 +00003800 return ReplaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00003801 Pred = ICmpInst::ICMP_UGT;
3802 break;
3803 case ICmpInst::ICMP_SGE:
3804 // (float)int >= -4.4 --> int >= -4
3805 // (float)int >= 4.4 --> int > 4
3806 if (!RHS.isNegative())
3807 Pred = ICmpInst::ICMP_SGT;
3808 break;
3809 }
3810 }
3811 }
3812
3813 // Lower this FP comparison into an appropriate integer version of the
3814 // comparison.
3815 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3816}
3817
3818Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3819 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003820
Chris Lattner2188e402010-01-04 07:37:31 +00003821 /// Orders the operands of the compare so that they are listed from most
3822 /// complex to least complex. This puts constants before unary operators,
3823 /// before binary operators.
3824 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3825 I.swapOperands();
3826 Changed = true;
3827 }
3828
3829 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003830
Hal Finkel60db0582014-09-07 18:57:58 +00003831 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AT))
Chris Lattner2188e402010-01-04 07:37:31 +00003832 return ReplaceInstUsesWith(I, V);
3833
3834 // Simplify 'fcmp pred X, X'
3835 if (Op0 == Op1) {
3836 switch (I.getPredicate()) {
3837 default: llvm_unreachable("Unknown predicate!");
3838 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
3839 case FCmpInst::FCMP_ULT: // True if unordered or less than
3840 case FCmpInst::FCMP_UGT: // True if unordered or greater than
3841 case FCmpInst::FCMP_UNE: // True if unordered or not equal
3842 // Canonicalize these to be 'fcmp uno %X, 0.0'.
3843 I.setPredicate(FCmpInst::FCMP_UNO);
3844 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3845 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003846
Chris Lattner2188e402010-01-04 07:37:31 +00003847 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
3848 case FCmpInst::FCMP_OEQ: // True if ordered and equal
3849 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
3850 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
3851 // Canonicalize these to be 'fcmp ord %X, 0.0'.
3852 I.setPredicate(FCmpInst::FCMP_ORD);
3853 I.setOperand(1, Constant::getNullValue(Op0->getType()));
3854 return &I;
3855 }
3856 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003857
Chris Lattner2188e402010-01-04 07:37:31 +00003858 // Handle fcmp with constant RHS
3859 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3860 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3861 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003862 case Instruction::FPExt: {
3863 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3864 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3865 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3866 if (!RHSF)
3867 break;
3868
3869 const fltSemantics *Sem;
3870 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00003871 if (LHSExt->getSrcTy()->isHalfTy())
3872 Sem = &APFloat::IEEEhalf;
3873 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003874 Sem = &APFloat::IEEEsingle;
3875 else if (LHSExt->getSrcTy()->isDoubleTy())
3876 Sem = &APFloat::IEEEdouble;
3877 else if (LHSExt->getSrcTy()->isFP128Ty())
3878 Sem = &APFloat::IEEEquad;
3879 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3880 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00003881 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3882 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003883 else
3884 break;
3885
3886 bool Lossy;
3887 APFloat F = RHSF->getValueAPF();
3888 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3889
Jim Grosbach24ff8342011-09-30 18:45:50 +00003890 // Avoid lossy conversions and denormals. Zero is a special case
3891 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00003892 APFloat Fabs = F;
3893 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003894 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00003895 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3896 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00003897
Benjamin Kramercbb18e92011-03-31 10:12:07 +00003898 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3899 ConstantFP::get(RHSC->getContext(), F));
3900 break;
3901 }
Chris Lattner2188e402010-01-04 07:37:31 +00003902 case Instruction::PHI:
3903 // Only fold fcmp into the PHI if the phi and fcmp are in the same
3904 // block. If in the same block, we're encouraging jump threading. If
3905 // not, we are just pessimizing the code by making an i1 phi.
3906 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003907 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003908 return NV;
3909 break;
3910 case Instruction::SIToFP:
3911 case Instruction::UIToFP:
3912 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3913 return NV;
3914 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00003915 case Instruction::FSub: {
3916 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3917 Value *Op;
3918 if (match(LHSI, m_FNeg(m_Value(Op))))
3919 return new FCmpInst(I.getSwappedPredicate(), Op,
3920 ConstantExpr::getFNeg(RHSC));
3921 break;
3922 }
Dan Gohman94732022010-02-24 06:46:09 +00003923 case Instruction::Load:
3924 if (GetElementPtrInst *GEP =
3925 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3926 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3927 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3928 !cast<LoadInst>(LHSI)->isVolatile())
3929 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3930 return Res;
3931 }
3932 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00003933 case Instruction::Call: {
3934 CallInst *CI = cast<CallInst>(LHSI);
3935 LibFunc::Func Func;
3936 // Various optimization for fabs compared with zero.
Benjamin Kramer9d032422012-08-18 22:04:34 +00003937 if (RHSC->isNullValue() && CI->getCalledFunction() &&
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00003938 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3939 TLI->has(Func)) {
3940 if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3941 Func == LibFunc::fabsl) {
3942 switch (I.getPredicate()) {
3943 default: break;
3944 // fabs(x) < 0 --> false
3945 case FCmpInst::FCMP_OLT:
3946 return ReplaceInstUsesWith(I, Builder->getFalse());
3947 // fabs(x) > 0 --> x != 0
3948 case FCmpInst::FCMP_OGT:
3949 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3950 RHSC);
3951 // fabs(x) <= 0 --> x == 0
3952 case FCmpInst::FCMP_OLE:
3953 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3954 RHSC);
3955 // fabs(x) >= 0 --> !isnan(x)
3956 case FCmpInst::FCMP_OGE:
3957 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3958 RHSC);
3959 // fabs(x) == 0 --> x == 0
3960 // fabs(x) != 0 --> x != 0
3961 case FCmpInst::FCMP_OEQ:
3962 case FCmpInst::FCMP_UEQ:
3963 case FCmpInst::FCMP_ONE:
3964 case FCmpInst::FCMP_UNE:
3965 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3966 RHSC);
3967 }
3968 }
3969 }
3970 }
Chris Lattner2188e402010-01-04 07:37:31 +00003971 }
Chris Lattner2188e402010-01-04 07:37:31 +00003972 }
3973
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00003974 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00003975 Value *X, *Y;
3976 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00003977 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00003978
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00003979 // fcmp (fpext x), (fpext y) -> fcmp x, y
3980 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3981 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3982 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3983 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3984 RHSExt->getOperand(0));
3985
Craig Topperf40110f2014-04-25 05:29:35 +00003986 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003987}