blob: 5eb832530b7574f211ee19a27a92ab0f3ce86e7f [file] [log] [blame]
Chris Lattner2188e402010-01-04 07:37:31 +00001//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitICmp and visitFCmp functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Matt Arsenault55e73122015-01-06 15:50:59 +000015#include "llvm/ADT/APSInt.h"
Silviu Barangaf29dfd32016-01-15 15:52:05 +000016#include "llvm/ADT/SetVector.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000017#include "llvm/ADT/Statistic.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000018#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000019#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/MemoryBuiltins.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000025#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000027#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000028#include "llvm/Support/Debug.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000029
Chris Lattner2188e402010-01-04 07:37:31 +000030using namespace llvm;
31using namespace PatternMatch;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "instcombine"
34
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000035// How many times is a select replaced by one of its operands?
36STATISTIC(NumSel, "Number of select opts");
37
38// Initialization Routines
39
Chris Lattner98457102011-02-10 05:23:05 +000040static ConstantInt *getOne(Constant *C) {
41 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
42}
43
Chris Lattner2188e402010-01-04 07:37:31 +000044static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
45 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
46}
47
48static bool HasAddOverflow(ConstantInt *Result,
49 ConstantInt *In1, ConstantInt *In2,
50 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000051 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000052 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000053
54 if (In2->isNegative())
55 return Result->getValue().sgt(In1->getValue());
56 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000057}
58
Sanjay Patel5f0217f2016-06-05 16:46:18 +000059/// Compute Result = In1+In2, returning true if the result overflowed for this
60/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000061static bool AddWithOverflow(Constant *&Result, Constant *In1,
62 Constant *In2, bool IsSigned = false) {
63 Result = ConstantExpr::getAdd(In1, In2);
64
Chris Lattner229907c2011-07-18 04:54:35 +000065 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000066 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
67 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
68 if (HasAddOverflow(ExtractElement(Result, Idx),
69 ExtractElement(In1, Idx),
70 ExtractElement(In2, Idx),
71 IsSigned))
72 return true;
73 }
74 return false;
75 }
76
77 return HasAddOverflow(cast<ConstantInt>(Result),
78 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
79 IsSigned);
80}
81
82static bool HasSubOverflow(ConstantInt *Result,
83 ConstantInt *In1, ConstantInt *In2,
84 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000085 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000086 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000087
Chris Lattnerb1a15122011-07-15 06:08:15 +000088 if (In2->isNegative())
89 return Result->getValue().slt(In1->getValue());
90
91 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000092}
93
Sanjay Patel5f0217f2016-06-05 16:46:18 +000094/// Compute Result = In1-In2, returning true if the result overflowed for this
95/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000096static bool SubWithOverflow(Constant *&Result, Constant *In1,
97 Constant *In2, bool IsSigned = false) {
98 Result = ConstantExpr::getSub(In1, In2);
99
Chris Lattner229907c2011-07-18 04:54:35 +0000100 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +0000101 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
102 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
103 if (HasSubOverflow(ExtractElement(Result, Idx),
104 ExtractElement(In1, Idx),
105 ExtractElement(In2, Idx),
106 IsSigned))
107 return true;
108 }
109 return false;
110 }
111
112 return HasSubOverflow(cast<ConstantInt>(Result),
113 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
114 IsSigned);
115}
116
Balaram Makam569eaec2016-05-04 21:32:14 +0000117/// Given an icmp instruction, return true if any use of this comparison is a
118/// branch on sign bit comparison.
119static bool isBranchOnSignBitCheck(ICmpInst &I, bool isSignBit) {
120 for (auto *U : I.users())
121 if (isa<BranchInst>(U))
122 return isSignBit;
123 return false;
124}
125
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000126/// Given an exploded icmp instruction, return true if the comparison only
127/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the
128/// result of the comparison is true when the input value is signed.
129static bool isSignBitCheck(ICmpInst::Predicate Pred, ConstantInt *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000130 bool &TrueIfSigned) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000131 switch (Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000132 case ICmpInst::ICMP_SLT: // True if LHS s< 0
133 TrueIfSigned = true;
134 return RHS->isZero();
135 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
136 TrueIfSigned = true;
137 return RHS->isAllOnesValue();
138 case ICmpInst::ICMP_SGT: // True if LHS s> -1
139 TrueIfSigned = false;
140 return RHS->isAllOnesValue();
141 case ICmpInst::ICMP_UGT:
142 // True if LHS u> RHS and RHS == high-bit-mask - 1
143 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000144 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000145 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000146 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
147 TrueIfSigned = true;
148 return RHS->getValue().isSignBit();
149 default:
150 return false;
151 }
152}
153
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000154/// Returns true if the exploded icmp can be expressed as a signed comparison
155/// to zero and updates the predicate accordingly.
156/// The signedness of the comparison is preserved.
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000157static bool isSignTest(ICmpInst::Predicate &Pred, const ConstantInt *RHS) {
158 if (!ICmpInst::isSigned(Pred))
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000159 return false;
160
161 if (RHS->isZero())
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000162 return ICmpInst::isRelational(Pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000163
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000164 if (RHS->isOne()) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000165 if (Pred == ICmpInst::ICMP_SLT) {
166 Pred = ICmpInst::ICMP_SLE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000167 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000168 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000169 } else if (RHS->isAllOnesValue()) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000170 if (Pred == ICmpInst::ICMP_SGT) {
171 Pred = ICmpInst::ICMP_SGE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000172 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000173 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000174 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000175
176 return false;
177}
178
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000179/// Given a signed integer type and a set of known zero and one bits, compute
180/// the maximum and minimum values that could have the specified known zero and
181/// known one bits, returning them in Min/Max.
182static void ComputeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
183 const APInt &KnownOne,
184 APInt &Min, APInt &Max) {
Chris Lattner2188e402010-01-04 07:37:31 +0000185 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
186 KnownZero.getBitWidth() == Min.getBitWidth() &&
187 KnownZero.getBitWidth() == Max.getBitWidth() &&
188 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
189 APInt UnknownBits = ~(KnownZero|KnownOne);
190
191 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
192 // bit if it is unknown.
193 Min = KnownOne;
194 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000195
Chris Lattner2188e402010-01-04 07:37:31 +0000196 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000197 Min.setBit(Min.getBitWidth()-1);
198 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000199 }
200}
201
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000202/// Given an unsigned integer type and a set of known zero and one bits, compute
203/// the maximum and minimum values that could have the specified known zero and
204/// known one bits, returning them in Min/Max.
Chris Lattner2188e402010-01-04 07:37:31 +0000205static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
206 const APInt &KnownOne,
207 APInt &Min, APInt &Max) {
208 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
209 KnownZero.getBitWidth() == Min.getBitWidth() &&
210 KnownZero.getBitWidth() == Max.getBitWidth() &&
211 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
212 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000213
Chris Lattner2188e402010-01-04 07:37:31 +0000214 // The minimum value is when the unknown bits are all zeros.
215 Min = KnownOne;
216 // The maximum value is when the unknown bits are all ones.
217 Max = KnownOne|UnknownBits;
218}
219
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000220/// This is called when we see this pattern:
Chris Lattner2188e402010-01-04 07:37:31 +0000221/// cmp pred (load (gep GV, ...)), cmpcst
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000222/// 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
Chris Lattner2188e402010-01-04 07:37:31 +0000224/// 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
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000227/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Sanjay Patel43395062016-07-21 18:07:40 +0000228Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
229 GlobalVariable *GV,
230 CmpInst &ICI,
231 ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000232 Constant *Init = GV->getInitializer();
233 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000234 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000235
Chris Lattnerfe741762012-01-31 02:55:06 +0000236 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000237 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000238
Chris Lattner2188e402010-01-04 07:37:31 +0000239 // There are many forms of this optimization we can handle, for now, just do
240 // the simple index into a single-dimensional array.
241 //
242 // Require: GEP GV, 0, i {{, constant indices}}
243 if (GEP->getNumOperands() < 3 ||
244 !isa<ConstantInt>(GEP->getOperand(1)) ||
245 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
246 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000247 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000248
249 // Check that indices after the variable are constants and in-range for the
250 // type they index. Collect the indices. This is typically for arrays of
251 // structs.
252 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000253
Chris Lattnerfe741762012-01-31 02:55:06 +0000254 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000255 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
256 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000257 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000258
Chris Lattner2188e402010-01-04 07:37:31 +0000259 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000260 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000261
Chris Lattner229907c2011-07-18 04:54:35 +0000262 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000263 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000264 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000265 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000266 EltTy = ATy->getElementType();
267 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000268 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000269 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000270
Chris Lattner2188e402010-01-04 07:37:31 +0000271 LaterIndices.push_back(IdxVal);
272 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000273
Chris Lattner2188e402010-01-04 07:37:31 +0000274 enum { Overdefined = -3, Undefined = -2 };
275
276 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000277
Chris Lattner2188e402010-01-04 07:37:31 +0000278 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
279 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
280 // and 87 is the second (and last) index. FirstTrueElement is -2 when
281 // undefined, otherwise set to the first true element. SecondTrueElement is
282 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
283 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
284
285 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
286 // form "i != 47 & i != 87". Same state transitions as for true elements.
287 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000288
Chris Lattner2188e402010-01-04 07:37:31 +0000289 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
290 /// define a state machine that triggers for ranges of values that the index
291 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
292 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
293 /// index in the range (inclusive). We use -2 for undefined here because we
294 /// use relative comparisons and don't want 0-1 to match -1.
295 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000296
Chris Lattner2188e402010-01-04 07:37:31 +0000297 // MagicBitvector - This is a magic bitvector where we set a bit if the
298 // comparison is true for element 'i'. If there are 64 elements or less in
299 // the array, this will fully represent all the comparison results.
300 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000301
Chris Lattner2188e402010-01-04 07:37:31 +0000302 // Scan the array and see if one of our patterns matches.
303 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000304 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
305 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000306 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000307
Chris Lattner2188e402010-01-04 07:37:31 +0000308 // If this is indexing an array of structures, get the structure element.
309 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000310 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000311
Chris Lattner2188e402010-01-04 07:37:31 +0000312 // If the element is masked, handle it.
313 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000314
Chris Lattner2188e402010-01-04 07:37:31 +0000315 // Find out if the comparison would be true or false for the i'th element.
316 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Justin Bogner99798402016-08-05 01:06:44 +0000317 CompareRHS, DL, &TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000318 // If the result is undef for this element, ignore it.
319 if (isa<UndefValue>(C)) {
320 // Extend range state machines to cover this element in case there is an
321 // undef in the middle of the range.
322 if (TrueRangeEnd == (int)i-1)
323 TrueRangeEnd = i;
324 if (FalseRangeEnd == (int)i-1)
325 FalseRangeEnd = i;
326 continue;
327 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000328
Chris Lattner2188e402010-01-04 07:37:31 +0000329 // If we can't compute the result for any of the elements, we have to give
330 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000331 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000332
Chris Lattner2188e402010-01-04 07:37:31 +0000333 // Otherwise, we know if the comparison is true or false for this element,
334 // update our state machines.
335 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000336
Chris Lattner2188e402010-01-04 07:37:31 +0000337 // State machine for single/double/range index comparison.
338 if (IsTrueForElt) {
339 // Update the TrueElement state machine.
340 if (FirstTrueElement == Undefined)
341 FirstTrueElement = TrueRangeEnd = i; // First true element.
342 else {
343 // Update double-compare state machine.
344 if (SecondTrueElement == Undefined)
345 SecondTrueElement = i;
346 else
347 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000348
Chris Lattner2188e402010-01-04 07:37:31 +0000349 // Update range state machine.
350 if (TrueRangeEnd == (int)i-1)
351 TrueRangeEnd = i;
352 else
353 TrueRangeEnd = Overdefined;
354 }
355 } else {
356 // Update the FalseElement state machine.
357 if (FirstFalseElement == Undefined)
358 FirstFalseElement = FalseRangeEnd = i; // First false element.
359 else {
360 // Update double-compare state machine.
361 if (SecondFalseElement == Undefined)
362 SecondFalseElement = i;
363 else
364 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000365
Chris Lattner2188e402010-01-04 07:37:31 +0000366 // Update range state machine.
367 if (FalseRangeEnd == (int)i-1)
368 FalseRangeEnd = i;
369 else
370 FalseRangeEnd = Overdefined;
371 }
372 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000373
Chris Lattner2188e402010-01-04 07:37:31 +0000374 // If this element is in range, update our magic bitvector.
375 if (i < 64 && IsTrueForElt)
376 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000377
Chris Lattner2188e402010-01-04 07:37:31 +0000378 // If all of our states become overdefined, bail out early. Since the
379 // predicate is expensive, only check it every 8 elements. This is only
380 // really useful for really huge arrays.
381 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
382 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
383 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000384 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000385 }
386
387 // Now that we've scanned the entire array, emit our new comparison(s). We
388 // order the state machines in complexity of the generated code.
389 Value *Idx = GEP->getOperand(2);
390
Matt Arsenault5aeae182013-08-19 21:40:31 +0000391 // If the index is larger than the pointer size of the target, truncate the
392 // index down like the GEP would do implicitly. We don't have to do this for
393 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000394 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000395 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000396 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
397 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
398 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
399 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000400
Chris Lattner2188e402010-01-04 07:37:31 +0000401 // If the comparison is only true for one or two elements, emit direct
402 // comparisons.
403 if (SecondTrueElement != Overdefined) {
404 // None true -> false.
405 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000406 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000407
Chris Lattner2188e402010-01-04 07:37:31 +0000408 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000409
Chris Lattner2188e402010-01-04 07:37:31 +0000410 // True for one element -> 'i == 47'.
411 if (SecondTrueElement == Undefined)
412 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000413
Chris Lattner2188e402010-01-04 07:37:31 +0000414 // True for two elements -> 'i == 47 | i == 72'.
415 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
416 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
417 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
418 return BinaryOperator::CreateOr(C1, C2);
419 }
420
421 // If the comparison is only false for one or two elements, emit direct
422 // comparisons.
423 if (SecondFalseElement != Overdefined) {
424 // None false -> true.
425 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000426 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000427
Chris Lattner2188e402010-01-04 07:37:31 +0000428 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
429
430 // False for one element -> 'i != 47'.
431 if (SecondFalseElement == Undefined)
432 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000433
Chris Lattner2188e402010-01-04 07:37:31 +0000434 // False for two elements -> 'i != 47 & i != 72'.
435 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
436 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
437 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
438 return BinaryOperator::CreateAnd(C1, C2);
439 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000440
Chris Lattner2188e402010-01-04 07:37:31 +0000441 // If the comparison can be replaced with a range comparison for the elements
442 // where it is true, emit the range check.
443 if (TrueRangeEnd != Overdefined) {
444 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000445
Chris Lattner2188e402010-01-04 07:37:31 +0000446 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
447 if (FirstTrueElement) {
448 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
449 Idx = Builder->CreateAdd(Idx, Offs);
450 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000451
Chris Lattner2188e402010-01-04 07:37:31 +0000452 Value *End = ConstantInt::get(Idx->getType(),
453 TrueRangeEnd-FirstTrueElement+1);
454 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
455 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000456
Chris Lattner2188e402010-01-04 07:37:31 +0000457 // False range check.
458 if (FalseRangeEnd != Overdefined) {
459 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
460 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
461 if (FirstFalseElement) {
462 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
463 Idx = Builder->CreateAdd(Idx, Offs);
464 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000465
Chris Lattner2188e402010-01-04 07:37:31 +0000466 Value *End = ConstantInt::get(Idx->getType(),
467 FalseRangeEnd-FirstFalseElement);
468 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
469 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000470
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000471 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000472 // of this load, replace it with computation that does:
473 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000474 {
Craig Topperf40110f2014-04-25 05:29:35 +0000475 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000476
477 // Look for an appropriate type:
478 // - The type of Idx if the magic fits
479 // - The smallest fitting legal type if we have a DataLayout
480 // - Default to i32
481 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
482 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000483 else
484 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000485
Craig Topperf40110f2014-04-25 05:29:35 +0000486 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000487 Value *V = Builder->CreateIntCast(Idx, Ty, false);
488 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
489 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
490 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
491 }
Chris Lattner2188e402010-01-04 07:37:31 +0000492 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000493
Craig Topperf40110f2014-04-25 05:29:35 +0000494 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000495}
496
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000497/// Return a value that can be used to compare the *offset* implied by a GEP to
498/// zero. For example, if we have &A[i], we want to return 'i' for
499/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
500/// are involved. The above expression would also be legal to codegen as
501/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
502/// This latter form is less amenable to optimization though, and we are allowed
Chris Lattner2188e402010-01-04 07:37:31 +0000503/// to generate the first by knowing that pointer arithmetic doesn't overflow.
504///
505/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000506///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000507static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
508 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000509 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000510
Chris Lattner2188e402010-01-04 07:37:31 +0000511 // Check to see if this gep only has a single variable index. If so, and if
512 // any constant indices are a multiple of its scale, then we can compute this
513 // in terms of the scale of the variable index. For example, if the GEP
514 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
515 // because the expression will cross zero at the same point.
516 unsigned i, e = GEP->getNumOperands();
517 int64_t Offset = 0;
518 for (i = 1; i != e; ++i, ++GTI) {
519 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
520 // Compute the aggregate offset of constant indices.
521 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000522
Chris Lattner2188e402010-01-04 07:37:31 +0000523 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000524 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000525 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000526 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000527 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000528 Offset += Size*CI->getSExtValue();
529 }
530 } else {
531 // Found our variable index.
532 break;
533 }
534 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000535
Chris Lattner2188e402010-01-04 07:37:31 +0000536 // If there are no variable indices, we must have a constant offset, just
537 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000538 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000539
Chris Lattner2188e402010-01-04 07:37:31 +0000540 Value *VariableIdx = GEP->getOperand(i);
541 // Determine the scale factor of the variable element. For example, this is
542 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000543 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000544
Chris Lattner2188e402010-01-04 07:37:31 +0000545 // Verify that there are no other variable indices. If so, emit the hard way.
546 for (++i, ++GTI; i != e; ++i, ++GTI) {
547 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000548 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000549
Chris Lattner2188e402010-01-04 07:37:31 +0000550 // Compute the aggregate offset of constant indices.
551 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000552
Chris Lattner2188e402010-01-04 07:37:31 +0000553 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000554 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000555 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000556 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000557 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000558 Offset += Size*CI->getSExtValue();
559 }
560 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000561
Chris Lattner2188e402010-01-04 07:37:31 +0000562 // Okay, we know we have a single variable index, which must be a
563 // pointer/array/vector index. If there is no offset, life is simple, return
564 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000565 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000566 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000567 if (Offset == 0) {
568 // Cast to intptrty in case a truncation occurs. If an extension is needed,
569 // we don't need to bother extending: the extension won't affect where the
570 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000571 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000572 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
573 }
Chris Lattner2188e402010-01-04 07:37:31 +0000574 return VariableIdx;
575 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000576
Chris Lattner2188e402010-01-04 07:37:31 +0000577 // Otherwise, there is an index. The computation we will do will be modulo
578 // the pointer size, so get it.
579 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000580
Chris Lattner2188e402010-01-04 07:37:31 +0000581 Offset &= PtrSizeMask;
582 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000583
Chris Lattner2188e402010-01-04 07:37:31 +0000584 // To do this transformation, any constant index must be a multiple of the
585 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
586 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
587 // multiple of the variable scale.
588 int64_t NewOffs = Offset / (int64_t)VariableScale;
589 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000590 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000591
Chris Lattner2188e402010-01-04 07:37:31 +0000592 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000593 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000594 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
595 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000596 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000597 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000598}
599
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000600/// Returns true if we can rewrite Start as a GEP with pointer Base
601/// and some integer offset. The nodes that need to be re-written
602/// for this transformation will be added to Explored.
603static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
604 const DataLayout &DL,
605 SetVector<Value *> &Explored) {
606 SmallVector<Value *, 16> WorkList(1, Start);
607 Explored.insert(Base);
608
609 // The following traversal gives us an order which can be used
610 // when doing the final transformation. Since in the final
611 // transformation we create the PHI replacement instructions first,
612 // we don't have to get them in any particular order.
613 //
614 // However, for other instructions we will have to traverse the
615 // operands of an instruction first, which means that we have to
616 // do a post-order traversal.
617 while (!WorkList.empty()) {
618 SetVector<PHINode *> PHIs;
619
620 while (!WorkList.empty()) {
621 if (Explored.size() >= 100)
622 return false;
623
624 Value *V = WorkList.back();
625
626 if (Explored.count(V) != 0) {
627 WorkList.pop_back();
628 continue;
629 }
630
631 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
632 !isa<GEPOperator>(V) && !isa<PHINode>(V))
633 // We've found some value that we can't explore which is different from
634 // the base. Therefore we can't do this transformation.
635 return false;
636
637 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
638 auto *CI = dyn_cast<CastInst>(V);
639 if (!CI->isNoopCast(DL))
640 return false;
641
642 if (Explored.count(CI->getOperand(0)) == 0)
643 WorkList.push_back(CI->getOperand(0));
644 }
645
646 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
647 // We're limiting the GEP to having one index. This will preserve
648 // the original pointer type. We could handle more cases in the
649 // future.
650 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
651 GEP->getType() != Start->getType())
652 return false;
653
654 if (Explored.count(GEP->getOperand(0)) == 0)
655 WorkList.push_back(GEP->getOperand(0));
656 }
657
658 if (WorkList.back() == V) {
659 WorkList.pop_back();
660 // We've finished visiting this node, mark it as such.
661 Explored.insert(V);
662 }
663
664 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000665 // We cannot transform PHIs on unsplittable basic blocks.
666 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
667 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000668 Explored.insert(PN);
669 PHIs.insert(PN);
670 }
671 }
672
673 // Explore the PHI nodes further.
674 for (auto *PN : PHIs)
675 for (Value *Op : PN->incoming_values())
676 if (Explored.count(Op) == 0)
677 WorkList.push_back(Op);
678 }
679
680 // Make sure that we can do this. Since we can't insert GEPs in a basic
681 // block before a PHI node, we can't easily do this transformation if
682 // we have PHI node users of transformed instructions.
683 for (Value *Val : Explored) {
684 for (Value *Use : Val->uses()) {
685
686 auto *PHI = dyn_cast<PHINode>(Use);
687 auto *Inst = dyn_cast<Instruction>(Val);
688
689 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
690 Explored.count(PHI) == 0)
691 continue;
692
693 if (PHI->getParent() == Inst->getParent())
694 return false;
695 }
696 }
697 return true;
698}
699
700// Sets the appropriate insert point on Builder where we can add
701// a replacement Instruction for V (if that is possible).
702static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
703 bool Before = true) {
704 if (auto *PHI = dyn_cast<PHINode>(V)) {
705 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
706 return;
707 }
708 if (auto *I = dyn_cast<Instruction>(V)) {
709 if (!Before)
710 I = &*std::next(I->getIterator());
711 Builder.SetInsertPoint(I);
712 return;
713 }
714 if (auto *A = dyn_cast<Argument>(V)) {
715 // Set the insertion point in the entry block.
716 BasicBlock &Entry = A->getParent()->getEntryBlock();
717 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
718 return;
719 }
720 // Otherwise, this is a constant and we don't need to set a new
721 // insertion point.
722 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
723}
724
725/// Returns a re-written value of Start as an indexed GEP using Base as a
726/// pointer.
727static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
728 const DataLayout &DL,
729 SetVector<Value *> &Explored) {
730 // Perform all the substitutions. This is a bit tricky because we can
731 // have cycles in our use-def chains.
732 // 1. Create the PHI nodes without any incoming values.
733 // 2. Create all the other values.
734 // 3. Add the edges for the PHI nodes.
735 // 4. Emit GEPs to get the original pointers.
736 // 5. Remove the original instructions.
737 Type *IndexType = IntegerType::get(
738 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
739
740 DenseMap<Value *, Value *> NewInsts;
741 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
742
743 // Create the new PHI nodes, without adding any incoming values.
744 for (Value *Val : Explored) {
745 if (Val == Base)
746 continue;
747 // Create empty phi nodes. This avoids cyclic dependencies when creating
748 // the remaining instructions.
749 if (auto *PHI = dyn_cast<PHINode>(Val))
750 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
751 PHI->getName() + ".idx", PHI);
752 }
753 IRBuilder<> Builder(Base->getContext());
754
755 // Create all the other instructions.
756 for (Value *Val : Explored) {
757
758 if (NewInsts.find(Val) != NewInsts.end())
759 continue;
760
761 if (auto *CI = dyn_cast<CastInst>(Val)) {
762 NewInsts[CI] = NewInsts[CI->getOperand(0)];
763 continue;
764 }
765 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
766 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
767 : GEP->getOperand(1);
768 setInsertionPoint(Builder, GEP);
769 // Indices might need to be sign extended. GEPs will magically do
770 // this, but we need to do it ourselves here.
771 if (Index->getType()->getScalarSizeInBits() !=
772 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
773 Index = Builder.CreateSExtOrTrunc(
774 Index, NewInsts[GEP->getOperand(0)]->getType(),
775 GEP->getOperand(0)->getName() + ".sext");
776 }
777
778 auto *Op = NewInsts[GEP->getOperand(0)];
779 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
780 NewInsts[GEP] = Index;
781 else
782 NewInsts[GEP] = Builder.CreateNSWAdd(
783 Op, Index, GEP->getOperand(0)->getName() + ".add");
784 continue;
785 }
786 if (isa<PHINode>(Val))
787 continue;
788
789 llvm_unreachable("Unexpected instruction type");
790 }
791
792 // Add the incoming values to the PHI nodes.
793 for (Value *Val : Explored) {
794 if (Val == Base)
795 continue;
796 // All the instructions have been created, we can now add edges to the
797 // phi nodes.
798 if (auto *PHI = dyn_cast<PHINode>(Val)) {
799 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
800 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
801 Value *NewIncoming = PHI->getIncomingValue(I);
802
803 if (NewInsts.find(NewIncoming) != NewInsts.end())
804 NewIncoming = NewInsts[NewIncoming];
805
806 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
807 }
808 }
809 }
810
811 for (Value *Val : Explored) {
812 if (Val == Base)
813 continue;
814
815 // Depending on the type, for external users we have to emit
816 // a GEP or a GEP + ptrtoint.
817 setInsertionPoint(Builder, Val, false);
818
819 // If required, create an inttoptr instruction for Base.
820 Value *NewBase = Base;
821 if (!Base->getType()->isPointerTy())
822 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
823 Start->getName() + "to.ptr");
824
825 Value *GEP = Builder.CreateInBoundsGEP(
826 Start->getType()->getPointerElementType(), NewBase,
827 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
828
829 if (!Val->getType()->isPointerTy()) {
830 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
831 Val->getName() + ".conv");
832 GEP = Cast;
833 }
834 Val->replaceAllUsesWith(GEP);
835 }
836
837 return NewInsts[Start];
838}
839
840/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
841/// the input Value as a constant indexed GEP. Returns a pair containing
842/// the GEPs Pointer and Index.
843static std::pair<Value *, Value *>
844getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
845 Type *IndexType = IntegerType::get(V->getContext(),
846 DL.getPointerTypeSizeInBits(V->getType()));
847
848 Constant *Index = ConstantInt::getNullValue(IndexType);
849 while (true) {
850 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
851 // We accept only inbouds GEPs here to exclude the possibility of
852 // overflow.
853 if (!GEP->isInBounds())
854 break;
855 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
856 GEP->getType() == V->getType()) {
857 V = GEP->getOperand(0);
858 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
859 Index = ConstantExpr::getAdd(
860 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
861 continue;
862 }
863 break;
864 }
865 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
866 if (!CI->isNoopCast(DL))
867 break;
868 V = CI->getOperand(0);
869 continue;
870 }
871 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
872 if (!CI->isNoopCast(DL))
873 break;
874 V = CI->getOperand(0);
875 continue;
876 }
877 break;
878 }
879 return {V, Index};
880}
881
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000882/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
883/// We can look through PHIs, GEPs and casts in order to determine a common base
884/// between GEPLHS and RHS.
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000885static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
886 ICmpInst::Predicate Cond,
887 const DataLayout &DL) {
888 if (!GEPLHS->hasAllConstantIndices())
889 return nullptr;
890
891 Value *PtrBase, *Index;
892 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
893
894 // The set of nodes that will take part in this transformation.
895 SetVector<Value *> Nodes;
896
897 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
898 return nullptr;
899
900 // We know we can re-write this as
901 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
902 // Since we've only looked through inbouds GEPs we know that we
903 // can't have overflow on either side. We can therefore re-write
904 // this as:
905 // OFFSET1 cmp OFFSET2
906 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
907
908 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
909 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
910 // offset. Since Index is the offset of LHS to the base pointer, we will now
911 // compare the offsets instead of comparing the pointers.
912 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
913}
914
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000915/// Fold comparisons between a GEP instruction and something else. At this point
916/// we know that the GEP is on the LHS of the comparison.
Sanjay Patel43395062016-07-21 18:07:40 +0000917Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000918 ICmpInst::Predicate Cond,
919 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000920 // Don't transform signed compares of GEPs into index compares. Even if the
921 // GEP is inbounds, the final add of the base pointer can have signed overflow
922 // and would change the result of the icmp.
923 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000924 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000925 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000926 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000927
Matt Arsenault44f60d02014-06-09 19:20:29 +0000928 // Look through bitcasts and addrspacecasts. We do not however want to remove
929 // 0 GEPs.
930 if (!isa<GetElementPtrInst>(RHS))
931 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000932
933 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000934 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000935 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
936 // This transformation (ignoring the base and scales) is valid because we
937 // know pointers can't overflow since the gep is inbounds. See if we can
938 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000939 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000940
Chris Lattner2188e402010-01-04 07:37:31 +0000941 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000942 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000943 Offset = EmitGEPOffset(GEPLHS);
944 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
945 Constant::getNullValue(Offset->getType()));
946 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
947 // If the base pointers are different, but the indices are the same, just
948 // compare the base pointer.
949 if (PtrBase != GEPRHS->getOperand(0)) {
950 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
951 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
952 GEPRHS->getOperand(0)->getType();
953 if (IndicesTheSame)
954 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
955 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
956 IndicesTheSame = false;
957 break;
958 }
959
960 // If all indices are the same, just compare the base pointers.
961 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000962 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000963
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000964 // If we're comparing GEPs with two base pointers that only differ in type
965 // and both GEPs have only constant indices or just one use, then fold
966 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000968 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
969 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
970 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000971 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000972 Value *LOffset = EmitGEPOffset(GEPLHS);
973 Value *ROffset = EmitGEPOffset(GEPRHS);
974
975 // If we looked through an addrspacecast between different sized address
976 // spaces, the LHS and RHS pointers are different sized
977 // integers. Truncate to the smaller one.
978 Type *LHSIndexTy = LOffset->getType();
979 Type *RHSIndexTy = ROffset->getType();
980 if (LHSIndexTy != RHSIndexTy) {
981 if (LHSIndexTy->getPrimitiveSizeInBits() <
982 RHSIndexTy->getPrimitiveSizeInBits()) {
983 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
984 } else
985 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
986 }
987
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000988 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000989 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000990 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000991 }
992
Chris Lattner2188e402010-01-04 07:37:31 +0000993 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000994 // different. Try convert this to an indexed compare by looking through
995 // PHIs/casts.
996 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +0000997 }
998
999 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001000 if (GEPLHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001001 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +00001002 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +00001003
1004 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001005 if (GEPRHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001006 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner2188e402010-01-04 07:37:31 +00001007
Stuart Hastings66a82b92011-05-14 05:55:10 +00001008 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001009 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1010 // If the GEPs only differ by one index, compare it.
1011 unsigned NumDifferences = 0; // Keep track of # differences.
1012 unsigned DiffOperand = 0; // The operand that differs.
1013 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1014 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1015 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1016 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1017 // Irreconcilable differences.
1018 NumDifferences = 2;
1019 break;
1020 } else {
1021 if (NumDifferences++) break;
1022 DiffOperand = i;
1023 }
1024 }
1025
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001026 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001027 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001028 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001029
Stuart Hastings66a82b92011-05-14 05:55:10 +00001030 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001031 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1032 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1033 // Make sure we do a signed comparison here.
1034 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1035 }
1036 }
1037
1038 // Only lower this if the icmp is the only user of the GEP or if we expect
1039 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001040 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001041 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1042 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1043 Value *L = EmitGEPOffset(GEPLHS);
1044 Value *R = EmitGEPOffset(GEPRHS);
1045 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1046 }
1047 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001048
1049 // Try convert this to an indexed compare by looking through PHIs/casts as a
1050 // last resort.
1051 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001052}
1053
Sanjay Patel43395062016-07-21 18:07:40 +00001054Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI, AllocaInst *Alloca,
Hans Wennborgf1f36512015-10-07 00:20:07 +00001055 Value *Other) {
1056 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1057
1058 // It would be tempting to fold away comparisons between allocas and any
1059 // pointer not based on that alloca (e.g. an argument). However, even
1060 // though such pointers cannot alias, they can still compare equal.
1061 //
1062 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1063 // doesn't escape we can argue that it's impossible to guess its value, and we
1064 // can therefore act as if any such guesses are wrong.
1065 //
1066 // The code below checks that the alloca doesn't escape, and that it's only
1067 // used in a comparison once (the current instruction). The
1068 // single-comparison-use condition ensures that we're trivially folding all
1069 // comparisons against the alloca consistently, and avoids the risk of
1070 // erroneously folding a comparison of the pointer with itself.
1071
1072 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1073
1074 SmallVector<Use *, 32> Worklist;
1075 for (Use &U : Alloca->uses()) {
1076 if (Worklist.size() >= MaxIter)
1077 return nullptr;
1078 Worklist.push_back(&U);
1079 }
1080
1081 unsigned NumCmps = 0;
1082 while (!Worklist.empty()) {
1083 assert(Worklist.size() <= MaxIter);
1084 Use *U = Worklist.pop_back_val();
1085 Value *V = U->getUser();
1086 --MaxIter;
1087
1088 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1089 isa<SelectInst>(V)) {
1090 // Track the uses.
1091 } else if (isa<LoadInst>(V)) {
1092 // Loading from the pointer doesn't escape it.
1093 continue;
1094 } else if (auto *SI = dyn_cast<StoreInst>(V)) {
1095 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1096 if (SI->getValueOperand() == U->get())
1097 return nullptr;
1098 continue;
1099 } else if (isa<ICmpInst>(V)) {
1100 if (NumCmps++)
1101 return nullptr; // Found more than one cmp.
1102 continue;
1103 } else if (auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1104 switch (Intrin->getIntrinsicID()) {
1105 // These intrinsics don't escape or compare the pointer. Memset is safe
1106 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1107 // we don't allow stores, so src cannot point to V.
1108 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1109 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1110 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1111 continue;
1112 default:
1113 return nullptr;
1114 }
1115 } else {
1116 return nullptr;
1117 }
1118 for (Use &U : V->uses()) {
1119 if (Worklist.size() >= MaxIter)
1120 return nullptr;
1121 Worklist.push_back(&U);
1122 }
1123 }
1124
1125 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001126 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001127 ICI,
1128 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1129}
1130
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001131/// Fold "icmp pred (X+CI), X".
Sanjay Patel43395062016-07-21 18:07:40 +00001132Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI,
1133 Value *X, ConstantInt *CI,
1134 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001135 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001136 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001137 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001138
Chris Lattner8c92b572010-01-08 17:48:19 +00001139 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001140 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1141 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1142 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001143 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001144 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001145 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1146 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001147
Chris Lattner2188e402010-01-04 07:37:31 +00001148 // (X+1) >u X --> X <u (0-1) --> X != 255
1149 // (X+2) >u X --> X <u (0-2) --> X <u 254
1150 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001151 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001152 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001153
Chris Lattner2188e402010-01-04 07:37:31 +00001154 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1155 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1156 APInt::getSignedMaxValue(BitWidth));
1157
1158 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1159 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1160 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1161 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1162 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1163 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001164 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001165 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001166
Chris Lattner2188e402010-01-04 07:37:31 +00001167 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1168 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1169 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1170 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1171 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1172 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001173
Chris Lattner2188e402010-01-04 07:37:31 +00001174 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001175 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001176 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1177}
1178
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001179/// Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS and CmpRHS are
1180/// both known to be integer constants.
Sanjay Patel43395062016-07-21 18:07:40 +00001181Instruction *InstCombiner::foldICmpDivConst(ICmpInst &ICI, BinaryOperator *DivI,
1182 ConstantInt *DivRHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001183 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
1184 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001185
1186 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +00001187 // then don't attempt this transform. The code below doesn't have the
1188 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +00001189 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +00001190 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +00001191 // (x /u C1) <u C2. Simply casting the operands and result won't
1192 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +00001193 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +00001194 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
1195 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +00001196 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001197 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +00001198 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +00001199 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001200 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +00001201 if (DivRHS->isOne()) {
1202 // This eliminates some funny cases with INT_MIN.
1203 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
1204 return &ICI;
1205 }
Chris Lattner2188e402010-01-04 07:37:31 +00001206
1207 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +00001208 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
1209 // C2 (CI). By solving for X we can turn this into a range check
1210 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +00001211 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
1212
1213 // Determine if the product overflows by seeing if the product is
1214 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +00001215 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +00001216 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
1217 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
1218
1219 // Get the ICmp opcode
1220 ICmpInst::Predicate Pred = ICI.getPredicate();
1221
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001222 // If the division is known to be exact, then there is no remainder from the
1223 // divide, so the covered range size is unit, otherwise it is the divisor.
Chris Lattner98457102011-02-10 05:23:05 +00001224 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001225
Chris Lattner2188e402010-01-04 07:37:31 +00001226 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +00001227 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +00001228 // Compute this interval based on the constants involved and the signedness of
1229 // the compare/divide. This computes a half-open interval, keeping track of
1230 // whether either value in the interval overflows. After analysis each
1231 // overflow variable is set to 0 if it's corresponding bound variable is valid
1232 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
1233 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001234 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +00001235
Chris Lattner2188e402010-01-04 07:37:31 +00001236 if (!DivIsSigned) { // udiv
1237 // e.g. X/5 op 3 --> [15, 20)
1238 LoBound = Prod;
1239 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +00001240 if (!HiOverflow) {
1241 // If this is not an exact divide, then many values in the range collapse
1242 // to the same result value.
1243 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
1244 }
Chris Lattner2188e402010-01-04 07:37:31 +00001245 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
1246 if (CmpRHSV == 0) { // (X / pos) op 0
1247 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +00001248 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
1249 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +00001250 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
1251 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
1252 HiOverflow = LoOverflow = ProdOV;
1253 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001254 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001255 } else { // (X / pos) op neg
1256 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
1257 HiBound = AddOne(Prod);
1258 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
1259 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +00001260 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001261 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +00001262 }
Chris Lattner2188e402010-01-04 07:37:31 +00001263 }
Chris Lattnerb1a15122011-07-15 06:08:15 +00001264 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +00001265 if (DivI->isExact())
1266 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001267 if (CmpRHSV == 0) { // (X / neg) op 0
1268 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +00001269 LoBound = AddOne(RangeSize);
1270 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001271 if (HiBound == DivRHS) { // -INTMIN = INTMIN
1272 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +00001273 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +00001274 }
1275 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
1276 // e.g. X/-5 op 3 --> [-19, -14)
1277 HiBound = AddOne(Prod);
1278 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
1279 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001280 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +00001281 } else { // (X / neg) op neg
1282 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
1283 LoOverflow = HiOverflow = ProdOV;
1284 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001285 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001286 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001287
Chris Lattner2188e402010-01-04 07:37:31 +00001288 // Dividing by a negative swaps the condition. LT <-> GT
1289 Pred = ICmpInst::getSwappedPredicate(Pred);
1290 }
1291
1292 Value *X = DivI->getOperand(0);
1293 switch (Pred) {
1294 default: llvm_unreachable("Unhandled icmp opcode!");
1295 case ICmpInst::ICMP_EQ:
1296 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001297 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +00001298 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001299 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1300 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001301 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001302 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1303 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001304 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner98457102011-02-10 05:23:05 +00001305 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +00001306 case ICmpInst::ICMP_NE:
1307 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001308 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +00001309 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001310 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1311 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001312 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001313 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1314 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001315 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner067459c2010-03-05 08:46:26 +00001316 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +00001317 case ICmpInst::ICMP_ULT:
1318 case ICmpInst::ICMP_SLT:
1319 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001320 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001321 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001322 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001323 return new ICmpInst(Pred, X, LoBound);
1324 case ICmpInst::ICMP_UGT:
1325 case ICmpInst::ICMP_SGT:
1326 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001327 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +00001328 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001329 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001330 if (Pred == ICmpInst::ICMP_UGT)
1331 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +00001332 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +00001333 }
1334}
1335
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001336/// Handle "icmp(([al]shr X, cst1), cst2)".
Sanjay Patel43395062016-07-21 18:07:40 +00001337Instruction *InstCombiner::foldICmpShrConst(ICmpInst &ICI, BinaryOperator *Shr,
1338 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +00001339 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001340
Chris Lattnerd369f572011-02-13 07:43:07 +00001341 // Check that the shift amount is in range. If not, don't perform
1342 // undefined shifts. When the shift is visited it will be
1343 // simplified.
1344 uint32_t TypeBits = CmpRHSV.getBitWidth();
1345 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +00001346 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001347 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001348
Chris Lattner43273af2011-02-13 08:07:21 +00001349 if (!ICI.isEquality()) {
1350 // If we have an unsigned comparison and an ashr, we can't simplify this.
1351 // Similarly for signed comparisons with lshr.
1352 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +00001353 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001354
Eli Friedman865866e2011-05-25 23:26:20 +00001355 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1356 // by a power of 2. Since we already have logic to simplify these,
1357 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +00001358 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +00001359 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +00001360 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001361
Chris Lattner43273af2011-02-13 08:07:21 +00001362 // Revisit the shift (to delete it).
1363 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001364
Chris Lattner43273af2011-02-13 08:07:21 +00001365 Constant *DivCst =
1366 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001367
Chris Lattner43273af2011-02-13 08:07:21 +00001368 Value *Tmp =
1369 Shr->getOpcode() == Instruction::AShr ?
1370 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1371 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001372
Chris Lattner43273af2011-02-13 08:07:21 +00001373 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001374
Chris Lattner43273af2011-02-13 08:07:21 +00001375 // If the builder folded the binop, just return it.
1376 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +00001377 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +00001378 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001379
Chris Lattner43273af2011-02-13 08:07:21 +00001380 // Otherwise, fold this div/compare.
1381 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1382 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001383
Sanjay Patel43395062016-07-21 18:07:40 +00001384 Instruction *Res = foldICmpDivConst(ICI, TheDiv, cast<ConstantInt>(DivCst));
Chris Lattner43273af2011-02-13 08:07:21 +00001385 assert(Res && "This div/cst should have folded!");
1386 return Res;
1387 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001388
Chris Lattnerd369f572011-02-13 07:43:07 +00001389 // If we are comparing against bits always shifted out, the
1390 // comparison cannot succeed.
1391 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001392 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001393 if (Shr->getOpcode() == Instruction::LShr)
1394 Comp = Comp.lshr(ShAmtVal);
1395 else
1396 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001397
Chris Lattnerd369f572011-02-13 07:43:07 +00001398 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1399 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001400 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00001401 return replaceInstUsesWith(ICI, Cst);
Chris Lattnerd369f572011-02-13 07:43:07 +00001402 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001403
Chris Lattnerd369f572011-02-13 07:43:07 +00001404 // Otherwise, check to see if the bits shifted out are known to be zero.
1405 // If so, we can compare against the unshifted value:
1406 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001407 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001408 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001409
Chris Lattnerd369f572011-02-13 07:43:07 +00001410 if (Shr->hasOneUse()) {
1411 // Otherwise strength reduce the shift into an and.
1412 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001413 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001414
Chris Lattnerd369f572011-02-13 07:43:07 +00001415 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1416 Mask, Shr->getName()+".mask");
1417 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1418 }
Craig Topperf40110f2014-04-25 05:29:35 +00001419 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001420}
1421
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001422/// Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001423/// (icmp eq/ne A, Log2(const2/const1)) ->
1424/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
Sanjay Patel43395062016-07-21 18:07:40 +00001425Instruction *InstCombiner::foldICmpCstShrConst(ICmpInst &I, Value *Op, Value *A,
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001426 ConstantInt *CI1,
1427 ConstantInt *CI2) {
1428 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1429
1430 auto getConstant = [&I, this](bool IsTrue) {
1431 if (I.getPredicate() == I.ICMP_NE)
1432 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001433 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001434 };
1435
1436 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1437 if (I.getPredicate() == I.ICMP_NE)
1438 Pred = CmpInst::getInversePredicate(Pred);
1439 return new ICmpInst(Pred, LHS, RHS);
1440 };
1441
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001442 const APInt &AP1 = CI1->getValue();
1443 const APInt &AP2 = CI2->getValue();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001444
David Majnemer2abb8182014-10-25 07:13:13 +00001445 // Don't bother doing any work for cases which InstSimplify handles.
1446 if (AP2 == 0)
1447 return nullptr;
1448 bool IsAShr = isa<AShrOperator>(Op);
1449 if (IsAShr) {
1450 if (AP2.isAllOnesValue())
1451 return nullptr;
1452 if (AP2.isNegative() != AP1.isNegative())
1453 return nullptr;
1454 if (AP2.sgt(AP1))
1455 return nullptr;
1456 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001457
David Majnemerd2056022014-10-21 19:51:55 +00001458 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001459 // 'A' must be large enough to shift out the highest set bit.
1460 return getICmp(I.ICMP_UGT, A,
1461 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001462
David Majnemerd2056022014-10-21 19:51:55 +00001463 if (AP1 == AP2)
1464 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001465
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001466 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001467 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001468 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001469 else
David Majnemere5977eb2015-09-19 00:48:26 +00001470 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001471
David Majnemerd2056022014-10-21 19:51:55 +00001472 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001473 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1474 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001475 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001476 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1477 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001478 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001479 } else if (AP1 == AP2.lshr(Shift)) {
1480 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1481 }
David Majnemerd2056022014-10-21 19:51:55 +00001482 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001483 // Shifting const2 will never be equal to const1.
1484 return getConstant(false);
1485}
Chris Lattner2188e402010-01-04 07:37:31 +00001486
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001487/// Handle "(icmp eq/ne (shl const2, A), const1)" ->
David Majnemer59939ac2014-10-19 08:23:08 +00001488/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
Sanjay Patel43395062016-07-21 18:07:40 +00001489Instruction *InstCombiner::foldICmpCstShlConst(ICmpInst &I, Value *Op, Value *A,
1490 ConstantInt *CI1,
1491 ConstantInt *CI2) {
David Majnemer59939ac2014-10-19 08:23:08 +00001492 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1493
1494 auto getConstant = [&I, this](bool IsTrue) {
1495 if (I.getPredicate() == I.ICMP_NE)
1496 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001497 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
David Majnemer59939ac2014-10-19 08:23:08 +00001498 };
1499
1500 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1501 if (I.getPredicate() == I.ICMP_NE)
1502 Pred = CmpInst::getInversePredicate(Pred);
1503 return new ICmpInst(Pred, LHS, RHS);
1504 };
1505
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001506 const APInt &AP1 = CI1->getValue();
1507 const APInt &AP2 = CI2->getValue();
David Majnemer59939ac2014-10-19 08:23:08 +00001508
David Majnemer2abb8182014-10-25 07:13:13 +00001509 // Don't bother doing any work for cases which InstSimplify handles.
1510 if (AP2 == 0)
1511 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001512
1513 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1514
1515 if (!AP1 && AP2TrailingZeros != 0)
1516 return getICmp(I.ICMP_UGE, A,
1517 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1518
1519 if (AP1 == AP2)
1520 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1521
1522 // Get the distance between the lowest bits that are set.
1523 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1524
1525 if (Shift > 0 && AP2.shl(Shift) == AP1)
1526 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1527
1528 // Shifting const2 will never be equal to const1.
1529 return getConstant(false);
1530}
1531
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001532/// Handle "icmp (instr, intcst)".
Sanjay Patel43395062016-07-21 18:07:40 +00001533Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &ICI,
1534 Instruction *LHSI,
1535 ConstantInt *RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001536 const APInt &RHSV = RHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001537
Chris Lattner2188e402010-01-04 07:37:31 +00001538 switch (LHSI->getOpcode()) {
1539 case Instruction::Trunc:
Sanjoy Dase5f48892015-09-16 20:41:29 +00001540 if (RHS->isOne() && RHSV.getBitWidth() > 1) {
1541 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1542 Value *V = nullptr;
1543 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1544 match(LHSI->getOperand(0), m_Signum(m_Value(V))))
1545 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1546 ConstantInt::get(V->getType(), 1));
1547 }
Chris Lattner2188e402010-01-04 07:37:31 +00001548 if (ICI.isEquality() && LHSI->hasOneUse()) {
1549 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1550 // of the high bits truncated out of x are known.
1551 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1552 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
Chris Lattner2188e402010-01-04 07:37:31 +00001553 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001554 computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001555
Chris Lattner2188e402010-01-04 07:37:31 +00001556 // If all the high bits are known, we can do this xform.
1557 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1558 // Pull in the high bits from known-ones set.
Jay Foad583abbc2010-12-07 08:25:19 +00001559 APInt NewRHS = RHS->getValue().zext(SrcBits);
Eli Friedmane0a64d82012-05-11 01:32:59 +00001560 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
Chris Lattner2188e402010-01-04 07:37:31 +00001561 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001562 Builder->getInt(NewRHS));
Chris Lattner2188e402010-01-04 07:37:31 +00001563 }
1564 }
1565 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001566
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001567 case Instruction::Xor: // (icmp pred (xor X, XorCst), CI)
1568 if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00001569 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1570 // fold the xor.
1571 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1572 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1573 Value *CompareVal = LHSI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001574
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001575 // If the sign bit of the XorCst is not set, there is no change to
Chris Lattner2188e402010-01-04 07:37:31 +00001576 // the operation, just stop using the Xor.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001577 if (!XorCst->isNegative()) {
Chris Lattner2188e402010-01-04 07:37:31 +00001578 ICI.setOperand(0, CompareVal);
1579 Worklist.Add(LHSI);
1580 return &ICI;
1581 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001582
Chris Lattner2188e402010-01-04 07:37:31 +00001583 // Was the old condition true if the operand is positive?
1584 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001585
Chris Lattner2188e402010-01-04 07:37:31 +00001586 // If so, the new one isn't.
1587 isTrueIfPositive ^= true;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001588
Chris Lattner2188e402010-01-04 07:37:31 +00001589 if (isTrueIfPositive)
1590 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1591 SubOne(RHS));
1592 else
1593 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1594 AddOne(RHS));
1595 }
1596
1597 if (LHSI->hasOneUse()) {
1598 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001599 if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1600 const APInt &SignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001601 ICmpInst::Predicate Pred = ICI.isSigned()
1602 ? ICI.getUnsignedPredicate()
1603 : ICI.getSignedPredicate();
1604 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001605 Builder->getInt(RHSV ^ SignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001606 }
1607
1608 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001609 if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1610 const APInt &NotSignBit = XorCst->getValue();
Chris Lattner2188e402010-01-04 07:37:31 +00001611 ICmpInst::Predicate Pred = ICI.isSigned()
1612 ? ICI.getUnsignedPredicate()
1613 : ICI.getSignedPredicate();
1614 Pred = ICI.getSwappedPredicate(Pred);
1615 return new ICmpInst(Pred, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00001616 Builder->getInt(RHSV ^ NotSignBit));
Chris Lattner2188e402010-01-04 07:37:31 +00001617 }
1618 }
David Majnemer72d76272013-07-09 09:20:58 +00001619
1620 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1621 // iff -C is a power of 2
1622 if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001623 XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1624 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
David Majnemer72d76272013-07-09 09:20:58 +00001625
1626 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1627 // iff -C is a power of 2
1628 if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001629 XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1630 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001631 }
1632 break;
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001633 case Instruction::And: // (icmp pred (and X, AndCst), RHS)
Chris Lattner2188e402010-01-04 07:37:31 +00001634 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1635 LHSI->getOperand(0)->hasOneUse()) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001636 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001637
Chris Lattner2188e402010-01-04 07:37:31 +00001638 // If the LHS is an AND of a truncating cast, we can widen the
1639 // and/compare to be the input width without changing the value
1640 // produced, eliminating a cast.
1641 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1642 // We can do this transformation if either the AND constant does not
Jim Grosbach129c52a2011-09-30 18:09:53 +00001643 // have its sign bit set or if it is an equality comparison.
Chris Lattner2188e402010-01-04 07:37:31 +00001644 // Extending a relational comparison when we're checking the sign
1645 // bit would not work.
Benjamin Kramer35159c12011-06-12 22:47:53 +00001646 if (ICI.isEquality() ||
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001647 (!AndCst->isNegative() && RHSV.isNonNegative())) {
Benjamin Kramer35159c12011-06-12 22:47:53 +00001648 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001649 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001650 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
Benjamin Kramer35159c12011-06-12 22:47:53 +00001651 NewAnd->takeName(LHSI);
Chris Lattner2188e402010-01-04 07:37:31 +00001652 return new ICmpInst(ICI.getPredicate(), NewAnd,
Benjamin Kramer35159c12011-06-12 22:47:53 +00001653 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
Chris Lattner2188e402010-01-04 07:37:31 +00001654 }
1655 }
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001656
1657 // If the LHS is an AND of a zext, and we have an equality compare, we can
1658 // shrink the and/compare to the smaller type, eliminating the cast.
1659 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +00001660 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001661 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1662 // should fold the icmp to true/false in that case.
1663 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1664 Value *NewAnd =
1665 Builder->CreateAnd(Cast->getOperand(0),
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001666 ConstantExpr::getTrunc(AndCst, Ty));
Benjamin Kramer91f914c2011-06-12 22:48:00 +00001667 NewAnd->takeName(LHSI);
1668 return new ICmpInst(ICI.getPredicate(), NewAnd,
1669 ConstantExpr::getTrunc(RHS, Ty));
1670 }
1671 }
1672
Chris Lattner2188e402010-01-04 07:37:31 +00001673 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1674 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1675 // happens a LOT in code produced by the C front-end, for bitfield
1676 // access.
1677 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1678 if (Shift && !Shift->isShift())
Craig Topperf40110f2014-04-25 05:29:35 +00001679 Shift = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001680
Chris Lattner2188e402010-01-04 07:37:31 +00001681 ConstantInt *ShAmt;
Craig Topperf40110f2014-04-25 05:29:35 +00001682 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001683
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001684 // This seemingly simple opportunity to fold away a shift turns out to
1685 // be rather complicated. See PR17827
1686 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
Chris Lattner2188e402010-01-04 07:37:31 +00001687 if (ShAmt) {
Kay Tiong Khoo5389f742013-12-02 18:43:59 +00001688 bool CanFold = false;
1689 unsigned ShiftOpcode = Shift->getOpcode();
1690 if (ShiftOpcode == Instruction::AShr) {
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001691 // There may be some constraints that make this possible,
1692 // but nothing simple has been discovered yet.
1693 CanFold = false;
1694 } else if (ShiftOpcode == Instruction::Shl) {
1695 // For a left shift, we can fold if the comparison is not signed.
1696 // We can also fold a signed comparison if the mask value and
1697 // comparison value are not negative. These constraints may not be
1698 // obvious, but we can prove that they are correct using an SMT
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001699 // solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001700 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
Chris Lattner2188e402010-01-04 07:37:31 +00001701 CanFold = true;
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001702 } else if (ShiftOpcode == Instruction::LShr) {
1703 // For a logical right shift, we can fold if the comparison is not
1704 // signed. We can also fold a signed comparison if the shifted mask
1705 // value and the shifted comparison value are not negative.
1706 // These constraints may not be obvious, but we can prove that they
Kay Tiong Khooe37d5202013-12-19 18:35:54 +00001707 // are correct using an SMT solver.
Kay Tiong Khooa570b5a2013-12-19 18:07:17 +00001708 if (!ICI.isSigned())
1709 CanFold = true;
1710 else {
1711 ConstantInt *ShiftedAndCst =
1712 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1713 ConstantInt *ShiftedRHSCst =
1714 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1715
1716 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1717 CanFold = true;
1718 }
Chris Lattner2188e402010-01-04 07:37:31 +00001719 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001720
Chris Lattner2188e402010-01-04 07:37:31 +00001721 if (CanFold) {
1722 Constant *NewCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001723 if (ShiftOpcode == Instruction::Shl)
Chris Lattner2188e402010-01-04 07:37:31 +00001724 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1725 else
1726 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001727
Chris Lattner2188e402010-01-04 07:37:31 +00001728 // Check to see if we are shifting out any of the bits being
1729 // compared.
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001730 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001731 // If we shifted bits out, the fold is not going to work out.
1732 // As a special case, check to see if this means that the
1733 // result is always true or false now.
1734 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00001735 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001736 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Sanjay Patel4b198802016-02-01 22:23:39 +00001737 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001738 } else {
1739 ICI.setOperand(1, NewCst);
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001740 Constant *NewAndCst;
Kay Tiong Khood7b00ca2013-12-02 22:23:32 +00001741 if (ShiftOpcode == Instruction::Shl)
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001742 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
Chris Lattner2188e402010-01-04 07:37:31 +00001743 else
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001744 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1745 LHSI->setOperand(1, NewAndCst);
Chris Lattner2188e402010-01-04 07:37:31 +00001746 LHSI->setOperand(0, Shift->getOperand(0));
1747 Worklist.Add(Shift); // Shift is dead.
1748 return &ICI;
1749 }
1750 }
1751 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001752
Chris Lattner2188e402010-01-04 07:37:31 +00001753 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1754 // preferable because it allows the C<<Y expression to be hoisted out
1755 // of a loop if Y is invariant and X is not.
1756 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1757 ICI.isEquality() && !Shift->isArithmeticShift() &&
1758 !isa<Constant>(Shift->getOperand(0))) {
1759 // Compute C << Y.
1760 Value *NS;
1761 if (Shift->getOpcode() == Instruction::LShr) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001762 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001763 } else {
1764 // Insert a logical shift.
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001765 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
Chris Lattner2188e402010-01-04 07:37:31 +00001766 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001767
Chris Lattner2188e402010-01-04 07:37:31 +00001768 // Compute X & (C << Y).
Jim Grosbach129c52a2011-09-30 18:09:53 +00001769 Value *NewAnd =
Chris Lattner2188e402010-01-04 07:37:31 +00001770 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001771
Chris Lattner2188e402010-01-04 07:37:31 +00001772 ICI.setOperand(0, NewAnd);
1773 return &ICI;
1774 }
Paul Redmond5917f4c2012-12-19 19:47:13 +00001775
David Majnemer0ffccf72014-08-24 09:10:57 +00001776 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1777 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1778 //
1779 // iff pred isn't signed
1780 {
1781 Value *X, *Y, *LShr;
1782 if (!ICI.isSigned() && RHSV == 0) {
1783 if (match(LHSI->getOperand(1), m_One())) {
1784 Constant *One = cast<Constant>(LHSI->getOperand(1));
1785 Value *Or = LHSI->getOperand(0);
1786 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1787 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1788 unsigned UsesRemoved = 0;
1789 if (LHSI->hasOneUse())
1790 ++UsesRemoved;
1791 if (Or->hasOneUse())
1792 ++UsesRemoved;
1793 if (LShr->hasOneUse())
1794 ++UsesRemoved;
1795 Value *NewOr = nullptr;
1796 // Compute X & ((1 << Y) | 1)
1797 if (auto *C = dyn_cast<Constant>(Y)) {
1798 if (UsesRemoved >= 1)
1799 NewOr =
1800 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1801 } else {
1802 if (UsesRemoved >= 3)
1803 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1804 LShr->getName(),
1805 /*HasNUW=*/true),
1806 One, Or->getName());
1807 }
1808 if (NewOr) {
1809 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1810 ICI.setOperand(0, NewAnd);
1811 return &ICI;
1812 }
1813 }
1814 }
1815 }
1816 }
1817
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001818 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1819 // bit set in (X & AndCst) will produce a result greater than RHSV.
Paul Redmond5917f4c2012-12-19 19:47:13 +00001820 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
Kay Tiong Khoo564560f2013-12-02 22:11:56 +00001821 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1822 if ((NTZ < AndCst->getBitWidth()) &&
1823 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
Paul Redmond5917f4c2012-12-19 19:47:13 +00001824 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1825 Constant::getNullValue(RHS->getType()));
1826 }
Chris Lattner2188e402010-01-04 07:37:31 +00001827 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001828
Chris Lattner2188e402010-01-04 07:37:31 +00001829 // Try to optimize things like "A[i]&42 == 0" to index computations.
1830 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1831 if (GetElementPtrInst *GEP =
1832 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1833 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1834 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1835 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1836 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
Sanjay Patel43395062016-07-21 18:07:40 +00001837 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
Chris Lattner2188e402010-01-04 07:37:31 +00001838 return Res;
1839 }
1840 }
David Majnemer414d4e52013-07-09 08:09:32 +00001841
1842 // X & -C == -C -> X > u ~C
1843 // X & -C != -C -> X <= u ~C
1844 // iff C is a power of 2
1845 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1846 return new ICmpInst(
1847 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1848 : ICmpInst::ICMP_ULE,
1849 LHSI->getOperand(0), SubOne(RHS));
David Majnemerdfa3b092015-08-16 07:09:17 +00001850
1851 // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1852 // iff C is a power of 2
1853 if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) {
1854 if (auto *CI = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1855 const APInt &AI = CI->getValue();
1856 int32_t ExactLogBase2 = AI.exactLogBase2();
1857 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1858 Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1);
1859 Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy);
1860 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1861 ? ICmpInst::ICMP_SGE
1862 : ICmpInst::ICMP_SLT,
1863 Trunc, Constant::getNullValue(NTy));
1864 }
1865 }
1866 }
Chris Lattner2188e402010-01-04 07:37:31 +00001867 break;
1868
1869 case Instruction::Or: {
Sanjoy Dase5f48892015-09-16 20:41:29 +00001870 if (RHS->isOne()) {
1871 // icmp slt signum(V) 1 --> icmp slt V, 1
1872 Value *V = nullptr;
1873 if (ICI.getPredicate() == ICmpInst::ICMP_SLT &&
1874 match(LHSI, m_Signum(m_Value(V))))
1875 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1876 ConstantInt::get(V->getType(), 1));
1877 }
1878
Chris Lattner2188e402010-01-04 07:37:31 +00001879 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1880 break;
1881 Value *P, *Q;
1882 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1883 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1884 // -> and (icmp eq P, null), (icmp eq Q, null).
Chris Lattner2188e402010-01-04 07:37:31 +00001885 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1886 Constant::getNullValue(P->getType()));
1887 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1888 Constant::getNullValue(Q->getType()));
1889 Instruction *Op;
1890 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1891 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1892 else
1893 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1894 return Op;
1895 }
1896 break;
1897 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001898
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001899 case Instruction::Mul: { // (icmp pred (mul X, Val), CI)
1900 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1901 if (!Val) break;
1902
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +00001903 // If this is a signed comparison to 0 and the mul is sign preserving,
1904 // use the mul LHS operand instead.
1905 ICmpInst::Predicate pred = ICI.getPredicate();
1906 if (isSignTest(pred, RHS) && !Val->isZero() &&
1907 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1908 return new ICmpInst(Val->isNegative() ?
1909 ICmpInst::getSwappedPredicate(pred) : pred,
1910 LHSI->getOperand(0),
1911 Constant::getNullValue(RHS->getType()));
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00001912
1913 break;
1914 }
1915
Chris Lattner2188e402010-01-04 07:37:31 +00001916 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
Chris Lattner2188e402010-01-04 07:37:31 +00001917 uint32_t TypeBits = RHSV.getBitWidth();
David Majnemerb889e402013-06-28 23:42:03 +00001918 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1919 if (!ShAmt) {
1920 Value *X;
1921 // (1 << X) pred P2 -> X pred Log2(P2)
1922 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1923 bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1924 ICmpInst::Predicate Pred = ICI.getPredicate();
1925 if (ICI.isUnsigned()) {
1926 if (!RHSVIsPowerOf2) {
1927 // (1 << X) < 30 -> X <= 4
1928 // (1 << X) <= 30 -> X <= 4
1929 // (1 << X) >= 30 -> X > 4
1930 // (1 << X) > 30 -> X > 4
1931 if (Pred == ICmpInst::ICMP_ULT)
1932 Pred = ICmpInst::ICMP_ULE;
1933 else if (Pred == ICmpInst::ICMP_UGE)
1934 Pred = ICmpInst::ICMP_UGT;
1935 }
1936 unsigned RHSLog2 = RHSV.logBase2();
1937
1938 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
David Majnemerb889e402013-06-28 23:42:03 +00001939 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1940 if (RHSLog2 == TypeBits-1) {
1941 if (Pred == ICmpInst::ICMP_UGE)
1942 Pred = ICmpInst::ICMP_EQ;
David Majnemerb889e402013-06-28 23:42:03 +00001943 else if (Pred == ICmpInst::ICMP_ULT)
1944 Pred = ICmpInst::ICMP_NE;
1945 }
1946
1947 return new ICmpInst(Pred, X,
1948 ConstantInt::get(RHS->getType(), RHSLog2));
1949 } else if (ICI.isSigned()) {
1950 if (RHSV.isAllOnesValue()) {
1951 // (1 << X) <= -1 -> X == 31
1952 if (Pred == ICmpInst::ICMP_SLE)
1953 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1954 ConstantInt::get(RHS->getType(), TypeBits-1));
1955
1956 // (1 << X) > -1 -> X != 31
1957 if (Pred == ICmpInst::ICMP_SGT)
1958 return new ICmpInst(ICmpInst::ICMP_NE, X,
1959 ConstantInt::get(RHS->getType(), TypeBits-1));
1960 } else if (!RHSV) {
1961 // (1 << X) < 0 -> X == 31
1962 // (1 << X) <= 0 -> X == 31
1963 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1964 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1965 ConstantInt::get(RHS->getType(), TypeBits-1));
1966
1967 // (1 << X) >= 0 -> X != 31
1968 // (1 << X) > 0 -> X != 31
1969 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1970 return new ICmpInst(ICmpInst::ICMP_NE, X,
1971 ConstantInt::get(RHS->getType(), TypeBits-1));
1972 }
1973 } else if (ICI.isEquality()) {
1974 if (RHSVIsPowerOf2)
1975 return new ICmpInst(
1976 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
David Majnemerb889e402013-06-28 23:42:03 +00001977 }
1978 }
1979 break;
1980 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001981
Chris Lattner2188e402010-01-04 07:37:31 +00001982 // Check that the shift amount is in range. If not, don't perform
1983 // undefined shifts. When the shift is visited it will be
1984 // simplified.
1985 if (ShAmt->uge(TypeBits))
1986 break;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001987
Chris Lattner2188e402010-01-04 07:37:31 +00001988 if (ICI.isEquality()) {
1989 // If we are comparing against bits always shifted out, the
1990 // comparison cannot succeed.
1991 Constant *Comp =
1992 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1993 ShAmt);
1994 if (Comp != RHS) {// Comparing against a bit that we know is zero.
1995 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001996 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00001997 return replaceInstUsesWith(ICI, Cst);
Chris Lattner2188e402010-01-04 07:37:31 +00001998 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001999
Chris Lattner98457102011-02-10 05:23:05 +00002000 // If the shift is NUW, then it is just shifting out zeros, no need for an
2001 // AND.
2002 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
2003 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2004 ConstantExpr::getLShr(RHS, ShAmt));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002005
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002006 // If the shift is NSW and we compare to 0, then it is just shifting out
2007 // sign bits, no need for an AND either.
2008 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
2009 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2010 ConstantExpr::getLShr(RHS, ShAmt));
2011
Chris Lattner2188e402010-01-04 07:37:31 +00002012 if (LHSI->hasOneUse()) {
2013 // Otherwise strength reduce the shift into an and.
2014 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Jakub Staszakbddea112013-06-06 20:18:46 +00002015 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
2016 TypeBits - ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00002017
Chris Lattner2188e402010-01-04 07:37:31 +00002018 Value *And =
2019 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
2020 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner98457102011-02-10 05:23:05 +00002021 ConstantExpr::getLShr(RHS, ShAmt));
Chris Lattner2188e402010-01-04 07:37:31 +00002022 }
2023 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002024
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002025 // If this is a signed comparison to 0 and the shift is sign preserving,
2026 // use the shift LHS operand instead.
2027 ICmpInst::Predicate pred = ICI.getPredicate();
2028 if (isSignTest(pred, RHS) &&
2029 cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
2030 return new ICmpInst(pred,
2031 LHSI->getOperand(0),
2032 Constant::getNullValue(RHS->getType()));
2033
Chris Lattner2188e402010-01-04 07:37:31 +00002034 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2035 bool TrueIfSigned = false;
2036 if (LHSI->hasOneUse() &&
2037 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
2038 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner43273af2011-02-13 08:07:21 +00002039 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
Jim Grosbach129c52a2011-09-30 18:09:53 +00002040 APInt::getOneBitSet(TypeBits,
Chris Lattner43273af2011-02-13 08:07:21 +00002041 TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00002042 Value *And =
2043 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
2044 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2045 And, Constant::getNullValue(And->getType()));
2046 }
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002047
2048 // Transform (icmp pred iM (shl iM %v, N), CI)
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00002049 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
2050 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002051 // This enables to get rid of the shift in favor of a trunc which can be
2052 // free on the target. It has the additional benefit of comparing to a
2053 // smaller constant, which will be target friendly.
2054 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
Arnaud A. de Grandmaison71533052013-03-13 14:40:37 +00002055 if (LHSI->hasOneUse() &&
2056 Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002057 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
2058 Constant *NCI = ConstantExpr::getTrunc(
2059 ConstantExpr::getAShr(RHS,
2060 ConstantInt::get(RHS->getType(), Amt)),
2061 NTy);
2062 return new ICmpInst(ICI.getPredicate(),
2063 Builder->CreateTrunc(LHSI->getOperand(0), NTy),
Arnaud A. de Grandmaison1fd843e2013-02-15 15:18:17 +00002064 NCI);
Arnaud A. de Grandmaison61c167c2013-02-15 14:35:47 +00002065 }
2066
Chris Lattner2188e402010-01-04 07:37:31 +00002067 break;
2068 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002069
Chris Lattner2188e402010-01-04 07:37:31 +00002070 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Nick Lewycky174a7052011-02-28 08:31:40 +00002071 case Instruction::AShr: {
2072 // Handle equality comparisons of shift-by-constant.
2073 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
2074 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Sanjay Patel43395062016-07-21 18:07:40 +00002075 if (Instruction *Res = foldICmpShrConst(ICI, BO, ShAmt))
Chris Lattnerd369f572011-02-13 07:43:07 +00002076 return Res;
Nick Lewycky174a7052011-02-28 08:31:40 +00002077 }
2078
2079 // Handle exact shr's.
2080 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
2081 if (RHSV.isMinValue())
2082 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
2083 }
Chris Lattner2188e402010-01-04 07:37:31 +00002084 break;
Nick Lewycky174a7052011-02-28 08:31:40 +00002085 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002086
Chris Lattner2188e402010-01-04 07:37:31 +00002087 case Instruction::UDiv:
Chad Rosier4e6cda22016-05-10 20:22:09 +00002088 if (ConstantInt *DivLHS = dyn_cast<ConstantInt>(LHSI->getOperand(0))) {
2089 Value *X = LHSI->getOperand(1);
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002090 const APInt &C1 = RHS->getValue();
2091 const APInt &C2 = DivLHS->getValue();
Chad Rosier4e6cda22016-05-10 20:22:09 +00002092 assert(C2 != 0 && "udiv 0, X should have been simplified already.");
2093 // (icmp ugt (udiv C2, X), C1) -> (icmp ule X, C2/(C1+1))
2094 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
2095 assert(!C1.isMaxValue() &&
2096 "icmp ugt X, UINT_MAX should have been simplified already.");
2097 return new ICmpInst(ICmpInst::ICMP_ULE, X,
2098 ConstantInt::get(X->getType(), C2.udiv(C1 + 1)));
2099 }
2100 // (icmp ult (udiv C2, X), C1) -> (icmp ugt X, C2/C1)
2101 if (ICI.getPredicate() == ICmpInst::ICMP_ULT) {
2102 assert(C1 != 0 && "icmp ult X, 0 should have been simplified already.");
2103 return new ICmpInst(ICmpInst::ICMP_UGT, X,
2104 ConstantInt::get(X->getType(), C2.udiv(C1)));
2105 }
2106 }
2107 // fall-through
2108 case Instruction::SDiv:
Chris Lattner2188e402010-01-04 07:37:31 +00002109 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Jim Grosbach129c52a2011-09-30 18:09:53 +00002110 // Fold this div into the comparison, producing a range check.
2111 // Determine, based on the divide type, what the range is being
2112 // checked. If there is an overflow on the low or high side, remember
Chris Lattner2188e402010-01-04 07:37:31 +00002113 // it, otherwise compute the range [low, hi) bounding the new value.
2114 // See: InsertRangeTest above for the kinds of replacements possible.
2115 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
Sanjay Patel43395062016-07-21 18:07:40 +00002116 if (Instruction *R = foldICmpDivConst(ICI, cast<BinaryOperator>(LHSI),
Chris Lattner2188e402010-01-04 07:37:31 +00002117 DivRHS))
2118 return R;
2119 break;
2120
David Majnemerf2a9a512013-07-09 07:50:59 +00002121 case Instruction::Sub: {
2122 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
2123 if (!LHSC) break;
2124 const APInt &LHSV = LHSC->getValue();
2125
2126 // C1-X <u C2 -> (X|(C2-1)) == C1
2127 // iff C1 & (C2-1) == C2-1
2128 // C2 is a power of 2
2129 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
2130 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
2131 return new ICmpInst(ICmpInst::ICMP_EQ,
2132 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
2133 LHSC);
2134
David Majnemereeed73b2013-07-09 09:24:35 +00002135 // C1-X >u C2 -> (X|C2) != C1
David Majnemerf2a9a512013-07-09 07:50:59 +00002136 // iff C1 & C2 == C2
2137 // C2+1 is a power of 2
2138 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2139 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
2140 return new ICmpInst(ICmpInst::ICMP_NE,
2141 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
2142 break;
2143 }
2144
Chris Lattner2188e402010-01-04 07:37:31 +00002145 case Instruction::Add:
2146 // Fold: icmp pred (add X, C1), C2
2147 if (!ICI.isEquality()) {
2148 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
2149 if (!LHSC) break;
2150 const APInt &LHSV = LHSC->getValue();
2151
2152 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
2153 .subtract(LHSV);
2154
2155 if (ICI.isSigned()) {
2156 if (CR.getLower().isSignBit()) {
2157 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002158 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00002159 } else if (CR.getUpper().isSignBit()) {
2160 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002161 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00002162 }
2163 } else {
2164 if (CR.getLower().isMinValue()) {
2165 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002166 Builder->getInt(CR.getUpper()));
Chris Lattner2188e402010-01-04 07:37:31 +00002167 } else if (CR.getUpper().isMinValue()) {
2168 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Jakub Staszakbddea112013-06-06 20:18:46 +00002169 Builder->getInt(CR.getLower()));
Chris Lattner2188e402010-01-04 07:37:31 +00002170 }
2171 }
David Majnemerfa90a0b2013-07-08 11:53:08 +00002172
David Majnemerbafa5372013-07-09 07:58:32 +00002173 // X-C1 <u C2 -> (X & -C2) == C1
2174 // iff C1 & (C2-1) == 0
2175 // C2 is a power of 2
David Majnemerfa90a0b2013-07-08 11:53:08 +00002176 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
David Majnemerbafa5372013-07-09 07:58:32 +00002177 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
David Majnemerfa90a0b2013-07-08 11:53:08 +00002178 return new ICmpInst(ICmpInst::ICMP_EQ,
2179 Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
2180 ConstantExpr::getNeg(LHSC));
David Majnemerbafa5372013-07-09 07:58:32 +00002181
David Majnemereeed73b2013-07-09 09:24:35 +00002182 // X-C1 >u C2 -> (X & ~C2) != C1
David Majnemerbafa5372013-07-09 07:58:32 +00002183 // iff C1 & C2 == 0
2184 // C2+1 is a power of 2
2185 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
2186 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
2187 return new ICmpInst(ICmpInst::ICMP_NE,
2188 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
2189 ConstantExpr::getNeg(LHSC));
Chris Lattner2188e402010-01-04 07:37:31 +00002190 }
2191 break;
2192 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002193
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002194 return nullptr;
2195}
Jim Grosbach129c52a2011-09-30 18:09:53 +00002196
Sanjay Patelab50a932016-08-02 22:38:33 +00002197/// Simplify icmp_eq and icmp_ne instructions with binary operator LHS and
2198/// integer constant RHS.
2199Instruction *InstCombiner::foldICmpEqualityWithConstant(ICmpInst &ICI) {
Sanjay Patelab50a932016-08-02 22:38:33 +00002200 BinaryOperator *BO;
Sanjay Patel43aeb002016-08-03 18:59:03 +00002201 const APInt *RHSV;
2202 // FIXME: Some of these folds could work with arbitrary constants, but this
2203 // match is limited to scalars and vector splat constants.
Sanjay Patelab50a932016-08-02 22:38:33 +00002204 if (!ICI.isEquality() || !match(ICI.getOperand(0), m_BinOp(BO)) ||
Sanjay Patel43aeb002016-08-03 18:59:03 +00002205 !match(ICI.getOperand(1), m_APInt(RHSV)))
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002206 return nullptr;
2207
Sanjay Patel43aeb002016-08-03 18:59:03 +00002208 Constant *RHS = cast<Constant>(ICI.getOperand(1));
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002209 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002210 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002211
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002212 switch (BO->getOpcode()) {
2213 case Instruction::SRem:
2214 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Sanjay Patel2e9675f2016-08-03 19:48:40 +00002215 if (*RHSV == 0 && BO->hasOneUse()) {
2216 const APInt *BOC;
2217 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002218 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName());
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002219 return new ICmpInst(ICI.getPredicate(), NewRem,
2220 Constant::getNullValue(BO->getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002221 }
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002222 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002223 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002224 case Instruction::Add: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002225 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
Sanjay Patel00a324e2016-08-03 22:08:44 +00002226 const APInt *BOC;
2227 if (match(BOp1, m_APInt(BOC))) {
2228 if (BO->hasOneUse()) {
2229 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
2230 return new ICmpInst(ICI.getPredicate(), BOp0, SubC);
2231 }
Sanjay Patel43aeb002016-08-03 18:59:03 +00002232 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002233 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2234 // efficiently invertible, or if the add has just this one use.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002235 if (Value *NegVal = dyn_castNegVal(BOp1))
2236 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
2237 if (Value *NegVal = dyn_castNegVal(BOp0))
2238 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
2239 if (BO->hasOneUse()) {
2240 Value *Neg = Builder->CreateNeg(BOp1);
2241 Neg->takeName(BO);
2242 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
2243 }
2244 }
2245 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002246 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002247 case Instruction::Xor:
2248 if (BO->hasOneUse()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002249 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002250 // For the xor case, we can xor two constants together, eliminating
2251 // the explicit xor.
Sanjay Patel51a767c2016-08-03 17:23:08 +00002252 return new ICmpInst(ICI.getPredicate(), BOp0,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002253 ConstantExpr::getXor(RHS, BOC));
Sanjay Patel43aeb002016-08-03 18:59:03 +00002254 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002255 // Replace ((xor A, B) != 0) with (A != B)
Sanjay Patel51a767c2016-08-03 17:23:08 +00002256 return new ICmpInst(ICI.getPredicate(), BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002257 }
2258 }
2259 break;
2260 case Instruction::Sub:
2261 if (BO->hasOneUse()) {
Sanjay Patel9d591d12016-08-04 15:19:25 +00002262 const APInt *BOC;
2263 if (match(BOp0, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002264 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
Sanjay Patel9d591d12016-08-04 15:19:25 +00002265 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
2266 return new ICmpInst(ICI.getPredicate(), BOp1, SubC);
Sanjay Patel43aeb002016-08-03 18:59:03 +00002267 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002268 // Replace ((sub A, B) != 0) with (A != B)
Sanjay Patel51a767c2016-08-03 17:23:08 +00002269 return new ICmpInst(ICI.getPredicate(), BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002270 }
2271 }
2272 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002273 case Instruction::Or: {
2274 const APInt *BOC;
2275 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002276 // Comparing if all bits outside of a constant mask are set?
2277 // Replace (X | C) == -1 with (X & ~C) == ~C.
2278 // This removes the -1 constant.
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002279 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2280 Value *And = Builder->CreateAnd(BOp0, NotBOC);
2281 return new ICmpInst(ICI.getPredicate(), And, NotBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002282 }
2283 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002284 }
Sanjay Pateld938e882016-08-04 20:05:02 +00002285 case Instruction::And: {
2286 const APInt *BOC;
2287 if (match(BOp1, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002288 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Sanjay Pateld938e882016-08-04 20:05:02 +00002289 if (RHSV == BOC && RHSV->isPowerOf2())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002290 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
Sanjay Patelab50a932016-08-02 22:38:33 +00002291 BO, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002292
2293 // Don't perform the following transforms if the AND has multiple uses
2294 if (!BO->hasOneUse())
2295 break;
2296
2297 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Sanjay Pateld938e882016-08-04 20:05:02 +00002298 if (BOC->isSignBit()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002299 Constant *Zero = Constant::getNullValue(BOp0->getType());
2300 ICmpInst::Predicate Pred =
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002301 isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002302 return new ICmpInst(Pred, BOp0, Zero);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002303 }
2304
2305 // ((X & ~7) == 0) --> X < 8
Sanjay Pateld938e882016-08-04 20:05:02 +00002306 if (*RHSV == 0 && (~(*BOC) + 1).isPowerOf2()) {
2307 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1));
Sanjay Patel51a767c2016-08-03 17:23:08 +00002308 ICmpInst::Predicate Pred =
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002309 isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Sanjay Pateld938e882016-08-04 20:05:02 +00002310 return new ICmpInst(Pred, BOp0, NegBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002311 }
2312 }
2313 break;
Sanjay Pateld938e882016-08-04 20:05:02 +00002314 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002315 case Instruction::Mul:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002316 if (*RHSV == 0 && BO->hasNoSignedWrap()) {
Sanjay Patel3bade132016-08-04 22:19:27 +00002317 const APInt *BOC;
2318 if (match(BOp1, m_APInt(BOC)) && *BOC != 0) {
2319 // The trivial case (mul X, 0) is handled by InstSimplify.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002320 // General case : (mul X, C) != 0 iff X != 0
2321 // (mul X, C) == 0 iff X == 0
Sanjay Patel3bade132016-08-04 22:19:27 +00002322 return new ICmpInst(ICI.getPredicate(), BOp0,
2323 Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002324 }
2325 }
2326 break;
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002327 case Instruction::UDiv:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002328 if (*RHSV == 0) {
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002329 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
2330 ICmpInst::Predicate Pred =
2331 isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002332 return new ICmpInst(Pred, BOp1, BOp0);
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002333 }
2334 break;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002335 default:
2336 break;
2337 }
2338 return nullptr;
2339}
2340
Sanjay Patel1271bf92016-07-23 13:06:49 +00002341Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &ICI) {
2342 IntrinsicInst *II = dyn_cast<IntrinsicInst>(ICI.getOperand(0));
2343 const APInt *Op1C;
2344 if (!II || !ICI.isEquality() || !match(ICI.getOperand(1), m_APInt(Op1C)))
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002345 return nullptr;
2346
2347 // Handle icmp {eq|ne} <intrinsic>, intcst.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002348 switch (II->getIntrinsicID()) {
2349 case Intrinsic::bswap:
2350 Worklist.Add(II);
2351 ICI.setOperand(0, II->getArgOperand(0));
Sanjay Patel1271bf92016-07-23 13:06:49 +00002352 ICI.setOperand(1, Builder->getInt(Op1C->byteSwap()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002353 return &ICI;
2354 case Intrinsic::ctlz:
2355 case Intrinsic::cttz:
Amaury Sechet6bea6742016-08-04 05:27:20 +00002356 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
Sanjay Patel1271bf92016-07-23 13:06:49 +00002357 if (*Op1C == Op1C->getBitWidth()) {
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002358 Worklist.Add(II);
2359 ICI.setOperand(0, II->getArgOperand(0));
Sanjay Patel1271bf92016-07-23 13:06:49 +00002360 ICI.setOperand(1, ConstantInt::getNullValue(II->getType()));
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002361 return &ICI;
Chris Lattner2188e402010-01-04 07:37:31 +00002362 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002363 break;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002364 case Intrinsic::ctpop: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002365 // popcount(A) == 0 -> A == 0 and likewise for !=
Amaury Sechet6bea6742016-08-04 05:27:20 +00002366 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
2367 bool IsZero = *Op1C == 0;
2368 if (IsZero || *Op1C == Op1C->getBitWidth()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002369 Worklist.Add(II);
2370 ICI.setOperand(0, II->getArgOperand(0));
Amaury Sechet6bea6742016-08-04 05:27:20 +00002371 auto *NewOp = IsZero
2372 ? ConstantInt::getNullValue(II->getType())
2373 : ConstantInt::getAllOnesValue(II->getType());
2374 ICI.setOperand(1, NewOp);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002375 return &ICI;
2376 }
Amaury Sechet6bea6742016-08-04 05:27:20 +00002377 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002378 break;
2379 default:
2380 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002381 }
Craig Topperf40110f2014-04-25 05:29:35 +00002382 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002383}
2384
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002385/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
2386/// far.
Sanjay Patel43395062016-07-21 18:07:40 +00002387Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002388 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00002389 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002390 Type *SrcTy = LHSCIOp->getType();
2391 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002392 Value *RHSCIOp;
2393
Jim Grosbach129c52a2011-09-30 18:09:53 +00002394 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002395 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002396 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2397 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002398 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002399 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00002400 Value *RHSCIOp = RHSC->getOperand(0);
2401 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2402 LHSCIOp->getType()->getPointerAddressSpace()) {
2403 RHSOp = RHSC->getOperand(0);
2404 // If the pointer types don't match, insert a bitcast.
2405 if (LHSCIOp->getType() != RHSOp->getType())
2406 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2407 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002408 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002409 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002410 }
Chris Lattner2188e402010-01-04 07:37:31 +00002411
2412 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002413 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002414 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002415
Chris Lattner2188e402010-01-04 07:37:31 +00002416 // The code below only handles extension cast instructions, so far.
2417 // Enforce this.
2418 if (LHSCI->getOpcode() != Instruction::ZExt &&
2419 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002420 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002421
2422 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002423 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00002424
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002425 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002426 // Not an extension from the same type?
2427 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002428 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002429 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002430
Chris Lattner2188e402010-01-04 07:37:31 +00002431 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2432 // and the other is a zext), then we can't handle this.
2433 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002434 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002435
2436 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002437 if (ICmp.isEquality())
2438 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002439
2440 // A signed comparison of sign extended values simplifies into a
2441 // signed comparison.
2442 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002443 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002444
2445 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002446 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002447 }
2448
Sanjay Patel4c204232016-06-04 20:39:22 +00002449 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002450 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
2451 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00002452 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002453
2454 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002455 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002456 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002457 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002458
2459 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002460 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00002461 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002462 if (ICmp.isEquality())
2463 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002464
2465 // A signed comparison of sign extended values simplifies into a
2466 // signed comparison.
2467 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002468 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002469
2470 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002471 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002472 }
2473
Sanjay Patel6a333c32016-06-06 16:56:57 +00002474 // The re-extended constant changed, partly changed (in the case of a vector),
2475 // or could not be determined to be equal (in the case of a constant
2476 // expression), so the constant cannot be represented in the shorter type.
2477 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002478 // All the cases that fold to true or false will have already been handled
2479 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002480
Sanjay Patel6a333c32016-06-06 16:56:57 +00002481 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00002482 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002483
2484 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2485 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002486
2487 // We're performing an unsigned comp with a sign extended value.
2488 // This is true if the input is >= 0. [aka >s -1]
2489 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002490 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002491
2492 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002493 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
2494 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002495
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002496 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002497 return BinaryOperator::CreateNot(Result);
2498}
2499
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002500/// The caller has matched a pattern of the form:
Chris Lattneree61c1d2010-12-19 17:52:50 +00002501/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002502/// If this is of the form:
2503/// sum = a + b
2504/// if (sum+128 >u 255)
2505/// Then replace it with llvm.sadd.with.overflow.i8.
2506///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002507static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2508 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002509 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002510 // The transformation we're trying to do here is to transform this into an
2511 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2512 // with a narrower add, and discard the add-with-constant that is part of the
2513 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002514
Chris Lattnerf29562d2010-12-19 17:59:02 +00002515 // In order to eliminate the add-with-constant, the compare can be its only
2516 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002517 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002518 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002519
Chris Lattnerc56c8452010-12-19 18:22:06 +00002520 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002521 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002522 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002523 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002524
Chris Lattnerc56c8452010-12-19 18:22:06 +00002525 // The width of the new add formed is 1 more than the bias.
2526 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002527
Chris Lattnerc56c8452010-12-19 18:22:06 +00002528 // Check to see that CI1 is an all-ones value with NewWidth bits.
2529 if (CI1->getBitWidth() == NewWidth ||
2530 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002531 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002532
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002533 // This is only really a signed overflow check if the inputs have been
2534 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2535 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2536 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002537 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2538 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002539 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002540
Jim Grosbach129c52a2011-09-30 18:09:53 +00002541 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002542 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2543 // and truncates that discard the high bits of the add. Verify that this is
2544 // the case.
2545 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002546 for (User *U : OrigAdd->users()) {
2547 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002548
Chris Lattnerc56c8452010-12-19 18:22:06 +00002549 // Only accept truncates for now. We would really like a nice recursive
2550 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2551 // chain to see which bits of a value are actually demanded. If the
2552 // original add had another add which was then immediately truncated, we
2553 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002554 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002555 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2556 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002557 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002558
Chris Lattneree61c1d2010-12-19 17:52:50 +00002559 // If the pattern matches, truncate the inputs to the narrower type and
2560 // use the sadd_with_overflow intrinsic to efficiently compute both the
2561 // result and the overflow bit.
Jay Foadb804a2b2011-07-12 14:06:48 +00002562 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002563 Value *F = Intrinsic::getDeclaration(I.getModule(),
2564 Intrinsic::sadd_with_overflow, NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002565
Chris Lattnerce2995a2010-12-19 18:38:44 +00002566 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002567
Chris Lattner79874562010-12-19 18:35:09 +00002568 // Put the new code above the original add, in case there are any uses of the
2569 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002570 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002571
Chris Lattner79874562010-12-19 18:35:09 +00002572 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2573 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002574 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002575 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2576 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002577
Chris Lattneree61c1d2010-12-19 17:52:50 +00002578 // The inner add was the result of the narrow add, zero extended to the
2579 // wider type. Replace it with the result computed by the intrinsic.
Sanjay Patel4b198802016-02-01 22:23:39 +00002580 IC.replaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002581
Chris Lattner79874562010-12-19 18:35:09 +00002582 // The original icmp gets replaced with the overflow value.
2583 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002584}
Chris Lattner2188e402010-01-04 07:37:31 +00002585
Sanjoy Dasb0984472015-04-08 04:27:22 +00002586bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2587 Value *RHS, Instruction &OrigI,
2588 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002589 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2590 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002591
2592 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2593 Result = OpResult;
2594 Overflow = OverflowVal;
2595 if (ReuseName)
2596 Result->takeName(&OrigI);
2597 return true;
2598 };
2599
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002600 // If the overflow check was an add followed by a compare, the insertion point
2601 // may be pointing to the compare. We want to insert the new instructions
2602 // before the add in case there are uses of the add between the add and the
2603 // compare.
2604 Builder->SetInsertPoint(&OrigI);
2605
Sanjoy Dasb0984472015-04-08 04:27:22 +00002606 switch (OCF) {
2607 case OCF_INVALID:
2608 llvm_unreachable("bad overflow check kind!");
2609
2610 case OCF_UNSIGNED_ADD: {
2611 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2612 if (OR == OverflowResult::NeverOverflows)
2613 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2614 true);
2615
2616 if (OR == OverflowResult::AlwaysOverflows)
2617 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
2618 }
2619 // FALL THROUGH uadd into sadd
2620 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002621 // X + 0 -> {X, false}
2622 if (match(RHS, m_Zero()))
2623 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002624
2625 // We can strength reduce this signed add into a regular add if we can prove
2626 // that it will never overflow.
2627 if (OCF == OCF_SIGNED_ADD)
2628 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2629 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2630 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002631 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002632 }
2633
2634 case OCF_UNSIGNED_SUB:
2635 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002636 // X - 0 -> {X, false}
2637 if (match(RHS, m_Zero()))
2638 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002639
2640 if (OCF == OCF_SIGNED_SUB) {
2641 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2642 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2643 true);
2644 } else {
2645 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2646 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2647 true);
2648 }
2649 break;
2650 }
2651
2652 case OCF_UNSIGNED_MUL: {
2653 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2654 if (OR == OverflowResult::NeverOverflows)
2655 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2656 true);
2657 if (OR == OverflowResult::AlwaysOverflows)
2658 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
2659 } // FALL THROUGH
2660 case OCF_SIGNED_MUL:
2661 // X * undef -> undef
2662 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002663 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002664
David Majnemer27e89ba2015-05-21 23:04:21 +00002665 // X * 0 -> {0, false}
2666 if (match(RHS, m_Zero()))
2667 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002668
David Majnemer27e89ba2015-05-21 23:04:21 +00002669 // X * 1 -> {X, false}
2670 if (match(RHS, m_One()))
2671 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002672
2673 if (OCF == OCF_SIGNED_MUL)
2674 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2675 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2676 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002677 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002678 }
2679
2680 return false;
2681}
2682
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002683/// \brief Recognize and process idiom involving test for multiplication
2684/// overflow.
2685///
2686/// The caller has matched a pattern of the form:
2687/// I = cmp u (mul(zext A, zext B), V
2688/// The function checks if this is a test for overflow and if so replaces
2689/// multiplication with call to 'mul.with.overflow' intrinsic.
2690///
2691/// \param I Compare instruction.
2692/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2693/// the compare instruction. Must be of integer type.
2694/// \param OtherVal The other argument of compare instruction.
2695/// \returns Instruction which must replace the compare instruction, NULL if no
2696/// replacement required.
2697static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2698 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002699 // Don't bother doing this transformation for pointers, don't do it for
2700 // vectors.
2701 if (!isa<IntegerType>(MulVal->getType()))
2702 return nullptr;
2703
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002704 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2705 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002706 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2707 if (!MulInstr)
2708 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002709 assert(MulInstr->getOpcode() == Instruction::Mul);
2710
David Majnemer634ca232014-11-01 23:46:05 +00002711 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2712 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002713 assert(LHS->getOpcode() == Instruction::ZExt);
2714 assert(RHS->getOpcode() == Instruction::ZExt);
2715 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2716
2717 // Calculate type and width of the result produced by mul.with.overflow.
2718 Type *TyA = A->getType(), *TyB = B->getType();
2719 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2720 WidthB = TyB->getPrimitiveSizeInBits();
2721 unsigned MulWidth;
2722 Type *MulType;
2723 if (WidthB > WidthA) {
2724 MulWidth = WidthB;
2725 MulType = TyB;
2726 } else {
2727 MulWidth = WidthA;
2728 MulType = TyA;
2729 }
2730
2731 // In order to replace the original mul with a narrower mul.with.overflow,
2732 // all uses must ignore upper bits of the product. The number of used low
2733 // bits must be not greater than the width of mul.with.overflow.
2734 if (MulVal->hasNUsesOrMore(2))
2735 for (User *U : MulVal->users()) {
2736 if (U == &I)
2737 continue;
2738 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2739 // Check if truncation ignores bits above MulWidth.
2740 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2741 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002742 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002743 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2744 // Check if AND ignores bits above MulWidth.
2745 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002746 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002747 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2748 const APInt &CVal = CI->getValue();
2749 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002750 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002751 }
2752 } else {
2753 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002754 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002755 }
2756 }
2757
2758 // Recognize patterns
2759 switch (I.getPredicate()) {
2760 case ICmpInst::ICMP_EQ:
2761 case ICmpInst::ICMP_NE:
2762 // Recognize pattern:
2763 // mulval = mul(zext A, zext B)
2764 // cmp eq/neq mulval, zext trunc mulval
2765 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2766 if (Zext->hasOneUse()) {
2767 Value *ZextArg = Zext->getOperand(0);
2768 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2769 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2770 break; //Recognized
2771 }
2772
2773 // Recognize pattern:
2774 // mulval = mul(zext A, zext B)
2775 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2776 ConstantInt *CI;
2777 Value *ValToMask;
2778 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2779 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002780 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002781 const APInt &CVal = CI->getValue() + 1;
2782 if (CVal.isPowerOf2()) {
2783 unsigned MaskWidth = CVal.logBase2();
2784 if (MaskWidth == MulWidth)
2785 break; // Recognized
2786 }
2787 }
Craig Topperf40110f2014-04-25 05:29:35 +00002788 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002789
2790 case ICmpInst::ICMP_UGT:
2791 // Recognize pattern:
2792 // mulval = mul(zext A, zext B)
2793 // cmp ugt mulval, max
2794 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2795 APInt MaxVal = APInt::getMaxValue(MulWidth);
2796 MaxVal = MaxVal.zext(CI->getBitWidth());
2797 if (MaxVal.eq(CI->getValue()))
2798 break; // Recognized
2799 }
Craig Topperf40110f2014-04-25 05:29:35 +00002800 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002801
2802 case ICmpInst::ICMP_UGE:
2803 // Recognize pattern:
2804 // mulval = mul(zext A, zext B)
2805 // cmp uge mulval, max+1
2806 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2807 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2808 if (MaxVal.eq(CI->getValue()))
2809 break; // Recognized
2810 }
Craig Topperf40110f2014-04-25 05:29:35 +00002811 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002812
2813 case ICmpInst::ICMP_ULE:
2814 // Recognize pattern:
2815 // mulval = mul(zext A, zext B)
2816 // cmp ule mulval, max
2817 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2818 APInt MaxVal = APInt::getMaxValue(MulWidth);
2819 MaxVal = MaxVal.zext(CI->getBitWidth());
2820 if (MaxVal.eq(CI->getValue()))
2821 break; // Recognized
2822 }
Craig Topperf40110f2014-04-25 05:29:35 +00002823 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002824
2825 case ICmpInst::ICMP_ULT:
2826 // Recognize pattern:
2827 // mulval = mul(zext A, zext B)
2828 // cmp ule mulval, max + 1
2829 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002830 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002831 if (MaxVal.eq(CI->getValue()))
2832 break; // Recognized
2833 }
Craig Topperf40110f2014-04-25 05:29:35 +00002834 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002835
2836 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002837 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002838 }
2839
2840 InstCombiner::BuilderTy *Builder = IC.Builder;
2841 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002842
2843 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2844 Value *MulA = A, *MulB = B;
2845 if (WidthA < MulWidth)
2846 MulA = Builder->CreateZExt(A, MulType);
2847 if (WidthB < MulWidth)
2848 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002849 Value *F = Intrinsic::getDeclaration(I.getModule(),
2850 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002851 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002852 IC.Worklist.Add(MulInstr);
2853
2854 // If there are uses of mul result other than the comparison, we know that
2855 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002856 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002857 if (MulVal->hasNUsesOrMore(2)) {
2858 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2859 for (User *U : MulVal->users()) {
2860 if (U == &I || U == OtherVal)
2861 continue;
2862 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2863 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00002864 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002865 else
2866 TI->setOperand(0, Mul);
2867 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2868 assert(BO->getOpcode() == Instruction::And);
2869 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2870 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2871 APInt ShortMask = CI->getValue().trunc(MulWidth);
2872 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2873 Instruction *Zext =
2874 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2875 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00002876 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002877 } else {
2878 llvm_unreachable("Unexpected Binary operation");
2879 }
2880 IC.Worklist.Add(cast<Instruction>(U));
2881 }
2882 }
2883 if (isa<Instruction>(OtherVal))
2884 IC.Worklist.Add(cast<Instruction>(OtherVal));
2885
2886 // The original icmp gets replaced with the overflow value, maybe inverted
2887 // depending on predicate.
2888 bool Inverse = false;
2889 switch (I.getPredicate()) {
2890 case ICmpInst::ICMP_NE:
2891 break;
2892 case ICmpInst::ICMP_EQ:
2893 Inverse = true;
2894 break;
2895 case ICmpInst::ICMP_UGT:
2896 case ICmpInst::ICMP_UGE:
2897 if (I.getOperand(0) == MulVal)
2898 break;
2899 Inverse = true;
2900 break;
2901 case ICmpInst::ICMP_ULT:
2902 case ICmpInst::ICMP_ULE:
2903 if (I.getOperand(1) == MulVal)
2904 break;
2905 Inverse = true;
2906 break;
2907 default:
2908 llvm_unreachable("Unexpected predicate");
2909 }
2910 if (Inverse) {
2911 Value *Res = Builder->CreateExtractValue(Call, 1);
2912 return BinaryOperator::CreateNot(Res);
2913 }
2914
2915 return ExtractValueInst::Create(Call, 1);
2916}
2917
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002918/// When performing a comparison against a constant, it is possible that not all
2919/// the bits in the LHS are demanded. This helper method computes the mask that
2920/// IS demanded.
Owen Andersond490c2d2011-01-11 00:36:45 +00002921static APInt DemandedBitsLHSMask(ICmpInst &I,
2922 unsigned BitWidth, bool isSignCheck) {
2923 if (isSignCheck)
2924 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002925
Owen Andersond490c2d2011-01-11 00:36:45 +00002926 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2927 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002928 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002929
Owen Andersond490c2d2011-01-11 00:36:45 +00002930 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002931 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002932 // correspond to the trailing ones of the comparand. The value of these
2933 // bits doesn't impact the outcome of the comparison, because any value
2934 // greater than the RHS must differ in a bit higher than these due to carry.
2935 case ICmpInst::ICMP_UGT: {
2936 unsigned trailingOnes = RHS.countTrailingOnes();
2937 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2938 return ~lowBitsSet;
2939 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002940
Owen Andersond490c2d2011-01-11 00:36:45 +00002941 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2942 // Any value less than the RHS must differ in a higher bit because of carries.
2943 case ICmpInst::ICMP_ULT: {
2944 unsigned trailingZeros = RHS.countTrailingZeros();
2945 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2946 return ~lowBitsSet;
2947 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002948
Owen Andersond490c2d2011-01-11 00:36:45 +00002949 default:
2950 return APInt::getAllOnesValue(BitWidth);
2951 }
Owen Andersond490c2d2011-01-11 00:36:45 +00002952}
Chris Lattner2188e402010-01-04 07:37:31 +00002953
Quentin Colombet5ab55552013-09-09 20:56:48 +00002954/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2955/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002956/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002957/// as subtract operands and their positions in those instructions.
2958/// The rational is that several architectures use the same instruction for
2959/// both subtract and cmp, thus it is better if the order of those operands
2960/// match.
2961/// \return true if Op0 and Op1 should be swapped.
2962static bool swapMayExposeCSEOpportunities(const Value * Op0,
2963 const Value * Op1) {
2964 // Filter out pointer value as those cannot appears directly in subtract.
2965 // FIXME: we may want to go through inttoptrs or bitcasts.
2966 if (Op0->getType()->isPointerTy())
2967 return false;
2968 // Count every uses of both Op0 and Op1 in a subtract.
2969 // Each time Op0 is the first operand, count -1: swapping is bad, the
2970 // subtract has already the same layout as the compare.
2971 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00002972 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00002973 // At the end, if the benefit is greater than 0, Op0 should come second to
2974 // expose more CSE opportunities.
2975 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002976 for (const User *U : Op0->users()) {
2977 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00002978 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2979 continue;
2980 // If Op0 is the first argument, this is not beneficial to swap the
2981 // arguments.
2982 int LocalSwapBenefits = -1;
2983 unsigned Op1Idx = 1;
2984 if (BinOp->getOperand(Op1Idx) == Op0) {
2985 Op1Idx = 0;
2986 LocalSwapBenefits = 1;
2987 }
2988 if (BinOp->getOperand(Op1Idx) != Op1)
2989 continue;
2990 GlobalSwapBenefits += LocalSwapBenefits;
2991 }
2992 return GlobalSwapBenefits > 0;
2993}
2994
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00002995/// \brief Check that one use is in the same block as the definition and all
2996/// other uses are in blocks dominated by a given block
2997///
2998/// \param DI Definition
2999/// \param UI Use
3000/// \param DB Block that must dominate all uses of \p DI outside
3001/// the parent block
3002/// \return true when \p UI is the only use of \p DI in the parent block
3003/// and all other uses of \p DI are in blocks dominated by \p DB.
3004///
3005bool InstCombiner::dominatesAllUses(const Instruction *DI,
3006 const Instruction *UI,
3007 const BasicBlock *DB) const {
3008 assert(DI && UI && "Instruction not defined\n");
3009 // ignore incomplete definitions
3010 if (!DI->getParent())
3011 return false;
3012 // DI and UI must be in the same block
3013 if (DI->getParent() != UI->getParent())
3014 return false;
3015 // Protect from self-referencing blocks
3016 if (DI->getParent() == DB)
3017 return false;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003018 for (const User *U : DI->users()) {
3019 auto *Usr = cast<Instruction>(U);
Justin Bogner99798402016-08-05 01:06:44 +00003020 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003021 return false;
3022 }
3023 return true;
3024}
3025
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003026/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003027static bool isChainSelectCmpBranch(const SelectInst *SI) {
3028 const BasicBlock *BB = SI->getParent();
3029 if (!BB)
3030 return false;
3031 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3032 if (!BI || BI->getNumSuccessors() != 2)
3033 return false;
3034 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3035 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3036 return false;
3037 return true;
3038}
3039
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003040/// \brief True when a select result is replaced by one of its operands
3041/// in select-icmp sequence. This will eventually result in the elimination
3042/// of the select.
3043///
3044/// \param SI Select instruction
3045/// \param Icmp Compare instruction
3046/// \param SIOpd Operand that replaces the select
3047///
3048/// Notes:
3049/// - The replacement is global and requires dominator information
3050/// - The caller is responsible for the actual replacement
3051///
3052/// Example:
3053///
3054/// entry:
3055/// %4 = select i1 %3, %C* %0, %C* null
3056/// %5 = icmp eq %C* %4, null
3057/// br i1 %5, label %9, label %7
3058/// ...
3059/// ; <label>:7 ; preds = %entry
3060/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3061/// ...
3062///
3063/// can be transformed to
3064///
3065/// %5 = icmp eq %C* %0, null
3066/// %6 = select i1 %3, i1 %5, i1 true
3067/// br i1 %6, label %9, label %7
3068/// ...
3069/// ; <label>:7 ; preds = %entry
3070/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3071///
3072/// Similar when the first operand of the select is a constant or/and
3073/// the compare is for not equal rather than equal.
3074///
3075/// NOTE: The function is only called when the select and compare constants
3076/// are equal, the optimization can work only for EQ predicates. This is not a
3077/// major restriction since a NE compare should be 'normalized' to an equal
3078/// compare, which usually happens in the combiner and test case
3079/// select-cmp-br.ll
3080/// checks for it.
3081bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3082 const ICmpInst *Icmp,
3083 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003084 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003085 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3086 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3087 // The check for the unique predecessor is not the best that can be
3088 // done. But it protects efficiently against cases like when SI's
3089 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3090 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3091 // replaced can be reached on either path. So the uniqueness check
3092 // guarantees that the path all uses of SI (outside SI's parent) are on
3093 // is disjoint from all other paths out of SI. But that information
3094 // is more expensive to compute, and the trade-off here is in favor
3095 // of compile-time.
3096 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3097 NumSel++;
3098 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3099 return true;
3100 }
3101 }
3102 return false;
3103}
3104
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003105/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3106/// it into the appropriate icmp lt or icmp gt instruction. This transform
3107/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00003108static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
3109 ICmpInst::Predicate Pred = I.getPredicate();
3110 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
3111 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
3112 return nullptr;
3113
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003114 Value *Op0 = I.getOperand(0);
3115 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003116 auto *Op1C = dyn_cast<Constant>(Op1);
3117 if (!Op1C)
3118 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003119
Sanjay Patele9b2c322016-05-17 00:57:57 +00003120 // Check if the constant operand can be safely incremented/decremented without
3121 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
3122 // the edge cases for us, so we just assert on them. For vectors, we must
3123 // handle the edge cases.
3124 Type *Op1Type = Op1->getType();
3125 bool IsSigned = I.isSigned();
3126 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00003127 auto *CI = dyn_cast<ConstantInt>(Op1C);
3128 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00003129 // A <= MAX -> TRUE ; A >= MIN -> TRUE
3130 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
3131 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00003132 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00003133 // are for scalar, we could remove the min/max checks. However, to do that,
3134 // we would have to use insertelement/shufflevector to replace edge values.
3135 unsigned NumElts = Op1Type->getVectorNumElements();
3136 for (unsigned i = 0; i != NumElts; ++i) {
3137 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00003138 if (!Elt)
3139 return nullptr;
3140
Sanjay Patele9b2c322016-05-17 00:57:57 +00003141 if (isa<UndefValue>(Elt))
3142 continue;
3143 // Bail out if we can't determine if this constant is min/max or if we
3144 // know that this constant is min/max.
3145 auto *CI = dyn_cast<ConstantInt>(Elt);
3146 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
3147 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003148 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00003149 } else {
3150 // ConstantExpr?
3151 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003152 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003153
Sanjay Patele9b2c322016-05-17 00:57:57 +00003154 // Increment or decrement the constant and set the new comparison predicate:
3155 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00003156 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003157 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
3158 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
3159 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003160}
3161
Chris Lattner2188e402010-01-04 07:37:31 +00003162Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3163 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003164 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003165 unsigned Op0Cplxity = getComplexity(Op0);
3166 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003167
Chris Lattner2188e402010-01-04 07:37:31 +00003168 /// Orders the operands of the compare so that they are listed from most
3169 /// complex to least complex. This puts constants before unary operators,
3170 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003171 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00003172 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003173 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003174 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003175 Changed = true;
3176 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003177
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003178 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +00003179 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003180 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003181
Pete Cooperbc5c5242011-12-01 03:58:40 +00003182 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003183 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00003184 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003185 Value *Cond, *SelectTrue, *SelectFalse;
3186 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003187 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003188 if (Value *V = dyn_castNegVal(SelectTrue)) {
3189 if (V == SelectFalse)
3190 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3191 }
3192 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3193 if (V == SelectTrue)
3194 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003195 }
3196 }
3197 }
3198
Chris Lattner229907c2011-07-18 04:54:35 +00003199 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003200
3201 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00003202 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003203 switch (I.getPredicate()) {
3204 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003205 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3206 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003207 return BinaryOperator::CreateNot(Xor);
3208 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003209 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00003210 return BinaryOperator::CreateXor(Op0, Op1);
3211
3212 case ICmpInst::ICMP_UGT:
3213 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
3214 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003215 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3216 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003217 return BinaryOperator::CreateAnd(Not, Op1);
3218 }
3219 case ICmpInst::ICMP_SGT:
3220 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
3221 // FALL THROUGH
3222 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003223 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003224 return BinaryOperator::CreateAnd(Not, Op0);
3225 }
3226 case ICmpInst::ICMP_UGE:
3227 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
3228 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003229 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3230 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003231 return BinaryOperator::CreateOr(Not, Op1);
3232 }
3233 case ICmpInst::ICMP_SGE:
3234 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
3235 // FALL THROUGH
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003236 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3237 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003238 return BinaryOperator::CreateOr(Not, Op0);
3239 }
3240 }
3241 }
3242
Sanjay Patele9b2c322016-05-17 00:57:57 +00003243 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003244 return NewICmp;
3245
Chris Lattner2188e402010-01-04 07:37:31 +00003246 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003247 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00003248 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003249 else // Get pointer size.
3250 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003251
Chris Lattner2188e402010-01-04 07:37:31 +00003252 bool isSignBit = false;
3253
3254 // See if we are doing a comparison with a constant.
3255 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00003256 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003257
Owen Anderson1294ea72010-12-17 18:08:00 +00003258 // Match the following pattern, which is a common idiom when writing
3259 // overflow-safe integer arithmetic function. The source performs an
3260 // addition in wider type, and explicitly checks for overflow using
3261 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
3262 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00003263 //
3264 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00003265 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00003266 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003267 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00003268 // sum = a + b
3269 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00003270 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00003271 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00003272 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00003273 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00003274 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00003275 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00003276 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003277
Philip Reamesec8a8b52016-03-09 21:05:07 +00003278 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3279 if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3280 if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3281 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3282 if (SPR.Flavor == SPF_SMIN) {
Philip Reames8f12eba2016-03-09 21:31:47 +00003283 if (isKnownPositive(A, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003284 return new ICmpInst(I.getPredicate(), B, CI);
Philip Reames8f12eba2016-03-09 21:31:47 +00003285 if (isKnownPositive(B, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003286 return new ICmpInst(I.getPredicate(), A, CI);
3287 }
3288 }
3289
3290
David Majnemera0afb552015-01-14 19:26:56 +00003291 // The following transforms are only 'worth it' if the only user of the
3292 // subtraction is the icmp.
3293 if (Op0->hasOneUse()) {
3294 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3295 if (I.isEquality() && CI->isZero() &&
3296 match(Op0, m_Sub(m_Value(A), m_Value(B))))
3297 return new ICmpInst(I.getPredicate(), A, B);
3298
3299 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3300 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3301 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3302 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3303
3304 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3305 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3306 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3307 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3308
3309 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3310 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3311 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3312 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3313
3314 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3315 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3316 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3317 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00003318 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003319
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003320 if (I.isEquality()) {
3321 ConstantInt *CI2;
3322 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3323 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00003324 // (icmp eq/ne (ashr/lshr const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003325 if (Instruction *Inst = foldICmpCstShrConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003326 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003327 }
David Majnemer59939ac2014-10-19 08:23:08 +00003328 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3329 // (icmp eq/ne (shl const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003330 if (Instruction *Inst = foldICmpCstShlConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003331 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00003332 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003333 }
3334
Chris Lattner2188e402010-01-04 07:37:31 +00003335 // If this comparison is a normal comparison, it demands all
3336 // bits, if it is a sign bit comparison, it only demands the sign bit.
3337 bool UnusedBit;
3338 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
Balaram Makam569eaec2016-05-04 21:32:14 +00003339
3340 // Canonicalize icmp instructions based on dominating conditions.
3341 BasicBlock *Parent = I.getParent();
3342 BasicBlock *Dom = Parent->getSinglePredecessor();
3343 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
3344 ICmpInst::Predicate Pred;
3345 BasicBlock *TrueBB, *FalseBB;
3346 ConstantInt *CI2;
3347 if (BI && match(BI, m_Br(m_ICmp(Pred, m_Specific(Op0), m_ConstantInt(CI2)),
3348 TrueBB, FalseBB)) &&
3349 TrueBB != FalseBB) {
3350 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(I.getPredicate(),
3351 CI->getValue());
3352 ConstantRange DominatingCR =
3353 (Parent == TrueBB)
3354 ? ConstantRange::makeExactICmpRegion(Pred, CI2->getValue())
3355 : ConstantRange::makeExactICmpRegion(
3356 CmpInst::getInversePredicate(Pred), CI2->getValue());
3357 ConstantRange Intersection = DominatingCR.intersectWith(CR);
3358 ConstantRange Difference = DominatingCR.difference(CR);
3359 if (Intersection.isEmptySet())
3360 return replaceInstUsesWith(I, Builder->getFalse());
3361 if (Difference.isEmptySet())
3362 return replaceInstUsesWith(I, Builder->getTrue());
3363 // Canonicalizing a sign bit comparison that gets used in a branch,
3364 // pessimizes codegen by generating branch on zero instruction instead
3365 // of a test and branch. So we avoid canonicalizing in such situations
3366 // because test and branch instruction has better branch displacement
3367 // than compare and branch instruction.
3368 if (!isBranchOnSignBitCheck(I, isSignBit) && !I.isEquality()) {
3369 if (auto *AI = Intersection.getSingleElement())
3370 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Builder->getInt(*AI));
3371 if (auto *AD = Difference.getSingleElement())
3372 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Builder->getInt(*AD));
3373 }
3374 }
Chris Lattner2188e402010-01-04 07:37:31 +00003375 }
3376
3377 // See if we can fold the comparison based on range information we can get
3378 // by checking whether bits are known to be zero or one in the input.
3379 if (BitWidth != 0) {
3380 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3381 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3382
3383 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00003384 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00003385 Op0KnownZero, Op0KnownOne, 0))
3386 return &I;
3387 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003388 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
3389 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00003390 return &I;
3391
3392 // Given the known and unknown bits, compute a range that the LHS could be
3393 // in. Compute the Min, Max and RHS values based on the known bits. For the
3394 // EQ and NE we use unsigned values.
3395 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3396 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3397 if (I.isSigned()) {
3398 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3399 Op0Min, Op0Max);
3400 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3401 Op1Min, Op1Max);
3402 } else {
3403 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3404 Op0Min, Op0Max);
3405 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3406 Op1Min, Op1Max);
3407 }
3408
3409 // If Min and Max are known to be the same, then SimplifyDemandedBits
3410 // figured out that the LHS is a constant. Just constant fold this now so
3411 // that code below can assume that Min != Max.
3412 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3413 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00003414 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003415 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3416 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00003417 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00003418
3419 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00003420 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00003421 switch (I.getPredicate()) {
3422 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00003423 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00003424 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003425 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003426
Chris Lattnerf7e89612010-11-21 06:44:42 +00003427 // If all bits are known zero except for one, then we know at most one
3428 // bit is set. If the comparison is against zero, then this is a check
3429 // to see if *that* bit is set.
3430 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003431 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003432 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003433 Value *LHS = nullptr;
3434 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003435 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3436 LHSC->getValue() != Op0KnownZeroInverted)
3437 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003438
Chris Lattnerf7e89612010-11-21 06:44:42 +00003439 // 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 +00003440 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003441 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00003442 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003443 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003444 APInt ValToCheck = Op0KnownZeroInverted;
3445 if (ValToCheck.isPowerOf2()) {
3446 unsigned CmpVal = ValToCheck.countTrailingZeros();
3447 return new ICmpInst(ICmpInst::ICMP_NE, X,
3448 ConstantInt::get(X->getType(), CmpVal));
3449 } else if ((++ValToCheck).isPowerOf2()) {
3450 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3451 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3452 ConstantInt::get(X->getType(), CmpVal));
3453 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003454 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003455
Chris Lattnerf7e89612010-11-21 06:44:42 +00003456 // 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 +00003457 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00003458 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003459 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003460 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003461 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00003462 ConstantInt::get(X->getType(),
3463 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003464 }
Chris Lattner2188e402010-01-04 07:37:31 +00003465 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003466 }
3467 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00003468 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003469 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003470
Chris Lattnerf7e89612010-11-21 06:44:42 +00003471 // If all bits are known zero except for one, then we know at most one
3472 // bit is set. If the comparison is against zero, then this is a check
3473 // to see if *that* bit is set.
3474 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003475 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003476 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003477 Value *LHS = nullptr;
3478 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003479 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3480 LHSC->getValue() != Op0KnownZeroInverted)
3481 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003482
Chris Lattnerf7e89612010-11-21 06:44:42 +00003483 // 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 +00003484 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003485 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00003486 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003487 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003488 APInt ValToCheck = Op0KnownZeroInverted;
3489 if (ValToCheck.isPowerOf2()) {
3490 unsigned CmpVal = ValToCheck.countTrailingZeros();
3491 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3492 ConstantInt::get(X->getType(), CmpVal));
3493 } else if ((++ValToCheck).isPowerOf2()) {
3494 unsigned CmpVal = ValToCheck.countTrailingZeros();
3495 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3496 ConstantInt::get(X->getType(), CmpVal));
3497 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003498 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003499
Chris Lattnerf7e89612010-11-21 06:44:42 +00003500 // 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 +00003501 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00003502 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003503 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003504 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003505 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00003506 ConstantInt::get(X->getType(),
3507 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003508 }
Chris Lattner2188e402010-01-04 07:37:31 +00003509 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003510 }
Chris Lattner2188e402010-01-04 07:37:31 +00003511 case ICmpInst::ICMP_ULT:
3512 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003513 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003514 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003515 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003516 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3517 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3518 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3519 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
3520 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003521 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003522
3523 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3524 if (CI->isMinValue(true))
3525 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3526 Constant::getAllOnesValue(Op0->getType()));
3527 }
3528 break;
3529 case ICmpInst::ICMP_UGT:
3530 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003531 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003532 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003533 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003534
3535 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3536 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3537 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3538 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
3539 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003540 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003541
3542 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3543 if (CI->isMaxValue(true))
3544 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3545 Constant::getNullValue(Op0->getType()));
3546 }
3547 break;
3548 case ICmpInst::ICMP_SLT:
3549 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003550 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003551 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003552 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003553 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3554 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3555 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3556 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3557 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003558 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003559 }
3560 break;
3561 case ICmpInst::ICMP_SGT:
3562 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003563 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003564 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003565 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003566
3567 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3568 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3569 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3570 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3571 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003572 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003573 }
3574 break;
3575 case ICmpInst::ICMP_SGE:
3576 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3577 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003578 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003579 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003580 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003581 break;
3582 case ICmpInst::ICMP_SLE:
3583 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3584 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003585 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003586 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003587 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003588 break;
3589 case ICmpInst::ICMP_UGE:
3590 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3591 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003592 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003593 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003594 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003595 break;
3596 case ICmpInst::ICMP_ULE:
3597 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3598 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003599 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003600 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003601 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003602 break;
3603 }
3604
3605 // Turn a signed comparison into an unsigned one if both operands
3606 // are known to have the same sign.
3607 if (I.isSigned() &&
3608 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3609 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3610 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3611 }
3612
3613 // Test if the ICmpInst instruction is used exclusively by a select as
3614 // part of a minimum or maximum operation. If so, refrain from doing
3615 // any other folding. This helps out other analyses which understand
3616 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3617 // and CodeGen. And in this case, at least one of the comparison
3618 // operands has at least one user besides the compare (the select),
3619 // which would often largely negate the benefit of folding anyway.
3620 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003621 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003622 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3623 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003624 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003625
3626 // See if we are doing a comparison between a constant and an instruction that
3627 // can be folded into the comparison.
Sanjay Patel1271bf92016-07-23 13:06:49 +00003628
3629 // FIXME: Use m_APInt instead of dyn_cast<ConstantInt> to allow these
3630 // transforms for vectors.
3631
Chris Lattner2188e402010-01-04 07:37:31 +00003632 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003633 // Since the RHS is a ConstantInt (CI), if the left hand side is an
3634 // instruction, see if that instruction also has constants so that the
3635 // instruction can be folded into the icmp
Sanjay Patelab50a932016-08-02 22:38:33 +00003636 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00003637 if (Instruction *Res = foldICmpWithConstant(I, LHSI, CI))
Chris Lattner2188e402010-01-04 07:37:31 +00003638 return Res;
3639 }
3640
Sanjay Patelab50a932016-08-02 22:38:33 +00003641 if (Instruction *Res = foldICmpEqualityWithConstant(I))
3642 return Res;
3643
Sanjay Patel1271bf92016-07-23 13:06:49 +00003644 if (Instruction *Res = foldICmpIntrinsicWithConstant(I))
3645 return Res;
3646
Chris Lattner2188e402010-01-04 07:37:31 +00003647 // Handle icmp with constant (but not simple integer constant) RHS
3648 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3649 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3650 switch (LHSI->getOpcode()) {
3651 case Instruction::GetElementPtr:
3652 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3653 if (RHSC->isNullValue() &&
3654 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3655 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3656 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3657 break;
3658 case Instruction::PHI:
3659 // Only fold icmp into the PHI if the phi and icmp are in the same
3660 // block. If in the same block, we're encouraging jump threading. If
3661 // not, we are just pessimizing the code by making an i1 phi.
3662 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003663 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003664 return NV;
3665 break;
3666 case Instruction::Select: {
3667 // If either operand of the select is a constant, we can fold the
3668 // comparison into the select arms, which will cause one to be
3669 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003670 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003671 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003672 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003673 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003674 CI = dyn_cast<ConstantInt>(Op1);
3675 }
3676 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003677 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003678 CI = dyn_cast<ConstantInt>(Op2);
3679 }
Chris Lattner2188e402010-01-04 07:37:31 +00003680
3681 // We only want to perform this transformation if it will not lead to
3682 // additional code. This is true if either both sides of the select
3683 // fold to a constant (in which case the icmp is replaced with a select
3684 // which will usually simplify) or this is the only user of the
3685 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003686 // select+icmp) or all uses of the select can be replaced based on
3687 // dominance information ("Global cases").
3688 bool Transform = false;
3689 if (Op1 && Op2)
3690 Transform = true;
3691 else if (Op1 || Op2) {
3692 // Local case
3693 if (LHSI->hasOneUse())
3694 Transform = true;
3695 // Global cases
3696 else if (CI && !CI->isZero())
3697 // When Op1 is constant try replacing select with second operand.
3698 // Otherwise Op2 is constant and try replacing select with first
3699 // operand.
3700 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3701 Op1 ? 2 : 1);
3702 }
3703 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003704 if (!Op1)
3705 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3706 RHSC, I.getName());
3707 if (!Op2)
3708 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3709 RHSC, I.getName());
3710 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3711 }
3712 break;
3713 }
Chris Lattner2188e402010-01-04 07:37:31 +00003714 case Instruction::IntToPtr:
3715 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003716 if (RHSC->isNullValue() &&
3717 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003718 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3719 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3720 break;
3721
3722 case Instruction::Load:
3723 // Try to optimize things like "A[i] > 4" to index computations.
3724 if (GetElementPtrInst *GEP =
3725 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3726 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3727 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3728 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00003729 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Chris Lattner2188e402010-01-04 07:37:31 +00003730 return Res;
3731 }
3732 break;
3733 }
3734 }
3735
3736 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3737 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00003738 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner2188e402010-01-04 07:37:31 +00003739 return NI;
3740 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003741 if (Instruction *NI = foldGEPICmp(GEP, Op0,
Chris Lattner2188e402010-01-04 07:37:31 +00003742 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3743 return NI;
3744
Hans Wennborgf1f36512015-10-07 00:20:07 +00003745 // Try to optimize equality comparisons against alloca-based pointers.
3746 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3747 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3748 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003749 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003750 return New;
3751 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003752 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003753 return New;
3754 }
3755
Chris Lattner2188e402010-01-04 07:37:31 +00003756 // Test to see if the operands of the icmp are casted versions of other
3757 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3758 // now.
3759 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003760 if (Op0->getType()->isPointerTy() &&
3761 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003762 // We keep moving the cast from the left operand over to the right
3763 // operand, where it can often be eliminated completely.
3764 Op0 = CI->getOperand(0);
3765
3766 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3767 // so eliminate it as well.
3768 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3769 Op1 = CI2->getOperand(0);
3770
3771 // If Op1 is a constant, we can fold the cast into the constant.
3772 if (Op0->getType() != Op1->getType()) {
3773 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3774 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3775 } else {
3776 // Otherwise, cast the RHS right before the icmp
3777 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3778 }
3779 }
3780 return new ICmpInst(I.getPredicate(), Op0, Op1);
3781 }
3782 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003783
Chris Lattner2188e402010-01-04 07:37:31 +00003784 if (isa<CastInst>(Op0)) {
3785 // Handle the special case of: icmp (cast bool to X), <cst>
3786 // This comes up when you have code like
3787 // int X = A < B;
3788 // if (X) ...
3789 // For generality, we handle any zero-extension of any operand comparison
3790 // with a constant or another cast from the same type.
3791 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003792 if (Instruction *R = foldICmpWithCastAndCast(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003793 return R;
3794 }
Chris Lattner2188e402010-01-04 07:37:31 +00003795
Duncan Sandse5220012011-02-17 07:46:37 +00003796 // Special logic for binary operators.
3797 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3798 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3799 if (BO0 || BO1) {
3800 CmpInst::Predicate Pred = I.getPredicate();
3801 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3802 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3803 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3804 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3805 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3806 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3807 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3808 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3809 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3810
3811 // Analyze the case when either Op0 or Op1 is an add instruction.
3812 // 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 +00003813 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003814 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3815 A = BO0->getOperand(0);
3816 B = BO0->getOperand(1);
3817 }
3818 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3819 C = BO1->getOperand(0);
3820 D = BO1->getOperand(1);
3821 }
Duncan Sandse5220012011-02-17 07:46:37 +00003822
David Majnemer549f4f22014-11-01 09:09:51 +00003823 // icmp (X+cst) < 0 --> X < -cst
3824 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3825 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3826 if (!RHSC->isMinValue(/*isSigned=*/true))
3827 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3828
Duncan Sandse5220012011-02-17 07:46:37 +00003829 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3830 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3831 return new ICmpInst(Pred, A == Op1 ? B : A,
3832 Constant::getNullValue(Op1->getType()));
3833
3834 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3835 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3836 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3837 C == Op0 ? D : C);
3838
Duncan Sands84653b32011-02-18 16:25:37 +00003839 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003840 if (A && C && (A == C || A == D || B == C || B == D) &&
3841 NoOp0WrapProblem && NoOp1WrapProblem &&
3842 // Try not to increase register pressure.
3843 BO0->hasOneUse() && BO1->hasOneUse()) {
3844 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003845 Value *Y, *Z;
3846 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003847 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003848 Y = B;
3849 Z = D;
3850 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003851 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003852 Y = B;
3853 Z = C;
3854 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003855 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003856 Y = A;
3857 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003858 } else {
3859 assert(B == D);
3860 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003861 Y = A;
3862 Z = C;
3863 }
Duncan Sandse5220012011-02-17 07:46:37 +00003864 return new ICmpInst(Pred, Y, Z);
3865 }
3866
David Majnemerb81cd632013-04-11 20:05:46 +00003867 // icmp slt (X + -1), Y -> icmp sle X, Y
3868 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3869 match(B, m_AllOnes()))
3870 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3871
3872 // icmp sge (X + -1), Y -> icmp sgt X, Y
3873 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3874 match(B, m_AllOnes()))
3875 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3876
3877 // icmp sle (X + 1), Y -> icmp slt X, Y
3878 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3879 match(B, m_One()))
3880 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3881
3882 // icmp sgt (X + 1), Y -> icmp sge X, Y
3883 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3884 match(B, m_One()))
3885 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3886
Michael Liaoc65d3862015-10-19 22:08:14 +00003887 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3888 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3889 match(D, m_AllOnes()))
3890 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3891
3892 // icmp sle X, (Y + -1) -> icmp slt X, Y
3893 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3894 match(D, m_AllOnes()))
3895 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3896
3897 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3898 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3899 match(D, m_One()))
3900 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3901
3902 // icmp slt X, (Y + 1) -> icmp sle X, Y
3903 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3904 match(D, m_One()))
3905 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3906
David Majnemerb81cd632013-04-11 20:05:46 +00003907 // if C1 has greater magnitude than C2:
3908 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3909 // s.t. C3 = C1 - C2
3910 //
3911 // if C2 has greater magnitude than C1:
3912 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3913 // s.t. C3 = C2 - C1
3914 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3915 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3916 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3917 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3918 const APInt &AP1 = C1->getValue();
3919 const APInt &AP2 = C2->getValue();
3920 if (AP1.isNegative() == AP2.isNegative()) {
3921 APInt AP1Abs = C1->getValue().abs();
3922 APInt AP2Abs = C2->getValue().abs();
3923 if (AP1Abs.uge(AP2Abs)) {
3924 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3925 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3926 return new ICmpInst(Pred, NewAdd, C);
3927 } else {
3928 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3929 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3930 return new ICmpInst(Pred, A, NewAdd);
3931 }
3932 }
3933 }
3934
3935
Duncan Sandse5220012011-02-17 07:46:37 +00003936 // Analyze the case when either Op0 or Op1 is a sub instruction.
3937 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
Richard Trieu7a083812016-02-18 22:09:30 +00003938 A = nullptr;
3939 B = nullptr;
3940 C = nullptr;
3941 D = nullptr;
3942 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3943 A = BO0->getOperand(0);
3944 B = BO0->getOperand(1);
3945 }
3946 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3947 C = BO1->getOperand(0);
3948 D = BO1->getOperand(1);
3949 }
Duncan Sandse5220012011-02-17 07:46:37 +00003950
Duncan Sands84653b32011-02-18 16:25:37 +00003951 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3952 if (A == Op1 && NoOp0WrapProblem)
3953 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3954
3955 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
3956 if (C == Op0 && NoOp1WrapProblem)
3957 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
3958
3959 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003960 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
3961 // Try not to increase register pressure.
3962 BO0->hasOneUse() && BO1->hasOneUse())
3963 return new ICmpInst(Pred, A, C);
3964
Duncan Sands84653b32011-02-18 16:25:37 +00003965 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
3966 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3967 // Try not to increase register pressure.
3968 BO0->hasOneUse() && BO1->hasOneUse())
3969 return new ICmpInst(Pred, D, B);
3970
David Majnemer186c9422014-05-15 00:02:20 +00003971 // icmp (0-X) < cst --> x > -cst
3972 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
3973 Value *X;
3974 if (match(BO0, m_Neg(m_Value(X))))
3975 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
3976 if (!RHSC->isMinValue(/*isSigned=*/true))
3977 return new ICmpInst(I.getSwappedPredicate(), X,
3978 ConstantExpr::getNeg(RHSC));
3979 }
3980
Craig Topperf40110f2014-04-25 05:29:35 +00003981 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003982 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00003983 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
3984 Op1 == BO0->getOperand(1))
3985 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00003986 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00003987 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3988 Op0 == BO1->getOperand(1))
3989 SRem = BO1;
3990 if (SRem) {
3991 // We don't check hasOneUse to avoid increasing register pressure because
3992 // the value we use is the same value this instruction was already using.
3993 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
3994 default: break;
3995 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00003996 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003997 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00003998 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00003999 case ICmpInst::ICMP_SGT:
4000 case ICmpInst::ICMP_SGE:
4001 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4002 Constant::getAllOnesValue(SRem->getType()));
4003 case ICmpInst::ICMP_SLT:
4004 case ICmpInst::ICMP_SLE:
4005 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4006 Constant::getNullValue(SRem->getType()));
4007 }
4008 }
4009
Duncan Sandse5220012011-02-17 07:46:37 +00004010 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
4011 BO0->hasOneUse() && BO1->hasOneUse() &&
4012 BO0->getOperand(1) == BO1->getOperand(1)) {
4013 switch (BO0->getOpcode()) {
4014 default: break;
4015 case Instruction::Add:
4016 case Instruction::Sub:
4017 case Instruction::Xor:
4018 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4019 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4020 BO1->getOperand(0));
4021 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
4022 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4023 if (CI->getValue().isSignBit()) {
4024 ICmpInst::Predicate Pred = I.isSigned()
4025 ? I.getUnsignedPredicate()
4026 : I.getSignedPredicate();
4027 return new ICmpInst(Pred, BO0->getOperand(0),
4028 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00004029 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004030
David Majnemerf8853ae2016-02-01 17:37:56 +00004031 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00004032 ICmpInst::Predicate Pred = I.isSigned()
4033 ? I.getUnsignedPredicate()
4034 : I.getSignedPredicate();
4035 Pred = I.getSwappedPredicate(Pred);
4036 return new ICmpInst(Pred, BO0->getOperand(0),
4037 BO1->getOperand(0));
4038 }
Chris Lattner2188e402010-01-04 07:37:31 +00004039 }
Duncan Sandse5220012011-02-17 07:46:37 +00004040 break;
4041 case Instruction::Mul:
4042 if (!I.isEquality())
4043 break;
4044
4045 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4046 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
4047 // Mask = -1 >> count-trailing-zeros(Cst).
4048 if (!CI->isZero() && !CI->isOne()) {
4049 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004050 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00004051 APInt::getLowBitsSet(AP.getBitWidth(),
4052 AP.getBitWidth() -
4053 AP.countTrailingZeros()));
4054 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4055 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4056 return new ICmpInst(I.getPredicate(), And1, And2);
4057 }
4058 }
4059 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00004060 case Instruction::UDiv:
4061 case Instruction::LShr:
4062 if (I.isSigned())
4063 break;
4064 // fall-through
4065 case Instruction::SDiv:
4066 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00004067 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00004068 break;
4069 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4070 BO1->getOperand(0));
4071 case Instruction::Shl: {
4072 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4073 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4074 if (!NUW && !NSW)
4075 break;
4076 if (!NSW && I.isSigned())
4077 break;
4078 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4079 BO1->getOperand(0));
4080 }
Chris Lattner2188e402010-01-04 07:37:31 +00004081 }
4082 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00004083
4084 if (BO0) {
4085 // Transform A & (L - 1) `ult` L --> L != 0
4086 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4087 auto BitwiseAnd =
4088 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4089
4090 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4091 auto *Zero = Constant::getNullValue(BO0->getType());
4092 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4093 }
4094 }
Chris Lattner2188e402010-01-04 07:37:31 +00004095 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004096
Chris Lattner2188e402010-01-04 07:37:31 +00004097 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004098 // Transform (A & ~B) == 0 --> (A & B) != 0
4099 // and (A & ~B) != 0 --> (A & B) == 0
4100 // if A is a power of 2.
4101 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004102 match(Op1, m_Zero()) &&
Justin Bogner99798402016-08-05 01:06:44 +00004103 isKnownToBeAPowerOfTwo(A, DL, false, 0, &AC, &I, &DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004104 return new ICmpInst(I.getInversePredicate(),
4105 Builder->CreateAnd(A, B),
4106 Op1);
4107
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004108 // ~x < ~y --> y < x
4109 // ~x < cst --> ~cst < x
4110 if (match(Op0, m_Not(m_Value(A)))) {
4111 if (match(Op1, m_Not(m_Value(B))))
4112 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004113 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004114 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4115 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004116
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004117 Instruction *AddI = nullptr;
4118 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4119 m_Instruction(AddI))) &&
4120 isa<IntegerType>(A->getType())) {
4121 Value *Result;
4122 Constant *Overflow;
4123 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4124 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004125 replaceInstUsesWith(*AddI, Result);
4126 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004127 }
4128 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004129
4130 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4131 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4132 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4133 return R;
4134 }
4135 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4136 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4137 return R;
4138 }
Chris Lattner2188e402010-01-04 07:37:31 +00004139 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004140
Chris Lattner2188e402010-01-04 07:37:31 +00004141 if (I.isEquality()) {
4142 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004143
Chris Lattner2188e402010-01-04 07:37:31 +00004144 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4145 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4146 Value *OtherVal = A == Op1 ? B : A;
4147 return new ICmpInst(I.getPredicate(), OtherVal,
4148 Constant::getNullValue(A->getType()));
4149 }
4150
4151 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4152 // A^c1 == C^c2 --> A == C^(c1^c2)
4153 ConstantInt *C1, *C2;
4154 if (match(B, m_ConstantInt(C1)) &&
4155 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004156 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004157 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004158 return new ICmpInst(I.getPredicate(), A, Xor);
4159 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004160
Chris Lattner2188e402010-01-04 07:37:31 +00004161 // A^B == A^D -> B == D
4162 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4163 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4164 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4165 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4166 }
4167 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004168
Chris Lattner2188e402010-01-04 07:37:31 +00004169 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4170 (A == Op0 || B == Op0)) {
4171 // A == (A^B) -> B == 0
4172 Value *OtherVal = A == Op0 ? B : A;
4173 return new ICmpInst(I.getPredicate(), OtherVal,
4174 Constant::getNullValue(A->getType()));
4175 }
4176
Chris Lattner2188e402010-01-04 07:37:31 +00004177 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004178 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004179 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004180 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004181
Chris Lattner2188e402010-01-04 07:37:31 +00004182 if (A == C) {
4183 X = B; Y = D; Z = A;
4184 } else if (A == D) {
4185 X = B; Y = C; Z = A;
4186 } else if (B == C) {
4187 X = A; Y = D; Z = B;
4188 } else if (B == D) {
4189 X = A; Y = C; Z = B;
4190 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004191
Chris Lattner2188e402010-01-04 07:37:31 +00004192 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004193 Op1 = Builder->CreateXor(X, Y);
4194 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004195 I.setOperand(0, Op1);
4196 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4197 return &I;
4198 }
4199 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004200
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004201 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004202 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004203 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004204 if ((Op0->hasOneUse() &&
4205 match(Op0, m_ZExt(m_Value(A))) &&
4206 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4207 (Op1->hasOneUse() &&
4208 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4209 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004210 APInt Pow2 = Cst1->getValue() + 1;
4211 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4212 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4213 return new ICmpInst(I.getPredicate(), A,
4214 Builder->CreateTrunc(B, A->getType()));
4215 }
4216
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004217 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4218 // For lshr and ashr pairs.
4219 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4220 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4221 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4222 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4223 unsigned TypeBits = Cst1->getBitWidth();
4224 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4225 if (ShAmt < TypeBits && ShAmt != 0) {
4226 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4227 ? ICmpInst::ICMP_UGE
4228 : ICmpInst::ICMP_ULT;
4229 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4230 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4231 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4232 }
4233 }
4234
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004235 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4236 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4237 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4238 unsigned TypeBits = Cst1->getBitWidth();
4239 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4240 if (ShAmt < TypeBits && ShAmt != 0) {
4241 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4242 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4243 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4244 I.getName() + ".mask");
4245 return new ICmpInst(I.getPredicate(), And,
4246 Constant::getNullValue(Cst1->getType()));
4247 }
4248 }
4249
Chris Lattner1b06c712011-04-26 20:18:20 +00004250 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4251 // "icmp (and X, mask), cst"
4252 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004253 if (Op0->hasOneUse() &&
4254 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4255 m_ConstantInt(ShAmt))))) &&
4256 match(Op1, m_ConstantInt(Cst1)) &&
4257 // Only do this when A has multiple uses. This is most important to do
4258 // when it exposes other optimizations.
4259 !A->hasOneUse()) {
4260 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004261
Chris Lattner1b06c712011-04-26 20:18:20 +00004262 if (ShAmt < ASize) {
4263 APInt MaskV =
4264 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4265 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004266
Chris Lattner1b06c712011-04-26 20:18:20 +00004267 APInt CmpV = Cst1->getValue().zext(ASize);
4268 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004269
Chris Lattner1b06c712011-04-26 20:18:20 +00004270 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4271 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4272 }
4273 }
Chris Lattner2188e402010-01-04 07:37:31 +00004274 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004275
David Majnemerc1eca5a2014-11-06 23:23:30 +00004276 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4277 // an i1 which indicates whether or not we successfully did the swap.
4278 //
4279 // Replace comparisons between the old value and the expected value with the
4280 // indicator that 'cmpxchg' returns.
4281 //
4282 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4283 // spuriously fail. In those cases, the old value may equal the expected
4284 // value but it is possible for the swap to not occur.
4285 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4286 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4287 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4288 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4289 !ACXI->isWeak())
4290 return ExtractValueInst::Create(ACXI, 1);
4291
Chris Lattner2188e402010-01-04 07:37:31 +00004292 {
4293 Value *X; ConstantInt *Cst;
4294 // icmp X+Cst, X
4295 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004296 return foldICmpAddOpConst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004297
4298 // icmp X, X+Cst
4299 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004300 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004301 }
Craig Topperf40110f2014-04-25 05:29:35 +00004302 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004303}
4304
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004305/// Fold fcmp ([us]itofp x, cst) if possible.
Sanjay Patel43395062016-07-21 18:07:40 +00004306Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
Chris Lattner2188e402010-01-04 07:37:31 +00004307 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004308 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004309 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004310
Chris Lattner2188e402010-01-04 07:37:31 +00004311 // Get the width of the mantissa. We don't want to hack on conversions that
4312 // might lose information from the integer, e.g. "i64 -> float"
4313 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004314 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004315
Matt Arsenault55e73122015-01-06 15:50:59 +00004316 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4317
Chris Lattner2188e402010-01-04 07:37:31 +00004318 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004319
Matt Arsenault55e73122015-01-06 15:50:59 +00004320 if (I.isEquality()) {
4321 FCmpInst::Predicate P = I.getPredicate();
4322 bool IsExact = false;
4323 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4324 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4325
4326 // If the floating point constant isn't an integer value, we know if we will
4327 // ever compare equal / not equal to it.
4328 if (!IsExact) {
4329 // TODO: Can never be -0.0 and other non-representable values
4330 APFloat RHSRoundInt(RHS);
4331 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4332 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4333 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004334 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004335
4336 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004337 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004338 }
4339 }
4340
4341 // TODO: If the constant is exactly representable, is it always OK to do
4342 // equality compares as integer?
4343 }
4344
Arch D. Robison8ed08542015-09-15 17:51:59 +00004345 // Check to see that the input is converted from an integer type that is small
4346 // enough that preserves all bits. TODO: check here for "known" sign bits.
4347 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4348 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004349
Arch D. Robison8ed08542015-09-15 17:51:59 +00004350 // Following test does NOT adjust InputSize downwards for signed inputs,
4351 // because the most negative value still requires all the mantissa bits
4352 // to distinguish it from one less than that value.
4353 if ((int)InputSize > MantissaWidth) {
4354 // Conversion would lose accuracy. Check if loss can impact comparison.
4355 int Exp = ilogb(RHS);
4356 if (Exp == APFloat::IEK_Inf) {
4357 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
4358 if (MaxExponent < (int)InputSize - !LHSUnsigned)
4359 // Conversion could create infinity.
4360 return nullptr;
4361 } else {
4362 // Note that if RHS is zero or NaN, then Exp is negative
4363 // and first condition is trivially false.
4364 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
4365 // Conversion could affect comparison.
4366 return nullptr;
4367 }
4368 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004369
Chris Lattner2188e402010-01-04 07:37:31 +00004370 // Otherwise, we can potentially simplify the comparison. We know that it
4371 // will always come through as an integer value and we know the constant is
4372 // not a NAN (it would have been previously simplified).
4373 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004374
Chris Lattner2188e402010-01-04 07:37:31 +00004375 ICmpInst::Predicate Pred;
4376 switch (I.getPredicate()) {
4377 default: llvm_unreachable("Unexpected predicate!");
4378 case FCmpInst::FCMP_UEQ:
4379 case FCmpInst::FCMP_OEQ:
4380 Pred = ICmpInst::ICMP_EQ;
4381 break;
4382 case FCmpInst::FCMP_UGT:
4383 case FCmpInst::FCMP_OGT:
4384 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4385 break;
4386 case FCmpInst::FCMP_UGE:
4387 case FCmpInst::FCMP_OGE:
4388 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4389 break;
4390 case FCmpInst::FCMP_ULT:
4391 case FCmpInst::FCMP_OLT:
4392 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4393 break;
4394 case FCmpInst::FCMP_ULE:
4395 case FCmpInst::FCMP_OLE:
4396 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4397 break;
4398 case FCmpInst::FCMP_UNE:
4399 case FCmpInst::FCMP_ONE:
4400 Pred = ICmpInst::ICMP_NE;
4401 break;
4402 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004403 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004404 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004405 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004406 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004407
Chris Lattner2188e402010-01-04 07:37:31 +00004408 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004409
Chris Lattner2188e402010-01-04 07:37:31 +00004410 // See if the FP constant is too large for the integer. For example,
4411 // comparing an i8 to 300.0.
4412 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004413
Chris Lattner2188e402010-01-04 07:37:31 +00004414 if (!LHSUnsigned) {
4415 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4416 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004417 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004418 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4419 APFloat::rmNearestTiesToEven);
4420 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4421 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4422 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004423 return replaceInstUsesWith(I, Builder->getTrue());
4424 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004425 }
4426 } else {
4427 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4428 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004429 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004430 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4431 APFloat::rmNearestTiesToEven);
4432 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4433 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4434 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004435 return replaceInstUsesWith(I, Builder->getTrue());
4436 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004437 }
4438 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004439
Chris Lattner2188e402010-01-04 07:37:31 +00004440 if (!LHSUnsigned) {
4441 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004442 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004443 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4444 APFloat::rmNearestTiesToEven);
4445 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4446 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4447 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004448 return replaceInstUsesWith(I, Builder->getTrue());
4449 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004450 }
Devang Patel698452b2012-02-13 23:05:18 +00004451 } else {
4452 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004453 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004454 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4455 APFloat::rmNearestTiesToEven);
4456 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4457 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4458 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004459 return replaceInstUsesWith(I, Builder->getTrue());
4460 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004461 }
Chris Lattner2188e402010-01-04 07:37:31 +00004462 }
4463
4464 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4465 // [0, UMAX], but it may still be fractional. See if it is fractional by
4466 // casting the FP value to the integer value and back, checking for equality.
4467 // Don't do this for zero, because -0.0 is not fractional.
4468 Constant *RHSInt = LHSUnsigned
4469 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4470 : ConstantExpr::getFPToSI(RHSC, IntTy);
4471 if (!RHS.isZero()) {
4472 bool Equal = LHSUnsigned
4473 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4474 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4475 if (!Equal) {
4476 // If we had a comparison against a fractional value, we have to adjust
4477 // the compare predicate and sometimes the value. RHSC is rounded towards
4478 // zero at this point.
4479 switch (Pred) {
4480 default: llvm_unreachable("Unexpected integer comparison!");
4481 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004482 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004483 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004484 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004485 case ICmpInst::ICMP_ULE:
4486 // (float)int <= 4.4 --> int <= 4
4487 // (float)int <= -4.4 --> false
4488 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004489 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004490 break;
4491 case ICmpInst::ICMP_SLE:
4492 // (float)int <= 4.4 --> int <= 4
4493 // (float)int <= -4.4 --> int < -4
4494 if (RHS.isNegative())
4495 Pred = ICmpInst::ICMP_SLT;
4496 break;
4497 case ICmpInst::ICMP_ULT:
4498 // (float)int < -4.4 --> false
4499 // (float)int < 4.4 --> int <= 4
4500 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004501 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004502 Pred = ICmpInst::ICMP_ULE;
4503 break;
4504 case ICmpInst::ICMP_SLT:
4505 // (float)int < -4.4 --> int < -4
4506 // (float)int < 4.4 --> int <= 4
4507 if (!RHS.isNegative())
4508 Pred = ICmpInst::ICMP_SLE;
4509 break;
4510 case ICmpInst::ICMP_UGT:
4511 // (float)int > 4.4 --> int > 4
4512 // (float)int > -4.4 --> true
4513 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004514 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004515 break;
4516 case ICmpInst::ICMP_SGT:
4517 // (float)int > 4.4 --> int > 4
4518 // (float)int > -4.4 --> int >= -4
4519 if (RHS.isNegative())
4520 Pred = ICmpInst::ICMP_SGE;
4521 break;
4522 case ICmpInst::ICMP_UGE:
4523 // (float)int >= -4.4 --> true
4524 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004525 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004526 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004527 Pred = ICmpInst::ICMP_UGT;
4528 break;
4529 case ICmpInst::ICMP_SGE:
4530 // (float)int >= -4.4 --> int >= -4
4531 // (float)int >= 4.4 --> int > 4
4532 if (!RHS.isNegative())
4533 Pred = ICmpInst::ICMP_SGT;
4534 break;
4535 }
4536 }
4537 }
4538
4539 // Lower this FP comparison into an appropriate integer version of the
4540 // comparison.
4541 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4542}
4543
4544Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4545 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004546
Chris Lattner2188e402010-01-04 07:37:31 +00004547 /// Orders the operands of the compare so that they are listed from most
4548 /// complex to least complex. This puts constants before unary operators,
4549 /// before binary operators.
4550 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4551 I.swapOperands();
4552 Changed = true;
4553 }
4554
4555 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004556
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004557 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
Justin Bogner99798402016-08-05 01:06:44 +00004558 I.getFastMathFlags(), DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004559 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004560
4561 // Simplify 'fcmp pred X, X'
4562 if (Op0 == Op1) {
4563 switch (I.getPredicate()) {
4564 default: llvm_unreachable("Unknown predicate!");
4565 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4566 case FCmpInst::FCMP_ULT: // True if unordered or less than
4567 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4568 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4569 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4570 I.setPredicate(FCmpInst::FCMP_UNO);
4571 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4572 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004573
Chris Lattner2188e402010-01-04 07:37:31 +00004574 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4575 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4576 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4577 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4578 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4579 I.setPredicate(FCmpInst::FCMP_ORD);
4580 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4581 return &I;
4582 }
4583 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004584
James Molloy2b21a7c2015-05-20 18:41:25 +00004585 // Test if the FCmpInst instruction is used exclusively by a select as
4586 // part of a minimum or maximum operation. If so, refrain from doing
4587 // any other folding. This helps out other analyses which understand
4588 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4589 // and CodeGen. And in this case, at least one of the comparison
4590 // operands has at least one user besides the compare (the select),
4591 // which would often largely negate the benefit of folding anyway.
4592 if (I.hasOneUse())
4593 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4594 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4595 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4596 return nullptr;
4597
Chris Lattner2188e402010-01-04 07:37:31 +00004598 // Handle fcmp with constant RHS
4599 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4600 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4601 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004602 case Instruction::FPExt: {
4603 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4604 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4605 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4606 if (!RHSF)
4607 break;
4608
4609 const fltSemantics *Sem;
4610 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004611 if (LHSExt->getSrcTy()->isHalfTy())
4612 Sem = &APFloat::IEEEhalf;
4613 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004614 Sem = &APFloat::IEEEsingle;
4615 else if (LHSExt->getSrcTy()->isDoubleTy())
4616 Sem = &APFloat::IEEEdouble;
4617 else if (LHSExt->getSrcTy()->isFP128Ty())
4618 Sem = &APFloat::IEEEquad;
4619 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4620 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004621 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4622 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004623 else
4624 break;
4625
4626 bool Lossy;
4627 APFloat F = RHSF->getValueAPF();
4628 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4629
Jim Grosbach24ff8342011-09-30 18:45:50 +00004630 // Avoid lossy conversions and denormals. Zero is a special case
4631 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004632 APFloat Fabs = F;
4633 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004634 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004635 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4636 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004637
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004638 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4639 ConstantFP::get(RHSC->getContext(), F));
4640 break;
4641 }
Chris Lattner2188e402010-01-04 07:37:31 +00004642 case Instruction::PHI:
4643 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4644 // block. If in the same block, we're encouraging jump threading. If
4645 // not, we are just pessimizing the code by making an i1 phi.
4646 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004647 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004648 return NV;
4649 break;
4650 case Instruction::SIToFP:
4651 case Instruction::UIToFP:
Sanjay Patel43395062016-07-21 18:07:40 +00004652 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
Chris Lattner2188e402010-01-04 07:37:31 +00004653 return NV;
4654 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004655 case Instruction::FSub: {
4656 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4657 Value *Op;
4658 if (match(LHSI, m_FNeg(m_Value(Op))))
4659 return new FCmpInst(I.getSwappedPredicate(), Op,
4660 ConstantExpr::getFNeg(RHSC));
4661 break;
4662 }
Dan Gohman94732022010-02-24 06:46:09 +00004663 case Instruction::Load:
4664 if (GetElementPtrInst *GEP =
4665 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4666 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4667 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4668 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00004669 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Dan Gohman94732022010-02-24 06:46:09 +00004670 return Res;
4671 }
4672 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004673 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004674 if (!RHSC->isNullValue())
4675 break;
4676
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004677 CallInst *CI = cast<CallInst>(LHSI);
Justin Bogner99798402016-08-05 01:06:44 +00004678 Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004679 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004680 break;
4681
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004682 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004683 switch (I.getPredicate()) {
4684 default:
4685 break;
4686 // fabs(x) < 0 --> false
4687 case FCmpInst::FCMP_OLT:
4688 llvm_unreachable("handled by SimplifyFCmpInst");
4689 // fabs(x) > 0 --> x != 0
4690 case FCmpInst::FCMP_OGT:
4691 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4692 // fabs(x) <= 0 --> x == 0
4693 case FCmpInst::FCMP_OLE:
4694 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4695 // fabs(x) >= 0 --> !isnan(x)
4696 case FCmpInst::FCMP_OGE:
4697 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4698 // fabs(x) == 0 --> x == 0
4699 // fabs(x) != 0 --> x != 0
4700 case FCmpInst::FCMP_OEQ:
4701 case FCmpInst::FCMP_UEQ:
4702 case FCmpInst::FCMP_ONE:
4703 case FCmpInst::FCMP_UNE:
4704 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004705 }
4706 }
Chris Lattner2188e402010-01-04 07:37:31 +00004707 }
Chris Lattner2188e402010-01-04 07:37:31 +00004708 }
4709
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004710 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004711 Value *X, *Y;
4712 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004713 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004714
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004715 // fcmp (fpext x), (fpext y) -> fcmp x, y
4716 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4717 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4718 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4719 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4720 RHSExt->getOperand(0));
4721
Craig Topperf40110f2014-04-25 05:29:35 +00004722 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004723}