blob: 977d3cbad5c0f61da6a649f2d3dd0f0e4038ca75 [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
Chris Lattner98457102011-02-10 05:23:05 +000038
Chris Lattner2188e402010-01-04 07:37:31 +000039static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
40 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
41}
42
43static bool HasAddOverflow(ConstantInt *Result,
44 ConstantInt *In1, ConstantInt *In2,
45 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000046 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000047 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000048
49 if (In2->isNegative())
50 return Result->getValue().sgt(In1->getValue());
51 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000052}
53
Sanjay Patel5f0217f2016-06-05 16:46:18 +000054/// Compute Result = In1+In2, returning true if the result overflowed for this
55/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000056static bool AddWithOverflow(Constant *&Result, Constant *In1,
57 Constant *In2, bool IsSigned = false) {
58 Result = ConstantExpr::getAdd(In1, In2);
59
Chris Lattner229907c2011-07-18 04:54:35 +000060 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000061 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
62 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
63 if (HasAddOverflow(ExtractElement(Result, Idx),
64 ExtractElement(In1, Idx),
65 ExtractElement(In2, Idx),
66 IsSigned))
67 return true;
68 }
69 return false;
70 }
71
72 return HasAddOverflow(cast<ConstantInt>(Result),
73 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
74 IsSigned);
75}
76
77static bool HasSubOverflow(ConstantInt *Result,
78 ConstantInt *In1, ConstantInt *In2,
79 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000080 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000081 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000082
Chris Lattnerb1a15122011-07-15 06:08:15 +000083 if (In2->isNegative())
84 return Result->getValue().slt(In1->getValue());
85
86 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000087}
88
Sanjay Patel5f0217f2016-06-05 16:46:18 +000089/// Compute Result = In1-In2, returning true if the result overflowed for this
90/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000091static bool SubWithOverflow(Constant *&Result, Constant *In1,
92 Constant *In2, bool IsSigned = false) {
93 Result = ConstantExpr::getSub(In1, In2);
94
Chris Lattner229907c2011-07-18 04:54:35 +000095 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000096 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
97 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
98 if (HasSubOverflow(ExtractElement(Result, Idx),
99 ExtractElement(In1, Idx),
100 ExtractElement(In2, Idx),
101 IsSigned))
102 return true;
103 }
104 return false;
105 }
106
107 return HasSubOverflow(cast<ConstantInt>(Result),
108 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
109 IsSigned);
110}
111
Balaram Makam569eaec2016-05-04 21:32:14 +0000112/// Given an icmp instruction, return true if any use of this comparison is a
113/// branch on sign bit comparison.
114static bool isBranchOnSignBitCheck(ICmpInst &I, bool isSignBit) {
115 for (auto *U : I.users())
116 if (isa<BranchInst>(U))
117 return isSignBit;
118 return false;
119}
120
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000121/// Given an exploded icmp instruction, return true if the comparison only
122/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the
123/// result of the comparison is true when the input value is signed.
Sanjay Patel79263662016-08-21 15:07:45 +0000124static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000125 bool &TrueIfSigned) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000126 switch (Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000127 case ICmpInst::ICMP_SLT: // True if LHS s< 0
128 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000129 return RHS == 0;
Chris Lattner2188e402010-01-04 07:37:31 +0000130 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
131 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000132 return RHS.isAllOnesValue();
Chris Lattner2188e402010-01-04 07:37:31 +0000133 case ICmpInst::ICMP_SGT: // True if LHS s> -1
134 TrueIfSigned = false;
Sanjay Patel79263662016-08-21 15:07:45 +0000135 return RHS.isAllOnesValue();
Chris Lattner2188e402010-01-04 07:37:31 +0000136 case ICmpInst::ICMP_UGT:
137 // True if LHS u> RHS and RHS == high-bit-mask - 1
138 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000139 return RHS.isMaxSignedValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000140 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000141 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
142 TrueIfSigned = true;
Sanjay Patel79263662016-08-21 15:07:45 +0000143 return RHS.isSignBit();
Chris Lattner2188e402010-01-04 07:37:31 +0000144 default:
145 return false;
146 }
147}
148
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000149/// Returns true if the exploded icmp can be expressed as a signed comparison
150/// to zero and updates the predicate accordingly.
151/// The signedness of the comparison is preserved.
Sanjay Patel5b112842016-08-18 14:59:14 +0000152/// TODO: Refactor with decomposeBitTestICmp()?
153static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000154 if (!ICmpInst::isSigned(Pred))
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000155 return false;
156
Sanjay Patel5b112842016-08-18 14:59:14 +0000157 if (C == 0)
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000158 return ICmpInst::isRelational(Pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000159
Sanjay Patel5b112842016-08-18 14:59:14 +0000160 if (C == 1) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000161 if (Pred == ICmpInst::ICMP_SLT) {
162 Pred = ICmpInst::ICMP_SLE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000163 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000164 }
Sanjay Patel5b112842016-08-18 14:59:14 +0000165 } else if (C.isAllOnesValue()) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000166 if (Pred == ICmpInst::ICMP_SGT) {
167 Pred = ICmpInst::ICMP_SGE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000168 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000169 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000170 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000171
172 return false;
173}
174
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000175/// Given a signed integer type and a set of known zero and one bits, compute
176/// the maximum and minimum values that could have the specified known zero and
177/// known one bits, returning them in Min/Max.
178static void ComputeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
179 const APInt &KnownOne,
180 APInt &Min, APInt &Max) {
Chris Lattner2188e402010-01-04 07:37:31 +0000181 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
182 KnownZero.getBitWidth() == Min.getBitWidth() &&
183 KnownZero.getBitWidth() == Max.getBitWidth() &&
184 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
185 APInt UnknownBits = ~(KnownZero|KnownOne);
186
187 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
188 // bit if it is unknown.
189 Min = KnownOne;
190 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000191
Chris Lattner2188e402010-01-04 07:37:31 +0000192 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000193 Min.setBit(Min.getBitWidth()-1);
194 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000195 }
196}
197
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000198/// Given an unsigned integer type and a set of known zero and one bits, compute
199/// the maximum and minimum values that could have the specified known zero and
200/// known one bits, returning them in Min/Max.
Chris Lattner2188e402010-01-04 07:37:31 +0000201static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
202 const APInt &KnownOne,
203 APInt &Min, APInt &Max) {
204 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
205 KnownZero.getBitWidth() == Min.getBitWidth() &&
206 KnownZero.getBitWidth() == Max.getBitWidth() &&
207 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
208 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000209
Chris Lattner2188e402010-01-04 07:37:31 +0000210 // The minimum value is when the unknown bits are all zeros.
211 Min = KnownOne;
212 // The maximum value is when the unknown bits are all ones.
213 Max = KnownOne|UnknownBits;
214}
215
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000216/// This is called when we see this pattern:
Chris Lattner2188e402010-01-04 07:37:31 +0000217/// cmp pred (load (gep GV, ...)), cmpcst
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000218/// where GV is a global variable with a constant initializer. Try to simplify
219/// this into some simple computation that does not need the load. For example
Chris Lattner2188e402010-01-04 07:37:31 +0000220/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
221///
222/// If AndCst is non-null, then the loaded value is masked with that constant
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000223/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Sanjay Patel43395062016-07-21 18:07:40 +0000224Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
225 GlobalVariable *GV,
226 CmpInst &ICI,
227 ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000228 Constant *Init = GV->getInitializer();
229 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000230 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000231
Chris Lattnerfe741762012-01-31 02:55:06 +0000232 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000233 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000234
Chris Lattner2188e402010-01-04 07:37:31 +0000235 // There are many forms of this optimization we can handle, for now, just do
236 // the simple index into a single-dimensional array.
237 //
238 // Require: GEP GV, 0, i {{, constant indices}}
239 if (GEP->getNumOperands() < 3 ||
240 !isa<ConstantInt>(GEP->getOperand(1)) ||
241 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
242 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000243 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000244
245 // Check that indices after the variable are constants and in-range for the
246 // type they index. Collect the indices. This is typically for arrays of
247 // structs.
248 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000249
Chris Lattnerfe741762012-01-31 02:55:06 +0000250 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000251 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
252 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000253 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000254
Chris Lattner2188e402010-01-04 07:37:31 +0000255 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000256 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000257
Chris Lattner229907c2011-07-18 04:54:35 +0000258 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000259 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000260 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000261 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000262 EltTy = ATy->getElementType();
263 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000264 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000265 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000266
Chris Lattner2188e402010-01-04 07:37:31 +0000267 LaterIndices.push_back(IdxVal);
268 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000269
Chris Lattner2188e402010-01-04 07:37:31 +0000270 enum { Overdefined = -3, Undefined = -2 };
271
272 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000273
Chris Lattner2188e402010-01-04 07:37:31 +0000274 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
275 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
276 // and 87 is the second (and last) index. FirstTrueElement is -2 when
277 // undefined, otherwise set to the first true element. SecondTrueElement is
278 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
279 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
280
281 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
282 // form "i != 47 & i != 87". Same state transitions as for true elements.
283 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000284
Chris Lattner2188e402010-01-04 07:37:31 +0000285 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
286 /// define a state machine that triggers for ranges of values that the index
287 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
288 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
289 /// index in the range (inclusive). We use -2 for undefined here because we
290 /// use relative comparisons and don't want 0-1 to match -1.
291 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000292
Chris Lattner2188e402010-01-04 07:37:31 +0000293 // MagicBitvector - This is a magic bitvector where we set a bit if the
294 // comparison is true for element 'i'. If there are 64 elements or less in
295 // the array, this will fully represent all the comparison results.
296 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000297
Chris Lattner2188e402010-01-04 07:37:31 +0000298 // Scan the array and see if one of our patterns matches.
299 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000300 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
301 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000302 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000303
Chris Lattner2188e402010-01-04 07:37:31 +0000304 // If this is indexing an array of structures, get the structure element.
305 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000306 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000307
Chris Lattner2188e402010-01-04 07:37:31 +0000308 // If the element is masked, handle it.
309 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000310
Chris Lattner2188e402010-01-04 07:37:31 +0000311 // Find out if the comparison would be true or false for the i'th element.
312 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Justin Bogner99798402016-08-05 01:06:44 +0000313 CompareRHS, DL, &TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000314 // If the result is undef for this element, ignore it.
315 if (isa<UndefValue>(C)) {
316 // Extend range state machines to cover this element in case there is an
317 // undef in the middle of the range.
318 if (TrueRangeEnd == (int)i-1)
319 TrueRangeEnd = i;
320 if (FalseRangeEnd == (int)i-1)
321 FalseRangeEnd = i;
322 continue;
323 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000324
Chris Lattner2188e402010-01-04 07:37:31 +0000325 // If we can't compute the result for any of the elements, we have to give
326 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000327 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000328
Chris Lattner2188e402010-01-04 07:37:31 +0000329 // Otherwise, we know if the comparison is true or false for this element,
330 // update our state machines.
331 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000332
Chris Lattner2188e402010-01-04 07:37:31 +0000333 // State machine for single/double/range index comparison.
334 if (IsTrueForElt) {
335 // Update the TrueElement state machine.
336 if (FirstTrueElement == Undefined)
337 FirstTrueElement = TrueRangeEnd = i; // First true element.
338 else {
339 // Update double-compare state machine.
340 if (SecondTrueElement == Undefined)
341 SecondTrueElement = i;
342 else
343 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000344
Chris Lattner2188e402010-01-04 07:37:31 +0000345 // Update range state machine.
346 if (TrueRangeEnd == (int)i-1)
347 TrueRangeEnd = i;
348 else
349 TrueRangeEnd = Overdefined;
350 }
351 } else {
352 // Update the FalseElement state machine.
353 if (FirstFalseElement == Undefined)
354 FirstFalseElement = FalseRangeEnd = i; // First false element.
355 else {
356 // Update double-compare state machine.
357 if (SecondFalseElement == Undefined)
358 SecondFalseElement = i;
359 else
360 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000361
Chris Lattner2188e402010-01-04 07:37:31 +0000362 // Update range state machine.
363 if (FalseRangeEnd == (int)i-1)
364 FalseRangeEnd = i;
365 else
366 FalseRangeEnd = Overdefined;
367 }
368 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000369
Chris Lattner2188e402010-01-04 07:37:31 +0000370 // If this element is in range, update our magic bitvector.
371 if (i < 64 && IsTrueForElt)
372 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000373
Chris Lattner2188e402010-01-04 07:37:31 +0000374 // If all of our states become overdefined, bail out early. Since the
375 // predicate is expensive, only check it every 8 elements. This is only
376 // really useful for really huge arrays.
377 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
378 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
379 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000380 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000381 }
382
383 // Now that we've scanned the entire array, emit our new comparison(s). We
384 // order the state machines in complexity of the generated code.
385 Value *Idx = GEP->getOperand(2);
386
Matt Arsenault5aeae182013-08-19 21:40:31 +0000387 // If the index is larger than the pointer size of the target, truncate the
388 // index down like the GEP would do implicitly. We don't have to do this for
389 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000390 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000391 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000392 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
393 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
394 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
395 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000396
Chris Lattner2188e402010-01-04 07:37:31 +0000397 // If the comparison is only true for one or two elements, emit direct
398 // comparisons.
399 if (SecondTrueElement != Overdefined) {
400 // None true -> false.
401 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000402 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000403
Chris Lattner2188e402010-01-04 07:37:31 +0000404 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000405
Chris Lattner2188e402010-01-04 07:37:31 +0000406 // True for one element -> 'i == 47'.
407 if (SecondTrueElement == Undefined)
408 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000409
Chris Lattner2188e402010-01-04 07:37:31 +0000410 // True for two elements -> 'i == 47 | i == 72'.
411 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
412 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
413 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
414 return BinaryOperator::CreateOr(C1, C2);
415 }
416
417 // If the comparison is only false for one or two elements, emit direct
418 // comparisons.
419 if (SecondFalseElement != Overdefined) {
420 // None false -> true.
421 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000422 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000423
Chris Lattner2188e402010-01-04 07:37:31 +0000424 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
425
426 // False for one element -> 'i != 47'.
427 if (SecondFalseElement == Undefined)
428 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000429
Chris Lattner2188e402010-01-04 07:37:31 +0000430 // False for two elements -> 'i != 47 & i != 72'.
431 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
432 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
433 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
434 return BinaryOperator::CreateAnd(C1, C2);
435 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000436
Chris Lattner2188e402010-01-04 07:37:31 +0000437 // If the comparison can be replaced with a range comparison for the elements
438 // where it is true, emit the range check.
439 if (TrueRangeEnd != Overdefined) {
440 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000441
Chris Lattner2188e402010-01-04 07:37:31 +0000442 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
443 if (FirstTrueElement) {
444 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
445 Idx = Builder->CreateAdd(Idx, Offs);
446 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000447
Chris Lattner2188e402010-01-04 07:37:31 +0000448 Value *End = ConstantInt::get(Idx->getType(),
449 TrueRangeEnd-FirstTrueElement+1);
450 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
451 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000452
Chris Lattner2188e402010-01-04 07:37:31 +0000453 // False range check.
454 if (FalseRangeEnd != Overdefined) {
455 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
456 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
457 if (FirstFalseElement) {
458 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
459 Idx = Builder->CreateAdd(Idx, Offs);
460 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000461
Chris Lattner2188e402010-01-04 07:37:31 +0000462 Value *End = ConstantInt::get(Idx->getType(),
463 FalseRangeEnd-FirstFalseElement);
464 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
465 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000466
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000467 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000468 // of this load, replace it with computation that does:
469 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000470 {
Craig Topperf40110f2014-04-25 05:29:35 +0000471 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000472
473 // Look for an appropriate type:
474 // - The type of Idx if the magic fits
475 // - The smallest fitting legal type if we have a DataLayout
476 // - Default to i32
477 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
478 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000479 else
480 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000481
Craig Topperf40110f2014-04-25 05:29:35 +0000482 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000483 Value *V = Builder->CreateIntCast(Idx, Ty, false);
484 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
485 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
486 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
487 }
Chris Lattner2188e402010-01-04 07:37:31 +0000488 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000489
Craig Topperf40110f2014-04-25 05:29:35 +0000490 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000491}
492
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000493/// Return a value that can be used to compare the *offset* implied by a GEP to
494/// zero. For example, if we have &A[i], we want to return 'i' for
495/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
496/// are involved. The above expression would also be legal to codegen as
497/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
498/// This latter form is less amenable to optimization though, and we are allowed
Chris Lattner2188e402010-01-04 07:37:31 +0000499/// to generate the first by knowing that pointer arithmetic doesn't overflow.
500///
501/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000502///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000503static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
504 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000505 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000506
Chris Lattner2188e402010-01-04 07:37:31 +0000507 // Check to see if this gep only has a single variable index. If so, and if
508 // any constant indices are a multiple of its scale, then we can compute this
509 // in terms of the scale of the variable index. For example, if the GEP
510 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
511 // because the expression will cross zero at the same point.
512 unsigned i, e = GEP->getNumOperands();
513 int64_t Offset = 0;
514 for (i = 1; i != e; ++i, ++GTI) {
515 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
516 // Compute the aggregate offset of constant indices.
517 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000518
Chris Lattner2188e402010-01-04 07:37:31 +0000519 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000520 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000521 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000522 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000523 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000524 Offset += Size*CI->getSExtValue();
525 }
526 } else {
527 // Found our variable index.
528 break;
529 }
530 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000531
Chris Lattner2188e402010-01-04 07:37:31 +0000532 // If there are no variable indices, we must have a constant offset, just
533 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000534 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000535
Chris Lattner2188e402010-01-04 07:37:31 +0000536 Value *VariableIdx = GEP->getOperand(i);
537 // Determine the scale factor of the variable element. For example, this is
538 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000539 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000540
Chris Lattner2188e402010-01-04 07:37:31 +0000541 // Verify that there are no other variable indices. If so, emit the hard way.
542 for (++i, ++GTI; i != e; ++i, ++GTI) {
543 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000544 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000545
Chris Lattner2188e402010-01-04 07:37:31 +0000546 // Compute the aggregate offset of constant indices.
547 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000548
Chris Lattner2188e402010-01-04 07:37:31 +0000549 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000550 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000551 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000552 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000553 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000554 Offset += Size*CI->getSExtValue();
555 }
556 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000557
Chris Lattner2188e402010-01-04 07:37:31 +0000558 // Okay, we know we have a single variable index, which must be a
559 // pointer/array/vector index. If there is no offset, life is simple, return
560 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000561 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000562 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000563 if (Offset == 0) {
564 // Cast to intptrty in case a truncation occurs. If an extension is needed,
565 // we don't need to bother extending: the extension won't affect where the
566 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000567 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000568 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
569 }
Chris Lattner2188e402010-01-04 07:37:31 +0000570 return VariableIdx;
571 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000572
Chris Lattner2188e402010-01-04 07:37:31 +0000573 // Otherwise, there is an index. The computation we will do will be modulo
574 // the pointer size, so get it.
575 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000576
Chris Lattner2188e402010-01-04 07:37:31 +0000577 Offset &= PtrSizeMask;
578 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000579
Chris Lattner2188e402010-01-04 07:37:31 +0000580 // To do this transformation, any constant index must be a multiple of the
581 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
582 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
583 // multiple of the variable scale.
584 int64_t NewOffs = Offset / (int64_t)VariableScale;
585 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000586 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000587
Chris Lattner2188e402010-01-04 07:37:31 +0000588 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000589 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000590 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
591 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000592 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000593 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000594}
595
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000596/// Returns true if we can rewrite Start as a GEP with pointer Base
597/// and some integer offset. The nodes that need to be re-written
598/// for this transformation will be added to Explored.
599static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
600 const DataLayout &DL,
601 SetVector<Value *> &Explored) {
602 SmallVector<Value *, 16> WorkList(1, Start);
603 Explored.insert(Base);
604
605 // The following traversal gives us an order which can be used
606 // when doing the final transformation. Since in the final
607 // transformation we create the PHI replacement instructions first,
608 // we don't have to get them in any particular order.
609 //
610 // However, for other instructions we will have to traverse the
611 // operands of an instruction first, which means that we have to
612 // do a post-order traversal.
613 while (!WorkList.empty()) {
614 SetVector<PHINode *> PHIs;
615
616 while (!WorkList.empty()) {
617 if (Explored.size() >= 100)
618 return false;
619
620 Value *V = WorkList.back();
621
622 if (Explored.count(V) != 0) {
623 WorkList.pop_back();
624 continue;
625 }
626
627 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
628 !isa<GEPOperator>(V) && !isa<PHINode>(V))
629 // We've found some value that we can't explore which is different from
630 // the base. Therefore we can't do this transformation.
631 return false;
632
633 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
634 auto *CI = dyn_cast<CastInst>(V);
635 if (!CI->isNoopCast(DL))
636 return false;
637
638 if (Explored.count(CI->getOperand(0)) == 0)
639 WorkList.push_back(CI->getOperand(0));
640 }
641
642 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
643 // We're limiting the GEP to having one index. This will preserve
644 // the original pointer type. We could handle more cases in the
645 // future.
646 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
647 GEP->getType() != Start->getType())
648 return false;
649
650 if (Explored.count(GEP->getOperand(0)) == 0)
651 WorkList.push_back(GEP->getOperand(0));
652 }
653
654 if (WorkList.back() == V) {
655 WorkList.pop_back();
656 // We've finished visiting this node, mark it as such.
657 Explored.insert(V);
658 }
659
660 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000661 // We cannot transform PHIs on unsplittable basic blocks.
662 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
663 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000664 Explored.insert(PN);
665 PHIs.insert(PN);
666 }
667 }
668
669 // Explore the PHI nodes further.
670 for (auto *PN : PHIs)
671 for (Value *Op : PN->incoming_values())
672 if (Explored.count(Op) == 0)
673 WorkList.push_back(Op);
674 }
675
676 // Make sure that we can do this. Since we can't insert GEPs in a basic
677 // block before a PHI node, we can't easily do this transformation if
678 // we have PHI node users of transformed instructions.
679 for (Value *Val : Explored) {
680 for (Value *Use : Val->uses()) {
681
682 auto *PHI = dyn_cast<PHINode>(Use);
683 auto *Inst = dyn_cast<Instruction>(Val);
684
685 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
686 Explored.count(PHI) == 0)
687 continue;
688
689 if (PHI->getParent() == Inst->getParent())
690 return false;
691 }
692 }
693 return true;
694}
695
696// Sets the appropriate insert point on Builder where we can add
697// a replacement Instruction for V (if that is possible).
698static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
699 bool Before = true) {
700 if (auto *PHI = dyn_cast<PHINode>(V)) {
701 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
702 return;
703 }
704 if (auto *I = dyn_cast<Instruction>(V)) {
705 if (!Before)
706 I = &*std::next(I->getIterator());
707 Builder.SetInsertPoint(I);
708 return;
709 }
710 if (auto *A = dyn_cast<Argument>(V)) {
711 // Set the insertion point in the entry block.
712 BasicBlock &Entry = A->getParent()->getEntryBlock();
713 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
714 return;
715 }
716 // Otherwise, this is a constant and we don't need to set a new
717 // insertion point.
718 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
719}
720
721/// Returns a re-written value of Start as an indexed GEP using Base as a
722/// pointer.
723static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
724 const DataLayout &DL,
725 SetVector<Value *> &Explored) {
726 // Perform all the substitutions. This is a bit tricky because we can
727 // have cycles in our use-def chains.
728 // 1. Create the PHI nodes without any incoming values.
729 // 2. Create all the other values.
730 // 3. Add the edges for the PHI nodes.
731 // 4. Emit GEPs to get the original pointers.
732 // 5. Remove the original instructions.
733 Type *IndexType = IntegerType::get(
734 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
735
736 DenseMap<Value *, Value *> NewInsts;
737 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
738
739 // Create the new PHI nodes, without adding any incoming values.
740 for (Value *Val : Explored) {
741 if (Val == Base)
742 continue;
743 // Create empty phi nodes. This avoids cyclic dependencies when creating
744 // the remaining instructions.
745 if (auto *PHI = dyn_cast<PHINode>(Val))
746 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
747 PHI->getName() + ".idx", PHI);
748 }
749 IRBuilder<> Builder(Base->getContext());
750
751 // Create all the other instructions.
752 for (Value *Val : Explored) {
753
754 if (NewInsts.find(Val) != NewInsts.end())
755 continue;
756
757 if (auto *CI = dyn_cast<CastInst>(Val)) {
758 NewInsts[CI] = NewInsts[CI->getOperand(0)];
759 continue;
760 }
761 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
762 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
763 : GEP->getOperand(1);
764 setInsertionPoint(Builder, GEP);
765 // Indices might need to be sign extended. GEPs will magically do
766 // this, but we need to do it ourselves here.
767 if (Index->getType()->getScalarSizeInBits() !=
768 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
769 Index = Builder.CreateSExtOrTrunc(
770 Index, NewInsts[GEP->getOperand(0)]->getType(),
771 GEP->getOperand(0)->getName() + ".sext");
772 }
773
774 auto *Op = NewInsts[GEP->getOperand(0)];
775 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
776 NewInsts[GEP] = Index;
777 else
778 NewInsts[GEP] = Builder.CreateNSWAdd(
779 Op, Index, GEP->getOperand(0)->getName() + ".add");
780 continue;
781 }
782 if (isa<PHINode>(Val))
783 continue;
784
785 llvm_unreachable("Unexpected instruction type");
786 }
787
788 // Add the incoming values to the PHI nodes.
789 for (Value *Val : Explored) {
790 if (Val == Base)
791 continue;
792 // All the instructions have been created, we can now add edges to the
793 // phi nodes.
794 if (auto *PHI = dyn_cast<PHINode>(Val)) {
795 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
796 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
797 Value *NewIncoming = PHI->getIncomingValue(I);
798
799 if (NewInsts.find(NewIncoming) != NewInsts.end())
800 NewIncoming = NewInsts[NewIncoming];
801
802 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
803 }
804 }
805 }
806
807 for (Value *Val : Explored) {
808 if (Val == Base)
809 continue;
810
811 // Depending on the type, for external users we have to emit
812 // a GEP or a GEP + ptrtoint.
813 setInsertionPoint(Builder, Val, false);
814
815 // If required, create an inttoptr instruction for Base.
816 Value *NewBase = Base;
817 if (!Base->getType()->isPointerTy())
818 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
819 Start->getName() + "to.ptr");
820
821 Value *GEP = Builder.CreateInBoundsGEP(
822 Start->getType()->getPointerElementType(), NewBase,
823 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
824
825 if (!Val->getType()->isPointerTy()) {
826 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
827 Val->getName() + ".conv");
828 GEP = Cast;
829 }
830 Val->replaceAllUsesWith(GEP);
831 }
832
833 return NewInsts[Start];
834}
835
836/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
837/// the input Value as a constant indexed GEP. Returns a pair containing
838/// the GEPs Pointer and Index.
839static std::pair<Value *, Value *>
840getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
841 Type *IndexType = IntegerType::get(V->getContext(),
842 DL.getPointerTypeSizeInBits(V->getType()));
843
844 Constant *Index = ConstantInt::getNullValue(IndexType);
845 while (true) {
846 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
847 // We accept only inbouds GEPs here to exclude the possibility of
848 // overflow.
849 if (!GEP->isInBounds())
850 break;
851 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
852 GEP->getType() == V->getType()) {
853 V = GEP->getOperand(0);
854 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
855 Index = ConstantExpr::getAdd(
856 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
857 continue;
858 }
859 break;
860 }
861 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
862 if (!CI->isNoopCast(DL))
863 break;
864 V = CI->getOperand(0);
865 continue;
866 }
867 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
868 if (!CI->isNoopCast(DL))
869 break;
870 V = CI->getOperand(0);
871 continue;
872 }
873 break;
874 }
875 return {V, Index};
876}
877
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000878/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
879/// We can look through PHIs, GEPs and casts in order to determine a common base
880/// between GEPLHS and RHS.
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000881static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
882 ICmpInst::Predicate Cond,
883 const DataLayout &DL) {
884 if (!GEPLHS->hasAllConstantIndices())
885 return nullptr;
886
887 Value *PtrBase, *Index;
888 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
889
890 // The set of nodes that will take part in this transformation.
891 SetVector<Value *> Nodes;
892
893 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
894 return nullptr;
895
896 // We know we can re-write this as
897 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
898 // Since we've only looked through inbouds GEPs we know that we
899 // can't have overflow on either side. We can therefore re-write
900 // this as:
901 // OFFSET1 cmp OFFSET2
902 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
903
904 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
905 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
906 // offset. Since Index is the offset of LHS to the base pointer, we will now
907 // compare the offsets instead of comparing the pointers.
908 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
909}
910
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000911/// Fold comparisons between a GEP instruction and something else. At this point
912/// we know that the GEP is on the LHS of the comparison.
Sanjay Patel43395062016-07-21 18:07:40 +0000913Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000914 ICmpInst::Predicate Cond,
915 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000916 // Don't transform signed compares of GEPs into index compares. Even if the
917 // GEP is inbounds, the final add of the base pointer can have signed overflow
918 // and would change the result of the icmp.
919 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000920 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000921 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000922 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000923
Matt Arsenault44f60d02014-06-09 19:20:29 +0000924 // Look through bitcasts and addrspacecasts. We do not however want to remove
925 // 0 GEPs.
926 if (!isa<GetElementPtrInst>(RHS))
927 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000928
929 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000930 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000931 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
932 // This transformation (ignoring the base and scales) is valid because we
933 // know pointers can't overflow since the gep is inbounds. See if we can
934 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000935 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000936
Chris Lattner2188e402010-01-04 07:37:31 +0000937 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000938 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000939 Offset = EmitGEPOffset(GEPLHS);
940 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
941 Constant::getNullValue(Offset->getType()));
942 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
943 // If the base pointers are different, but the indices are the same, just
944 // compare the base pointer.
945 if (PtrBase != GEPRHS->getOperand(0)) {
946 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
947 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
948 GEPRHS->getOperand(0)->getType();
949 if (IndicesTheSame)
950 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
951 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
952 IndicesTheSame = false;
953 break;
954 }
955
956 // If all indices are the same, just compare the base pointers.
957 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000958 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000959
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000960 // If we're comparing GEPs with two base pointers that only differ in type
961 // and both GEPs have only constant indices or just one use, then fold
962 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000963 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000964 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
965 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
966 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000968 Value *LOffset = EmitGEPOffset(GEPLHS);
969 Value *ROffset = EmitGEPOffset(GEPRHS);
970
971 // If we looked through an addrspacecast between different sized address
972 // spaces, the LHS and RHS pointers are different sized
973 // integers. Truncate to the smaller one.
974 Type *LHSIndexTy = LOffset->getType();
975 Type *RHSIndexTy = ROffset->getType();
976 if (LHSIndexTy != RHSIndexTy) {
977 if (LHSIndexTy->getPrimitiveSizeInBits() <
978 RHSIndexTy->getPrimitiveSizeInBits()) {
979 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
980 } else
981 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
982 }
983
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000984 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000985 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000986 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000987 }
988
Chris Lattner2188e402010-01-04 07:37:31 +0000989 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000990 // different. Try convert this to an indexed compare by looking through
991 // PHIs/casts.
992 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +0000993 }
994
995 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +0000996 if (GEPLHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +0000997 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +0000998 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +0000999
1000 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001001 if (GEPRHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001002 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner2188e402010-01-04 07:37:31 +00001003
Stuart Hastings66a82b92011-05-14 05:55:10 +00001004 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001005 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1006 // If the GEPs only differ by one index, compare it.
1007 unsigned NumDifferences = 0; // Keep track of # differences.
1008 unsigned DiffOperand = 0; // The operand that differs.
1009 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1010 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1011 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1012 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1013 // Irreconcilable differences.
1014 NumDifferences = 2;
1015 break;
1016 } else {
1017 if (NumDifferences++) break;
1018 DiffOperand = i;
1019 }
1020 }
1021
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001022 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001023 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001024 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001025
Stuart Hastings66a82b92011-05-14 05:55:10 +00001026 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001027 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1028 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1029 // Make sure we do a signed comparison here.
1030 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1031 }
1032 }
1033
1034 // Only lower this if the icmp is the only user of the GEP or if we expect
1035 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001036 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001037 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1038 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1039 Value *L = EmitGEPOffset(GEPLHS);
1040 Value *R = EmitGEPOffset(GEPRHS);
1041 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1042 }
1043 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001044
1045 // Try convert this to an indexed compare by looking through PHIs/casts as a
1046 // last resort.
1047 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001048}
1049
Pete Cooper980a9352016-08-12 17:13:28 +00001050Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI,
1051 const AllocaInst *Alloca,
1052 const Value *Other) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001053 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1054
1055 // It would be tempting to fold away comparisons between allocas and any
1056 // pointer not based on that alloca (e.g. an argument). However, even
1057 // though such pointers cannot alias, they can still compare equal.
1058 //
1059 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1060 // doesn't escape we can argue that it's impossible to guess its value, and we
1061 // can therefore act as if any such guesses are wrong.
1062 //
1063 // The code below checks that the alloca doesn't escape, and that it's only
1064 // used in a comparison once (the current instruction). The
1065 // single-comparison-use condition ensures that we're trivially folding all
1066 // comparisons against the alloca consistently, and avoids the risk of
1067 // erroneously folding a comparison of the pointer with itself.
1068
1069 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1070
Pete Cooper980a9352016-08-12 17:13:28 +00001071 SmallVector<const Use *, 32> Worklist;
1072 for (const Use &U : Alloca->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001073 if (Worklist.size() >= MaxIter)
1074 return nullptr;
1075 Worklist.push_back(&U);
1076 }
1077
1078 unsigned NumCmps = 0;
1079 while (!Worklist.empty()) {
1080 assert(Worklist.size() <= MaxIter);
Pete Cooper980a9352016-08-12 17:13:28 +00001081 const Use *U = Worklist.pop_back_val();
1082 const Value *V = U->getUser();
Hans Wennborgf1f36512015-10-07 00:20:07 +00001083 --MaxIter;
1084
1085 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1086 isa<SelectInst>(V)) {
1087 // Track the uses.
1088 } else if (isa<LoadInst>(V)) {
1089 // Loading from the pointer doesn't escape it.
1090 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001091 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001092 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1093 if (SI->getValueOperand() == U->get())
1094 return nullptr;
1095 continue;
1096 } else if (isa<ICmpInst>(V)) {
1097 if (NumCmps++)
1098 return nullptr; // Found more than one cmp.
1099 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001100 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001101 switch (Intrin->getIntrinsicID()) {
1102 // These intrinsics don't escape or compare the pointer. Memset is safe
1103 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1104 // we don't allow stores, so src cannot point to V.
1105 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1106 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1107 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1108 continue;
1109 default:
1110 return nullptr;
1111 }
1112 } else {
1113 return nullptr;
1114 }
Pete Cooper980a9352016-08-12 17:13:28 +00001115 for (const Use &U : V->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001116 if (Worklist.size() >= MaxIter)
1117 return nullptr;
1118 Worklist.push_back(&U);
1119 }
1120 }
1121
1122 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001123 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001124 ICI,
1125 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1126}
1127
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001128/// Fold "icmp pred (X+CI), X".
Sanjay Patel43395062016-07-21 18:07:40 +00001129Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI,
1130 Value *X, ConstantInt *CI,
1131 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001132 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001133 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001134 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001135
Chris Lattner8c92b572010-01-08 17:48:19 +00001136 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001137 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1138 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1139 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001140 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001141 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001142 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1143 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001144
Chris Lattner2188e402010-01-04 07:37:31 +00001145 // (X+1) >u X --> X <u (0-1) --> X != 255
1146 // (X+2) >u X --> X <u (0-2) --> X <u 254
1147 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001148 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001149 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001150
Chris Lattner2188e402010-01-04 07:37:31 +00001151 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1152 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1153 APInt::getSignedMaxValue(BitWidth));
1154
1155 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1156 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1157 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1158 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1159 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1160 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001161 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001162 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001163
Chris Lattner2188e402010-01-04 07:37:31 +00001164 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1165 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1166 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1167 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1168 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1169 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001170
Chris Lattner2188e402010-01-04 07:37:31 +00001171 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001172 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001173 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1174}
1175
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001176/// Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001177/// (icmp eq/ne A, Log2(const2/const1)) ->
1178/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
Sanjay Patel43395062016-07-21 18:07:40 +00001179Instruction *InstCombiner::foldICmpCstShrConst(ICmpInst &I, Value *Op, Value *A,
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001180 ConstantInt *CI1,
1181 ConstantInt *CI2) {
1182 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1183
1184 auto getConstant = [&I, this](bool IsTrue) {
1185 if (I.getPredicate() == I.ICMP_NE)
1186 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001187 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001188 };
1189
1190 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1191 if (I.getPredicate() == I.ICMP_NE)
1192 Pred = CmpInst::getInversePredicate(Pred);
1193 return new ICmpInst(Pred, LHS, RHS);
1194 };
1195
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001196 const APInt &AP1 = CI1->getValue();
1197 const APInt &AP2 = CI2->getValue();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001198
David Majnemer2abb8182014-10-25 07:13:13 +00001199 // Don't bother doing any work for cases which InstSimplify handles.
1200 if (AP2 == 0)
1201 return nullptr;
1202 bool IsAShr = isa<AShrOperator>(Op);
1203 if (IsAShr) {
1204 if (AP2.isAllOnesValue())
1205 return nullptr;
1206 if (AP2.isNegative() != AP1.isNegative())
1207 return nullptr;
1208 if (AP2.sgt(AP1))
1209 return nullptr;
1210 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001211
David Majnemerd2056022014-10-21 19:51:55 +00001212 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001213 // 'A' must be large enough to shift out the highest set bit.
1214 return getICmp(I.ICMP_UGT, A,
1215 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001216
David Majnemerd2056022014-10-21 19:51:55 +00001217 if (AP1 == AP2)
1218 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001219
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001220 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001221 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001222 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001223 else
David Majnemere5977eb2015-09-19 00:48:26 +00001224 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001225
David Majnemerd2056022014-10-21 19:51:55 +00001226 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001227 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1228 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001229 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001230 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1231 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001232 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001233 } else if (AP1 == AP2.lshr(Shift)) {
1234 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1235 }
David Majnemerd2056022014-10-21 19:51:55 +00001236 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001237 // Shifting const2 will never be equal to const1.
1238 return getConstant(false);
1239}
Chris Lattner2188e402010-01-04 07:37:31 +00001240
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001241/// Handle "(icmp eq/ne (shl const2, A), const1)" ->
David Majnemer59939ac2014-10-19 08:23:08 +00001242/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
Sanjay Patel43395062016-07-21 18:07:40 +00001243Instruction *InstCombiner::foldICmpCstShlConst(ICmpInst &I, Value *Op, Value *A,
1244 ConstantInt *CI1,
1245 ConstantInt *CI2) {
David Majnemer59939ac2014-10-19 08:23:08 +00001246 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1247
1248 auto getConstant = [&I, this](bool IsTrue) {
1249 if (I.getPredicate() == I.ICMP_NE)
1250 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001251 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
David Majnemer59939ac2014-10-19 08:23:08 +00001252 };
1253
1254 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1255 if (I.getPredicate() == I.ICMP_NE)
1256 Pred = CmpInst::getInversePredicate(Pred);
1257 return new ICmpInst(Pred, LHS, RHS);
1258 };
1259
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001260 const APInt &AP1 = CI1->getValue();
1261 const APInt &AP2 = CI2->getValue();
David Majnemer59939ac2014-10-19 08:23:08 +00001262
David Majnemer2abb8182014-10-25 07:13:13 +00001263 // Don't bother doing any work for cases which InstSimplify handles.
1264 if (AP2 == 0)
1265 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001266
1267 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1268
1269 if (!AP1 && AP2TrailingZeros != 0)
1270 return getICmp(I.ICMP_UGE, A,
1271 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1272
1273 if (AP1 == AP2)
1274 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1275
1276 // Get the distance between the lowest bits that are set.
1277 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1278
1279 if (Shift > 0 && AP2.shl(Shift) == AP1)
1280 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1281
1282 // Shifting const2 will never be equal to const1.
1283 return getConstant(false);
1284}
1285
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001286/// Fold icmp (trunc X, Y), C.
1287Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp,
1288 Instruction *Trunc,
1289 const APInt *C) {
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001290 ICmpInst::Predicate Pred = Cmp.getPredicate();
1291 Value *X = Trunc->getOperand(0);
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001292 if (*C == 1 && C->getBitWidth() > 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001293 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1294 Value *V = nullptr;
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001295 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001296 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1297 ConstantInt::get(V->getType(), 1));
1298 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001299
1300 if (Cmp.isEquality() && Trunc->hasOneUse()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001301 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1302 // of the high bits truncated out of x are known.
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001303 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1304 SrcBits = X->getType()->getScalarSizeInBits();
Sanjay Patela3f4f082016-08-16 17:54:36 +00001305 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001306 computeKnownBits(X, KnownZero, KnownOne, 0, &Cmp);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001307
1308 // If all the high bits are known, we can do this xform.
1309 if ((KnownZero | KnownOne).countLeadingOnes() >= SrcBits - DstBits) {
1310 // Pull in the high bits from known-ones set.
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001311 APInt NewRHS = C->zext(SrcBits);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001312 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
Sanjay Patel40e8ca42016-08-18 20:28:54 +00001313 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001314 }
1315 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001316
Sanjay Patela3f4f082016-08-16 17:54:36 +00001317 return nullptr;
1318}
1319
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001320/// Fold icmp (xor X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001321Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp,
1322 BinaryOperator *Xor,
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001323 const APInt *C) {
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001324 Value *X = Xor->getOperand(0);
1325 Value *Y = Xor->getOperand(1);
Sanjay Pateldaffec912016-08-17 19:45:18 +00001326 const APInt *XorC;
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001327 if (!match(Y, m_APInt(XorC)))
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001328 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001329
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001330 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1331 // fold the xor.
1332 ICmpInst::Predicate Pred = Cmp.getPredicate();
1333 if ((Pred == ICmpInst::ICMP_SLT && *C == 0) ||
1334 (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001335
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001336 // If the sign bit of the XorCst is not set, there is no change to
1337 // the operation, just stop using the Xor.
Sanjay Pateldaffec912016-08-17 19:45:18 +00001338 if (!XorC->isNegative()) {
1339 Cmp.setOperand(0, X);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001340 Worklist.Add(Xor);
1341 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001342 }
1343
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001344 // Was the old condition true if the operand is positive?
1345 bool isTrueIfPositive = Pred == ICmpInst::ICMP_SGT;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001346
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001347 // If so, the new one isn't.
1348 isTrueIfPositive ^= true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001349
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001350 Constant *CmpConstant = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001351 if (isTrueIfPositive)
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001352 return new ICmpInst(ICmpInst::ICMP_SGT, X, SubOne(CmpConstant));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001353 else
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001354 return new ICmpInst(ICmpInst::ICMP_SLT, X, AddOne(CmpConstant));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001355 }
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001356
1357 if (Xor->hasOneUse()) {
Sanjay Pateldaffec912016-08-17 19:45:18 +00001358 // (icmp u/s (xor X SignBit), C) -> (icmp s/u X, (xor C SignBit))
1359 if (!Cmp.isEquality() && XorC->isSignBit()) {
1360 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1361 : Cmp.getSignedPredicate();
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001362 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001363 }
1364
Sanjay Pateldaffec912016-08-17 19:45:18 +00001365 // (icmp u/s (xor X ~SignBit), C) -> (icmp s/u X, (xor C ~SignBit))
1366 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1367 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1368 : Cmp.getSignedPredicate();
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001369 Pred = Cmp.getSwappedPredicate(Pred);
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001370 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001371 }
1372 }
1373
1374 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1375 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001376 if (Pred == ICmpInst::ICMP_UGT && *XorC == ~(*C) && (*C + 1).isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001377 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001378
1379 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1380 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001381 if (Pred == ICmpInst::ICMP_ULT && *XorC == -(*C) && C->isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001382 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001383
Sanjay Patela3f4f082016-08-16 17:54:36 +00001384 return nullptr;
1385}
1386
Sanjay Patel14e0e182016-08-26 18:28:46 +00001387/// Fold icmp (and (sh X, Y), C2), C1.
1388Instruction *InstCombiner::foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
Sanjay Patel9b40f982016-09-07 22:33:03 +00001389 const APInt *C1, const APInt *C2) {
1390 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1391 if (!Shift || !Shift->isShift())
Sanjay Patelda9c5622016-08-26 17:15:22 +00001392 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001393
Sanjay Patelda9c5622016-08-26 17:15:22 +00001394 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1395 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1396 // code produced by the clang front-end, for bitfield access.
Sanjay Patelda9c5622016-08-26 17:15:22 +00001397 // This seemingly simple opportunity to fold away a shift turns out to be
1398 // rather complicated. See PR17827 for details.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001399 unsigned ShiftOpcode = Shift->getOpcode();
1400 bool IsShl = ShiftOpcode == Instruction::Shl;
1401 const APInt *C3;
1402 if (match(Shift->getOperand(1), m_APInt(C3))) {
Sanjay Patelda9c5622016-08-26 17:15:22 +00001403 bool CanFold = false;
Sanjay Patelda9c5622016-08-26 17:15:22 +00001404 if (ShiftOpcode == Instruction::AShr) {
1405 // There may be some constraints that make this possible, but nothing
1406 // simple has been discovered yet.
1407 CanFold = false;
1408 } else if (ShiftOpcode == Instruction::Shl) {
1409 // For a left shift, we can fold if the comparison is not signed. We can
1410 // also fold a signed comparison if the mask value and comparison value
1411 // are not negative. These constraints may not be obvious, but we can
1412 // prove that they are correct using an SMT solver.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001413 if (!Cmp.isSigned() || (!C2->isNegative() && !C1->isNegative()))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001414 CanFold = true;
1415 } else if (ShiftOpcode == Instruction::LShr) {
1416 // For a logical right shift, we can fold if the comparison is not signed.
1417 // We can also fold a signed comparison if the shifted mask value and the
1418 // shifted comparison value are not negative. These constraints may not be
1419 // obvious, but we can prove that they are correct using an SMT solver.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001420 if (!Cmp.isSigned() ||
1421 (!C2->shl(*C3).isNegative() && !C1->shl(*C3).isNegative()))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001422 CanFold = true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001423 }
1424
Sanjay Patelda9c5622016-08-26 17:15:22 +00001425 if (CanFold) {
Sanjay Patel9b40f982016-09-07 22:33:03 +00001426 APInt NewCst = IsShl ? C1->lshr(*C3) : C1->shl(*C3);
1427 APInt SameAsC1 = IsShl ? NewCst.shl(*C3) : NewCst.lshr(*C3);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001428 // Check to see if we are shifting out any of the bits being compared.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001429 if (SameAsC1 != *C1) {
Sanjay Patelda9c5622016-08-26 17:15:22 +00001430 // If we shifted bits out, the fold is not going to work out. As a
1431 // special case, check to see if this means that the result is always
1432 // true or false now.
1433 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
Sanjay Patel1c608f42016-09-08 16:54:02 +00001434 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
Sanjay Patelda9c5622016-08-26 17:15:22 +00001435 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
Sanjay Patel1c608f42016-09-08 16:54:02 +00001436 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001437 } else {
Sanjay Patel9b40f982016-09-07 22:33:03 +00001438 Cmp.setOperand(1, ConstantInt::get(And->getType(), NewCst));
1439 APInt NewAndCst = IsShl ? C2->lshr(*C3) : C2->shl(*C3);
1440 And->setOperand(1, ConstantInt::get(And->getType(), NewAndCst));
Sanjay Patelda9c5622016-08-26 17:15:22 +00001441 And->setOperand(0, Shift->getOperand(0));
1442 Worklist.Add(Shift); // Shift is dead.
1443 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001444 }
Sanjay Patelda9c5622016-08-26 17:15:22 +00001445 }
1446 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001447
Sanjay Patelda9c5622016-08-26 17:15:22 +00001448 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1449 // preferable because it allows the C2 << Y expression to be hoisted out of a
1450 // loop if Y is invariant and X is not.
Sanjay Patel14e0e182016-08-26 18:28:46 +00001451 if (Shift->hasOneUse() && *C1 == 0 && Cmp.isEquality() &&
Sanjay Patelda9c5622016-08-26 17:15:22 +00001452 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1453 // Compute C2 << Y.
Sanjay Patel9b40f982016-09-07 22:33:03 +00001454 Value *NewShift =
1455 IsShl ? Builder->CreateLShr(And->getOperand(1), Shift->getOperand(1))
1456 : Builder->CreateShl(And->getOperand(1), Shift->getOperand(1));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001457
Sanjay Patelda9c5622016-08-26 17:15:22 +00001458 // Compute X & (C2 << Y).
Sanjay Patel9b40f982016-09-07 22:33:03 +00001459 Value *NewAnd = Builder->CreateAnd(Shift->getOperand(0), NewShift);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001460 Cmp.setOperand(0, NewAnd);
1461 return &Cmp;
1462 }
1463
Sanjay Patel14e0e182016-08-26 18:28:46 +00001464 return nullptr;
1465}
1466
1467/// Fold icmp (and X, C2), C1.
1468Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp,
1469 BinaryOperator *And,
1470 const APInt *C1) {
Sanjay Patel6b490972016-09-04 14:32:15 +00001471 const APInt *C2;
1472 if (!match(And->getOperand(1), m_APInt(C2)))
Sanjay Patel14e0e182016-08-26 18:28:46 +00001473 return nullptr;
1474
1475 if (!And->hasOneUse() || !And->getOperand(0)->hasOneUse())
1476 return nullptr;
1477
Sanjay Patel6b490972016-09-04 14:32:15 +00001478 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1479 // the input width without changing the value produced, eliminate the cast:
1480 //
1481 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1482 //
1483 // We can do this transformation if the constants do not have their sign bits
1484 // set or if it is an equality comparison. Extending a relational comparison
1485 // when we're checking the sign bit would not work.
1486 Value *W;
1487 if (match(And->getOperand(0), m_Trunc(m_Value(W))) &&
1488 (Cmp.isEquality() || (!C1->isNegative() && !C2->isNegative()))) {
1489 // TODO: Is this a good transform for vectors? Wider types may reduce
1490 // throughput. Should this transform be limited (even for scalars) by using
1491 // ShouldChangeType()?
1492 if (!Cmp.getType()->isVectorTy()) {
1493 Type *WideType = W->getType();
1494 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1495 Constant *ZextC1 = ConstantInt::get(WideType, C1->zext(WideScalarBits));
1496 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1497 Value *NewAnd = Builder->CreateAnd(W, ZextC2, And->getName());
1498 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
Sanjay Patel14e0e182016-08-26 18:28:46 +00001499 }
1500 }
1501
Sanjay Patel9b40f982016-09-07 22:33:03 +00001502 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2))
Sanjay Patel14e0e182016-08-26 18:28:46 +00001503 return I;
1504
Sanjay Patelda9c5622016-08-26 17:15:22 +00001505 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
Sanjay Patel6b490972016-09-04 14:32:15 +00001506 // (icmp pred (and A, (or (shl 1, B), 1), 0))
Sanjay Patelda9c5622016-08-26 17:15:22 +00001507 //
1508 // iff pred isn't signed
Sanjay Pateldef931e2016-09-07 20:50:44 +00001509 if (!Cmp.isSigned() && *C1 == 0 && match(And->getOperand(1), m_One())) {
1510 Constant *One = cast<Constant>(And->getOperand(1));
1511 Value *Or = And->getOperand(0);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001512 Value *A, *B, *LShr;
Sanjay Pateldef931e2016-09-07 20:50:44 +00001513 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1514 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1515 unsigned UsesRemoved = 0;
1516 if (And->hasOneUse())
1517 ++UsesRemoved;
1518 if (Or->hasOneUse())
1519 ++UsesRemoved;
1520 if (LShr->hasOneUse())
1521 ++UsesRemoved;
1522
1523 // Compute A & ((1 << B) | 1)
1524 Value *NewOr = nullptr;
1525 if (auto *C = dyn_cast<Constant>(B)) {
1526 if (UsesRemoved >= 1)
1527 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1528 } else {
1529 if (UsesRemoved >= 3)
1530 NewOr = Builder->CreateOr(Builder->CreateShl(One, B, LShr->getName(),
Sanjay Patelda9c5622016-08-26 17:15:22 +00001531 /*HasNUW=*/true),
1532 One, Or->getName());
Sanjay Pateldef931e2016-09-07 20:50:44 +00001533 }
1534 if (NewOr) {
1535 Value *NewAnd = Builder->CreateAnd(A, NewOr, And->getName());
1536 Cmp.setOperand(0, NewAnd);
1537 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001538 }
1539 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001540 }
Sanjay Patelda9c5622016-08-26 17:15:22 +00001541
Sanjay Pateldef931e2016-09-07 20:50:44 +00001542 // (X & C2) > C1 --> (X & C2) != 0, if any bit set in (X & C2) will produce a
1543 // result greater than C1.
1544 unsigned NumTZ = C2->countTrailingZeros();
1545 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && NumTZ < C2->getBitWidth() &&
1546 APInt::getOneBitSet(C2->getBitWidth(), NumTZ).ugt(*C1)) {
1547 Constant *Zero = Constant::getNullValue(And->getType());
1548 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero);
Sanjay Patelda9c5622016-08-26 17:15:22 +00001549 }
1550
Sanjay Pateld3c7bb282016-08-26 16:42:33 +00001551 return nullptr;
1552}
1553
1554/// Fold icmp (and X, Y), C.
1555Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp,
1556 BinaryOperator *And,
1557 const APInt *C) {
1558 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1559 return I;
1560
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001561 // TODO: These all require that Y is constant too, so refactor with the above.
Sanjay Patela3f4f082016-08-16 17:54:36 +00001562
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001563 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1564 Value *X = And->getOperand(0);
1565 Value *Y = And->getOperand(1);
1566 if (auto *LI = dyn_cast<LoadInst>(X))
1567 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1568 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001569 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001570 !LI->isVolatile() && isa<ConstantInt>(Y)) {
1571 ConstantInt *C2 = cast<ConstantInt>(Y);
1572 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001573 return Res;
1574 }
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001575
1576 if (!Cmp.isEquality())
1577 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001578
1579 // X & -C == -C -> X > u ~C
1580 // X & -C != -C -> X <= u ~C
1581 // iff C is a power of 2
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001582 if (Cmp.getOperand(1) == Y && (-(*C)).isPowerOf2()) {
1583 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT
1584 : CmpInst::ICMP_ULE;
1585 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1586 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001587
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001588 // (X & C2) == 0 -> (trunc X) >= 0
1589 // (X & C2) != 0 -> (trunc X) < 0
1590 // iff C2 is a power of 2 and it masks the sign bit of a legal integer type.
1591 const APInt *C2;
1592 if (And->hasOneUse() && *C == 0 && match(Y, m_APInt(C2))) {
1593 int32_t ExactLogBase2 = C2->exactLogBase2();
1594 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1595 Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1);
1596 if (And->getType()->isVectorTy())
1597 NTy = VectorType::get(NTy, And->getType()->getVectorNumElements());
1598 Value *Trunc = Builder->CreateTrunc(X, NTy);
1599 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE
1600 : CmpInst::ICMP_SLT;
1601 return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001602 }
1603 }
Sanjay Patel5c5311f2016-08-28 18:18:00 +00001604
Sanjay Patela3f4f082016-08-16 17:54:36 +00001605 return nullptr;
1606}
1607
Sanjay Patel943e92e2016-08-17 16:30:43 +00001608/// Fold icmp (or X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001609Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
Sanjay Patel943e92e2016-08-17 16:30:43 +00001610 const APInt *C) {
Sanjay Patel943e92e2016-08-17 16:30:43 +00001611 ICmpInst::Predicate Pred = Cmp.getPredicate();
1612 if (*C == 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001613 // icmp slt signum(V) 1 --> icmp slt V, 1
1614 Value *V = nullptr;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001615 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001616 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1617 ConstantInt::get(V->getType(), 1));
1618 }
1619
Sanjay Patel943e92e2016-08-17 16:30:43 +00001620 if (!Cmp.isEquality() || *C != 0 || !Or->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00001621 return nullptr;
1622
1623 Value *P, *Q;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001624 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001625 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1626 // -> and (icmp eq P, null), (icmp eq Q, null).
Reid Klecknera871d382016-08-19 16:53:18 +00001627 Value *CmpP =
1628 Builder->CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
1629 Value *CmpQ =
1630 Builder->CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
Sanjay Patel943e92e2016-08-17 16:30:43 +00001631 auto LogicOpc = Pred == ICmpInst::Predicate::ICMP_EQ ? Instruction::And
1632 : Instruction::Or;
1633 return BinaryOperator::Create(LogicOpc, CmpP, CmpQ);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001634 }
Sanjay Patel943e92e2016-08-17 16:30:43 +00001635
Sanjay Patela3f4f082016-08-16 17:54:36 +00001636 return nullptr;
1637}
1638
Sanjay Patel63478072016-08-18 15:44:44 +00001639/// Fold icmp (mul X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001640Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp,
1641 BinaryOperator *Mul,
Sanjay Patel63478072016-08-18 15:44:44 +00001642 const APInt *C) {
1643 const APInt *MulC;
1644 if (!match(Mul->getOperand(1), m_APInt(MulC)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001645 return nullptr;
1646
Sanjay Patel63478072016-08-18 15:44:44 +00001647 // If this is a test of the sign bit and the multiply is sign-preserving with
1648 // a constant operand, use the multiply LHS operand instead.
1649 ICmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patelc9196c42016-08-22 21:24:29 +00001650 if (isSignTest(Pred, *C) && Mul->hasNoSignedWrap()) {
Sanjay Patel63478072016-08-18 15:44:44 +00001651 if (MulC->isNegative())
1652 Pred = ICmpInst::getSwappedPredicate(Pred);
1653 return new ICmpInst(Pred, Mul->getOperand(0),
1654 Constant::getNullValue(Mul->getType()));
1655 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001656
1657 return nullptr;
1658}
1659
Sanjay Patel98cd99d2016-08-18 21:28:30 +00001660/// Fold icmp (shl 1, Y), C.
1661static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
1662 const APInt *C) {
1663 Value *Y;
1664 if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
1665 return nullptr;
1666
1667 Type *ShiftType = Shl->getType();
1668 uint32_t TypeBits = C->getBitWidth();
1669 bool CIsPowerOf2 = C->isPowerOf2();
1670 ICmpInst::Predicate Pred = Cmp.getPredicate();
1671 if (Cmp.isUnsigned()) {
1672 // (1 << Y) pred C -> Y pred Log2(C)
1673 if (!CIsPowerOf2) {
1674 // (1 << Y) < 30 -> Y <= 4
1675 // (1 << Y) <= 30 -> Y <= 4
1676 // (1 << Y) >= 30 -> Y > 4
1677 // (1 << Y) > 30 -> Y > 4
1678 if (Pred == ICmpInst::ICMP_ULT)
1679 Pred = ICmpInst::ICMP_ULE;
1680 else if (Pred == ICmpInst::ICMP_UGE)
1681 Pred = ICmpInst::ICMP_UGT;
1682 }
1683
1684 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31
1685 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31
1686 unsigned CLog2 = C->logBase2();
1687 if (CLog2 == TypeBits - 1) {
1688 if (Pred == ICmpInst::ICMP_UGE)
1689 Pred = ICmpInst::ICMP_EQ;
1690 else if (Pred == ICmpInst::ICMP_ULT)
1691 Pred = ICmpInst::ICMP_NE;
1692 }
1693 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
1694 } else if (Cmp.isSigned()) {
1695 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
1696 if (C->isAllOnesValue()) {
1697 // (1 << Y) <= -1 -> Y == 31
1698 if (Pred == ICmpInst::ICMP_SLE)
1699 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1700
1701 // (1 << Y) > -1 -> Y != 31
1702 if (Pred == ICmpInst::ICMP_SGT)
1703 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1704 } else if (!(*C)) {
1705 // (1 << Y) < 0 -> Y == 31
1706 // (1 << Y) <= 0 -> Y == 31
1707 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1708 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
1709
1710 // (1 << Y) >= 0 -> Y != 31
1711 // (1 << Y) > 0 -> Y != 31
1712 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1713 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
1714 }
1715 } else if (Cmp.isEquality() && CIsPowerOf2) {
1716 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C->logBase2()));
1717 }
1718
1719 return nullptr;
1720}
1721
Sanjay Patel38b75062016-08-19 17:20:37 +00001722/// Fold icmp (shl X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001723Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp,
1724 BinaryOperator *Shl,
Sanjay Patel38b75062016-08-19 17:20:37 +00001725 const APInt *C) {
Sanjay Patelfa7de602016-08-19 22:33:26 +00001726 const APInt *ShiftAmt;
1727 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
Sanjay Patel38b75062016-08-19 17:20:37 +00001728 return foldICmpShlOne(Cmp, Shl, C);
Sanjay Patela867afe2016-08-19 16:12:16 +00001729
Sanjay Patel38b75062016-08-19 17:20:37 +00001730 // Check that the shift amount is in range. If not, don't perform undefined
1731 // shifts. When the shift is visited it will be simplified.
1732 unsigned TypeBits = C->getBitWidth();
Sanjay Patelfa7de602016-08-19 22:33:26 +00001733 if (ShiftAmt->uge(TypeBits))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001734 return nullptr;
1735
Sanjay Patele38e79c2016-08-19 17:34:05 +00001736 ICmpInst::Predicate Pred = Cmp.getPredicate();
1737 Value *X = Shl->getOperand(0);
Sanjay Patel38b75062016-08-19 17:20:37 +00001738 if (Cmp.isEquality()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001739 // If the shift is NUW, then it is just shifting out zeros, no need for an
1740 // AND.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001741 Constant *LShrC = ConstantInt::get(Shl->getType(), C->lshr(*ShiftAmt));
Sanjay Patelc9196c42016-08-22 21:24:29 +00001742 if (Shl->hasNoUnsignedWrap())
Sanjay Patelfa7de602016-08-19 22:33:26 +00001743 return new ICmpInst(Pred, X, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001744
1745 // If the shift is NSW and we compare to 0, then it is just shifting out
1746 // sign bits, no need for an AND either.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001747 if (Shl->hasNoSignedWrap() && *C == 0)
Sanjay Patelfa7de602016-08-19 22:33:26 +00001748 return new ICmpInst(Pred, X, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001749
Sanjay Patel38b75062016-08-19 17:20:37 +00001750 if (Shl->hasOneUse()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001751 // Otherwise strength reduce the shift into an and.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001752 Constant *Mask = ConstantInt::get(Shl->getType(),
1753 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001754
Sanjay Patele38e79c2016-08-19 17:34:05 +00001755 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask");
Sanjay Patelfa7de602016-08-19 22:33:26 +00001756 return new ICmpInst(Pred, And, LShrC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001757 }
1758 }
1759
1760 // If this is a signed comparison to 0 and the shift is sign preserving,
Sanjay Patele38e79c2016-08-19 17:34:05 +00001761 // use the shift LHS operand instead; isSignTest may change 'Pred', so only
1762 // do that if we're sure to not continue on in this function.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001763 if (Shl->hasNoSignedWrap() && isSignTest(Pred, *C))
Sanjay Patel7e09f132016-08-21 16:28:22 +00001764 return new ICmpInst(Pred, X, Constant::getNullValue(X->getType()));
1765
Sanjay Patela3f4f082016-08-16 17:54:36 +00001766 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1767 bool TrueIfSigned = false;
Sanjay Patel79263662016-08-21 15:07:45 +00001768 if (Shl->hasOneUse() && isSignBitCheck(Pred, *C, TrueIfSigned)) {
Sanjay Patel7ffcde72016-08-21 16:35:34 +00001769 // (X << 31) <s 0 --> (X & 1) != 0
Sanjay Patela3f4f082016-08-16 17:54:36 +00001770 Constant *Mask = ConstantInt::get(
Sanjay Patele38e79c2016-08-19 17:34:05 +00001771 X->getType(),
Sanjay Patelfa7de602016-08-19 22:33:26 +00001772 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
Sanjay Patele38e79c2016-08-19 17:34:05 +00001773 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask");
Sanjay Patela3f4f082016-08-16 17:54:36 +00001774 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1775 And, Constant::getNullValue(And->getType()));
1776 }
1777
Sanjay Patel643d21a2016-08-21 17:10:07 +00001778 // Transform (icmp pred iM (shl iM %v, N), C)
1779 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
1780 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
1781 // This enables us to get rid of the shift in favor of a trunc which can be
Sanjay Patela3f4f082016-08-16 17:54:36 +00001782 // free on the target. It has the additional benefit of comparing to a
1783 // smaller constant, which will be target friendly.
Sanjay Patelfa7de602016-08-19 22:33:26 +00001784 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
Sanjay Patel38b75062016-08-19 17:20:37 +00001785 if (Shl->hasOneUse() && Amt != 0 && C->countTrailingZeros() >= Amt) {
Sanjay Patel643d21a2016-08-21 17:10:07 +00001786 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
1787 if (X->getType()->isVectorTy())
1788 TruncTy = VectorType::get(TruncTy, X->getType()->getVectorNumElements());
1789 Constant *NewC =
1790 ConstantInt::get(TruncTy, C->ashr(*ShiftAmt).trunc(TypeBits - Amt));
1791 return new ICmpInst(Pred, Builder->CreateTrunc(X, TruncTy), NewC);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001792 }
1793
1794 return nullptr;
1795}
1796
Sanjay Patela3920492016-08-22 20:45:06 +00001797/// Fold icmp ({al}shr X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00001798Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp,
1799 BinaryOperator *Shr,
1800 const APInt *C) {
Sanjay Patela3920492016-08-22 20:45:06 +00001801 // An exact shr only shifts out zero bits, so:
1802 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
Sanjay Pateld64e9882016-08-23 22:05:55 +00001803 Value *X = Shr->getOperand(0);
Sanjay Patelc9196c42016-08-22 21:24:29 +00001804 CmpInst::Predicate Pred = Cmp.getPredicate();
1805 if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() && *C == 0)
Sanjay Pateld64e9882016-08-23 22:05:55 +00001806 return new ICmpInst(Pred, X, Cmp.getOperand(1));
Sanjay Patela3920492016-08-22 20:45:06 +00001807
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001808 const APInt *ShiftAmt;
1809 if (!match(Shr->getOperand(1), m_APInt(ShiftAmt)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001810 return nullptr;
1811
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001812 // Check that the shift amount is in range. If not, don't perform undefined
1813 // shifts. When the shift is visited it will be simplified.
1814 unsigned TypeBits = C->getBitWidth();
1815 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001816 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
1817 return nullptr;
1818
Sanjay Pateld64e9882016-08-23 22:05:55 +00001819 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001820 if (!Cmp.isEquality()) {
1821 // If we have an unsigned comparison and an ashr, we can't simplify this.
1822 // Similarly for signed comparisons with lshr.
Sanjay Pateld64e9882016-08-23 22:05:55 +00001823 if (Cmp.isSigned() != IsAShr)
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001824 return nullptr;
1825
1826 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1827 // by a power of 2. Since we already have logic to simplify these,
1828 // transform to div and then simplify the resultant comparison.
Sanjay Pateld64e9882016-08-23 22:05:55 +00001829 if (IsAShr && (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001830 return nullptr;
1831
1832 // Revisit the shift (to delete it).
1833 Worklist.Add(Shr);
1834
1835 Constant *DivCst = ConstantInt::get(
1836 Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
1837
Sanjay Pateld64e9882016-08-23 22:05:55 +00001838 Value *Tmp = IsAShr ? Builder->CreateSDiv(X, DivCst, "", Shr->isExact())
1839 : Builder->CreateUDiv(X, DivCst, "", Shr->isExact());
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001840
1841 Cmp.setOperand(0, Tmp);
1842
1843 // If the builder folded the binop, just return it.
1844 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1845 if (!TheDiv)
1846 return &Cmp;
1847
1848 // Otherwise, fold this div/compare.
1849 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1850 TheDiv->getOpcode() == Instruction::UDiv);
1851
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001852 Instruction *Res = foldICmpDivConstant(Cmp, TheDiv, C);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001853 assert(Res && "This div/cst should have folded!");
Sanjay Patela3920492016-08-22 20:45:06 +00001854 return Res;
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001855 }
1856
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001857 // Handle equality comparisons of shift-by-constant.
1858
Sanjay Patel8e297742016-08-24 13:55:55 +00001859 // If the comparison constant changes with the shift, the comparison cannot
1860 // succeed (bits of the comparison constant cannot match the shifted value).
1861 // This should be known by InstSimplify and already be folded to true/false.
1862 assert(((IsAShr && C->shl(ShAmtVal).ashr(ShAmtVal) == *C) ||
1863 (!IsAShr && C->shl(ShAmtVal).lshr(ShAmtVal) == *C)) &&
1864 "Expected icmp+shr simplify did not occur.");
1865
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001866 // Check if the bits shifted out are known to be zero. If so, we can compare
1867 // against the unshifted value:
1868 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001869 Constant *ShiftedCmpRHS = ConstantInt::get(Shr->getType(), *C << ShAmtVal);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001870 if (Shr->hasOneUse()) {
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001871 if (Shr->isExact())
1872 return new ICmpInst(Pred, X, ShiftedCmpRHS);
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001873
Sanjay Pateld398d4a2016-08-24 22:22:06 +00001874 // Otherwise strength reduce the shift into an 'and'.
1875 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1876 Constant *Mask = ConstantInt::get(Shr->getType(), Val);
Sanjay Pateld64e9882016-08-23 22:05:55 +00001877 Value *And = Builder->CreateAnd(X, Mask, Shr->getName() + ".mask");
Sanjay Pateldcac0df2016-08-23 21:25:13 +00001878 return new ICmpInst(Pred, And, ShiftedCmpRHS);
1879 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001880
1881 return nullptr;
1882}
1883
Sanjay Patel12a41052016-08-18 17:37:26 +00001884/// Fold icmp (udiv X, Y), C.
1885Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp,
Sanjay Patelc9196c42016-08-22 21:24:29 +00001886 BinaryOperator *UDiv,
Sanjay Patel12a41052016-08-18 17:37:26 +00001887 const APInt *C) {
Sanjay Patelfa5ca2b2016-08-18 17:55:59 +00001888 const APInt *C2;
1889 if (!match(UDiv->getOperand(0), m_APInt(C2)))
1890 return nullptr;
1891
1892 assert(C2 != 0 && "udiv 0, X should have been simplified already.");
1893
1894 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
1895 Value *Y = UDiv->getOperand(1);
1896 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) {
1897 assert(!C->isMaxValue() &&
1898 "icmp ugt X, UINT_MAX should have been simplified already.");
1899 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
1900 ConstantInt::get(Y->getType(), C2->udiv(*C + 1)));
1901 }
1902
1903 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
1904 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) {
1905 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
1906 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
1907 ConstantInt::get(Y->getType(), C2->udiv(*C)));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001908 }
1909
1910 return nullptr;
1911}
1912
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001913/// Fold icmp ({su}div X, Y), C.
1914Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp,
1915 BinaryOperator *Div,
1916 const APInt *C) {
Sanjay Patela7cb4772016-08-30 17:10:49 +00001917 // Fold: icmp pred ([us]div X, C2), C -> range test
Sanjay Patela3f4f082016-08-16 17:54:36 +00001918 // Fold this div into the comparison, producing a range check.
1919 // Determine, based on the divide type, what the range is being
1920 // checked. If there is an overflow on the low or high side, remember
1921 // it, otherwise compute the range [low, hi) bounding the new value.
1922 // See: InsertRangeTest above for the kinds of replacements possible.
Sanjay Patela7cb4772016-08-30 17:10:49 +00001923 const APInt *C2;
1924 if (!match(Div->getOperand(1), m_APInt(C2)))
Sanjay Patel16554142016-08-24 23:03:36 +00001925 return nullptr;
1926
Sanjay Patel16554142016-08-24 23:03:36 +00001927 // FIXME: If the operand types don't match the type of the divide
1928 // then don't attempt this transform. The code below doesn't have the
1929 // logic to deal with a signed divide and an unsigned compare (and
Sanjay Patela7cb4772016-08-30 17:10:49 +00001930 // vice versa). This is because (x /s C2) <s C produces different
1931 // results than (x /s C2) <u C or (x /u C2) <s C or even
1932 // (x /u C2) <u C. Simply casting the operands and result won't
Sanjay Patel16554142016-08-24 23:03:36 +00001933 // work. :( The if statement below tests that condition and bails
1934 // if it finds it.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001935 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
1936 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
Sanjay Patel16554142016-08-24 23:03:36 +00001937 return nullptr;
Sanjay Patela7cb4772016-08-30 17:10:49 +00001938
Sanjay Pateleea2ef72016-09-05 23:38:22 +00001939 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
1940 // INT_MIN will also fail if the divisor is 1. Although folds of all these
1941 // division-by-constant cases should be present, we can not assert that they
1942 // have happened before we reach this icmp instruction.
1943 if (*C2 == 0 || *C2 == 1 || (DivIsSigned && C2->isAllOnesValue()))
1944 return nullptr;
Sanjay Patelb3714572016-08-30 17:31:34 +00001945
Sanjay Patel541aef42016-08-31 21:57:21 +00001946 // TODO: We could do all of the computations below using APInt.
1947 Constant *CmpRHS = cast<Constant>(Cmp.getOperand(1));
1948 Constant *DivRHS = cast<Constant>(Div->getOperand(1));
Sanjay Patelb3714572016-08-30 17:31:34 +00001949
Sanjay Patel541aef42016-08-31 21:57:21 +00001950 // Compute Prod = CmpRHS * DivRHS. We are essentially solving an equation of
1951 // form X / C2 = C. We solve for X by multiplying C2 (DivRHS) and C (CmpRHS).
1952 // By solving for X, we can turn this into a range check instead of computing
1953 // a divide.
1954 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Sanjay Patel16554142016-08-24 23:03:36 +00001955
Sanjay Patel541aef42016-08-31 21:57:21 +00001956 // Determine if the product overflows by seeing if the product is not equal to
1957 // the divide. Make sure we do the same kind of divide as in the LHS
1958 // instruction that we're folding.
1959 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS)
1960 : ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Sanjay Patel16554142016-08-24 23:03:36 +00001961
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001962 ICmpInst::Predicate Pred = Cmp.getPredicate();
Sanjay Patel16554142016-08-24 23:03:36 +00001963
1964 // If the division is known to be exact, then there is no remainder from the
1965 // divide, so the covered range size is unit, otherwise it is the divisor.
Sanjay Patel541aef42016-08-31 21:57:21 +00001966 Constant *RangeSize =
1967 Div->isExact() ? ConstantInt::get(Div->getType(), 1) : DivRHS;
Sanjay Patel16554142016-08-24 23:03:36 +00001968
1969 // Figure out the interval that is being checked. For example, a comparison
1970 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
1971 // Compute this interval based on the constants involved and the signedness of
1972 // the compare/divide. This computes a half-open interval, keeping track of
1973 // whether either value in the interval overflows. After analysis each
1974 // overflow variable is set to 0 if it's corresponding bound variable is valid
1975 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
1976 int LoOverflow = 0, HiOverflow = 0;
1977 Constant *LoBound = nullptr, *HiBound = nullptr;
1978
1979 if (!DivIsSigned) { // udiv
1980 // e.g. X/5 op 3 --> [15, 20)
1981 LoBound = Prod;
1982 HiOverflow = LoOverflow = ProdOV;
1983 if (!HiOverflow) {
1984 // If this is not an exact divide, then many values in the range collapse
1985 // to the same result value.
1986 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
1987 }
Sanjay Patel541aef42016-08-31 21:57:21 +00001988 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001989 if (*C == 0) { // (X / pos) op 0
Sanjay Patel16554142016-08-24 23:03:36 +00001990 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
1991 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
1992 HiBound = RangeSize;
Sanjay Patelf7ba0892016-08-26 15:53:01 +00001993 } else if (C->isStrictlyPositive()) { // (X / pos) op pos
Sanjay Patel16554142016-08-24 23:03:36 +00001994 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
1995 HiOverflow = LoOverflow = ProdOV;
1996 if (!HiOverflow)
1997 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
1998 } else { // (X / pos) op neg
1999 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2000 HiBound = AddOne(Prod);
2001 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2002 if (!LoOverflow) {
Sanjay Patel541aef42016-08-31 21:57:21 +00002003 Constant *DivNeg = ConstantExpr::getNeg(RangeSize);
Sanjay Patel16554142016-08-24 23:03:36 +00002004 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2005 }
2006 }
Sanjay Patel541aef42016-08-31 21:57:21 +00002007 } else if (C2->isNegative()) { // Divisor is < 0.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002008 if (Div->isExact())
Sanjay Patel541aef42016-08-31 21:57:21 +00002009 RangeSize = ConstantExpr::getNeg(RangeSize);
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002010 if (*C == 0) { // (X / neg) op 0
Sanjay Patel16554142016-08-24 23:03:36 +00002011 // e.g. X/-5 op 0 --> [-4, 5)
2012 LoBound = AddOne(RangeSize);
Sanjay Patel541aef42016-08-31 21:57:21 +00002013 HiBound = ConstantExpr::getNeg(RangeSize);
Sanjay Patel16554142016-08-24 23:03:36 +00002014 if (HiBound == DivRHS) { // -INTMIN = INTMIN
2015 HiOverflow = 1; // [INTMIN+1, overflow)
2016 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
2017 }
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002018 } else if (C->isStrictlyPositive()) { // (X / neg) op pos
Sanjay Patel16554142016-08-24 23:03:36 +00002019 // e.g. X/-5 op 3 --> [-19, -14)
2020 HiBound = AddOne(Prod);
2021 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2022 if (!LoOverflow)
2023 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
2024 } else { // (X / neg) op neg
2025 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2026 LoOverflow = HiOverflow = ProdOV;
2027 if (!HiOverflow)
2028 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
2029 }
2030
2031 // Dividing by a negative swaps the condition. LT <-> GT
2032 Pred = ICmpInst::getSwappedPredicate(Pred);
2033 }
2034
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002035 Value *X = Div->getOperand(0);
Sanjay Patel16554142016-08-24 23:03:36 +00002036 switch (Pred) {
2037 default: llvm_unreachable("Unhandled icmp opcode!");
2038 case ICmpInst::ICMP_EQ:
2039 if (LoOverflow && HiOverflow)
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002040 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002041 if (HiOverflow)
2042 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2043 ICmpInst::ICMP_UGE, X, LoBound);
2044 if (LoOverflow)
2045 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2046 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel85d79742016-08-31 19:49:56 +00002047 return replaceInstUsesWith(
Sanjay Patel541aef42016-08-31 21:57:21 +00002048 Cmp, insertRangeTest(X, LoBound->getUniqueInteger(),
2049 HiBound->getUniqueInteger(), DivIsSigned, true));
Sanjay Patel16554142016-08-24 23:03:36 +00002050 case ICmpInst::ICMP_NE:
2051 if (LoOverflow && HiOverflow)
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002052 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002053 if (HiOverflow)
2054 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
2055 ICmpInst::ICMP_ULT, X, LoBound);
2056 if (LoOverflow)
2057 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
2058 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel541aef42016-08-31 21:57:21 +00002059 return replaceInstUsesWith(Cmp,
2060 insertRangeTest(X, LoBound->getUniqueInteger(),
2061 HiBound->getUniqueInteger(),
2062 DivIsSigned, false));
Sanjay Patel16554142016-08-24 23:03:36 +00002063 case ICmpInst::ICMP_ULT:
2064 case ICmpInst::ICMP_SLT:
2065 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002066 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002067 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002068 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002069 return new ICmpInst(Pred, X, LoBound);
2070 case ICmpInst::ICMP_UGT:
2071 case ICmpInst::ICMP_SGT:
2072 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002073 return replaceInstUsesWith(Cmp, Builder->getFalse());
Sanjay Patel16554142016-08-24 23:03:36 +00002074 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patelf7ba0892016-08-26 15:53:01 +00002075 return replaceInstUsesWith(Cmp, Builder->getTrue());
Sanjay Patel16554142016-08-24 23:03:36 +00002076 if (Pred == ICmpInst::ICMP_UGT)
2077 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
2078 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
2079 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002080
2081 return nullptr;
2082}
2083
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002084/// Fold icmp (sub X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002085Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp,
2086 BinaryOperator *Sub,
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002087 const APInt *C) {
Sanjay Patele47df1a2016-08-16 21:53:19 +00002088 const APInt *C2;
2089 if (!match(Sub->getOperand(0), m_APInt(C2)) || !Sub->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00002090 return nullptr;
2091
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002092 // C-X <u C2 -> (X|(C2-1)) == C
2093 // iff C & (C2-1) == C2-1
Sanjay Patela3f4f082016-08-16 17:54:36 +00002094 // C2 is a power of 2
Sanjay Patele47df1a2016-08-16 21:53:19 +00002095 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2096 (*C2 & (*C - 1)) == (*C - 1))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002097 return new ICmpInst(ICmpInst::ICMP_EQ,
Sanjay Patele47df1a2016-08-16 21:53:19 +00002098 Builder->CreateOr(Sub->getOperand(1), *C - 1),
2099 Sub->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002100
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002101 // C-X >u C2 -> (X|C2) != C
2102 // iff C & C2 == C2
Sanjay Patela3f4f082016-08-16 17:54:36 +00002103 // C2+1 is a power of 2
Sanjay Patele47df1a2016-08-16 21:53:19 +00002104 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2105 (*C2 & *C) == *C)
Sanjay Patela3f4f082016-08-16 17:54:36 +00002106 return new ICmpInst(ICmpInst::ICMP_NE,
Sanjay Patele47df1a2016-08-16 21:53:19 +00002107 Builder->CreateOr(Sub->getOperand(1), *C),
2108 Sub->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002109
2110 return nullptr;
2111}
2112
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002113/// Fold icmp (add X, Y), C.
Sanjay Patelc9196c42016-08-22 21:24:29 +00002114Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp,
2115 BinaryOperator *Add,
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002116 const APInt *C) {
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002117 Value *Y = Add->getOperand(1);
2118 const APInt *C2;
2119 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002120 return nullptr;
2121
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002122 // Fold icmp pred (add X, C2), C.
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002123 Value *X = Add->getOperand(0);
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002124 Type *Ty = Add->getType();
2125 auto CR = Cmp.makeConstantRange(Cmp.getPredicate(), *C).subtract(*C2);
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002126 const APInt &Upper = CR.getUpper();
2127 const APInt &Lower = CR.getLower();
2128 if (Cmp.isSigned()) {
2129 if (Lower.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002130 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002131 if (Upper.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002132 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002133 } else {
2134 if (Lower.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002135 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002136 if (Upper.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002137 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002138 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002139
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002140 if (!Add->hasOneUse())
2141 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002142
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002143 // X+C <u C2 -> (X & -C2) == C
2144 // iff C & (C2-1) == 0
2145 // C2 is a power of 2
2146 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2147 (*C2 & (*C - 1)) == 0)
2148 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(X, -(*C)),
2149 ConstantExpr::getNeg(cast<Constant>(Y)));
2150
2151 // X+C >u C2 -> (X & ~C2) != C
2152 // iff C & C2 == 0
2153 // C2+1 is a power of 2
2154 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2155 (*C2 & *C) == 0)
2156 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(X, ~(*C)),
2157 ConstantExpr::getNeg(cast<Constant>(Y)));
2158
Sanjay Patela3f4f082016-08-16 17:54:36 +00002159 return nullptr;
2160}
2161
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002162/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
2163/// where X is some kind of instruction.
2164Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) {
Sanjay Patelc9196c42016-08-22 21:24:29 +00002165 const APInt *C;
2166 if (!match(Cmp.getOperand(1), m_APInt(C)))
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00002167 return nullptr;
2168
Sanjay Patelc9196c42016-08-22 21:24:29 +00002169 BinaryOperator *BO;
2170 if (match(Cmp.getOperand(0), m_BinOp(BO))) {
2171 switch (BO->getOpcode()) {
2172 case Instruction::Xor:
2173 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
2174 return I;
2175 break;
2176 case Instruction::And:
2177 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
2178 return I;
2179 break;
2180 case Instruction::Or:
2181 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
2182 return I;
2183 break;
2184 case Instruction::Mul:
2185 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
2186 return I;
2187 break;
2188 case Instruction::Shl:
2189 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
2190 return I;
2191 break;
2192 case Instruction::LShr:
2193 case Instruction::AShr:
2194 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
2195 return I;
2196 break;
2197 case Instruction::UDiv:
2198 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
2199 return I;
2200 LLVM_FALLTHROUGH;
2201 case Instruction::SDiv:
2202 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
2203 return I;
2204 break;
2205 case Instruction::Sub:
2206 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
2207 return I;
2208 break;
2209 case Instruction::Add:
2210 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
2211 return I;
2212 break;
2213 default:
2214 break;
2215 }
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002216 // TODO: These folds could be refactored to be part of the above calls.
2217 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
2218 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002219 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002220
Sanjay Patelc9196c42016-08-22 21:24:29 +00002221 Instruction *LHSI;
2222 if (match(Cmp.getOperand(0), m_Instruction(LHSI)) &&
2223 LHSI->getOpcode() == Instruction::Trunc)
2224 if (Instruction *I = foldICmpTruncConstant(Cmp, LHSI, C))
2225 return I;
2226
Sanjay Patelf58f68c2016-09-10 15:03:44 +00002227 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, C))
2228 return I;
2229
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002230 return nullptr;
2231}
Jim Grosbach129c52a2011-09-30 18:09:53 +00002232
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002233/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
2234/// icmp eq/ne BO, C.
2235Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
2236 BinaryOperator *BO,
2237 const APInt *C) {
2238 // TODO: Some of these folds could work with arbitrary constants, but this
2239 // function is limited to scalar and vector splat constants.
2240 if (!Cmp.isEquality())
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002241 return nullptr;
2242
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002243 ICmpInst::Predicate Pred = Cmp.getPredicate();
2244 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
2245 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel51a767c2016-08-03 17:23:08 +00002246 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002247
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002248 switch (BO->getOpcode()) {
2249 case Instruction::SRem:
2250 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002251 if (*C == 0 && BO->hasOneUse()) {
Sanjay Patel2e9675f2016-08-03 19:48:40 +00002252 const APInt *BOC;
2253 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002254 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName());
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002255 return new ICmpInst(Pred, NewRem,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002256 Constant::getNullValue(BO->getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002257 }
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002258 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002259 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002260 case Instruction::Add: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002261 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
Sanjay Patel00a324e2016-08-03 22:08:44 +00002262 const APInt *BOC;
2263 if (match(BOp1, m_APInt(BOC))) {
2264 if (BO->hasOneUse()) {
2265 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002266 return new ICmpInst(Pred, BOp0, SubC);
Sanjay Patel00a324e2016-08-03 22:08:44 +00002267 }
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002268 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002269 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2270 // efficiently invertible, or if the add has just this one use.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002271 if (Value *NegVal = dyn_castNegVal(BOp1))
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002272 return new ICmpInst(Pred, BOp0, NegVal);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002273 if (Value *NegVal = dyn_castNegVal(BOp0))
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002274 return new ICmpInst(Pred, NegVal, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002275 if (BO->hasOneUse()) {
2276 Value *Neg = Builder->CreateNeg(BOp1);
2277 Neg->takeName(BO);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002278 return new ICmpInst(Pred, BOp0, Neg);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002279 }
2280 }
2281 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002282 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002283 case Instruction::Xor:
2284 if (BO->hasOneUse()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002285 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002286 // For the xor case, we can xor two constants together, eliminating
2287 // the explicit xor.
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002288 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
2289 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002290 // Replace ((xor A, B) != 0) with (A != B)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002291 return new ICmpInst(Pred, BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002292 }
2293 }
2294 break;
2295 case Instruction::Sub:
2296 if (BO->hasOneUse()) {
Sanjay Patel9d591d12016-08-04 15:19:25 +00002297 const APInt *BOC;
2298 if (match(BOp0, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002299 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
Sanjay Patel9d591d12016-08-04 15:19:25 +00002300 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002301 return new ICmpInst(Pred, BOp1, SubC);
2302 } else if (*C == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002303 // Replace ((sub A, B) != 0) with (A != B)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002304 return new ICmpInst(Pred, BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002305 }
2306 }
2307 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002308 case Instruction::Or: {
2309 const APInt *BOC;
2310 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002311 // Comparing if all bits outside of a constant mask are set?
2312 // Replace (X | C) == -1 with (X & ~C) == ~C.
2313 // This removes the -1 constant.
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002314 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2315 Value *And = Builder->CreateAnd(BOp0, NotBOC);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002316 return new ICmpInst(Pred, And, NotBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002317 }
2318 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002319 }
Sanjay Pateld938e882016-08-04 20:05:02 +00002320 case Instruction::And: {
2321 const APInt *BOC;
2322 if (match(BOp1, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002323 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002324 if (C == BOC && C->isPowerOf2())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002325 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
Sanjay Patelab50a932016-08-02 22:38:33 +00002326 BO, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002327
2328 // Don't perform the following transforms if the AND has multiple uses
2329 if (!BO->hasOneUse())
2330 break;
2331
2332 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Sanjay Pateld938e882016-08-04 20:05:02 +00002333 if (BOC->isSignBit()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002334 Constant *Zero = Constant::getNullValue(BOp0->getType());
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002335 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
2336 return new ICmpInst(NewPred, BOp0, Zero);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002337 }
2338
2339 // ((X & ~7) == 0) --> X < 8
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002340 if (*C == 0 && (~(*BOC) + 1).isPowerOf2()) {
Sanjay Pateld938e882016-08-04 20:05:02 +00002341 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1));
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002342 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
2343 return new ICmpInst(NewPred, BOp0, NegBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002344 }
2345 }
2346 break;
Sanjay Pateld938e882016-08-04 20:05:02 +00002347 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002348 case Instruction::Mul:
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002349 if (*C == 0 && BO->hasNoSignedWrap()) {
Sanjay Patel3bade132016-08-04 22:19:27 +00002350 const APInt *BOC;
2351 if (match(BOp1, m_APInt(BOC)) && *BOC != 0) {
2352 // The trivial case (mul X, 0) is handled by InstSimplify.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002353 // General case : (mul X, C) != 0 iff X != 0
2354 // (mul X, C) == 0 iff X == 0
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002355 return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002356 }
2357 }
2358 break;
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002359 case Instruction::UDiv:
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002360 if (*C == 0) {
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002361 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002362 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
2363 return new ICmpInst(NewPred, BOp1, BOp0);
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002364 }
2365 break;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002366 default:
2367 break;
2368 }
2369 return nullptr;
2370}
2371
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002372/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
2373Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
2374 const APInt *C) {
2375 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0));
2376 if (!II || !Cmp.isEquality())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002377 return nullptr;
2378
2379 // Handle icmp {eq|ne} <intrinsic>, intcst.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002380 switch (II->getIntrinsicID()) {
2381 case Intrinsic::bswap:
2382 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002383 Cmp.setOperand(0, II->getArgOperand(0));
2384 Cmp.setOperand(1, Builder->getInt(C->byteSwap()));
2385 return &Cmp;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002386 case Intrinsic::ctlz:
2387 case Intrinsic::cttz:
Amaury Sechet6bea6742016-08-04 05:27:20 +00002388 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002389 if (*C == C->getBitWidth()) {
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002390 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002391 Cmp.setOperand(0, II->getArgOperand(0));
2392 Cmp.setOperand(1, ConstantInt::getNullValue(II->getType()));
2393 return &Cmp;
Chris Lattner2188e402010-01-04 07:37:31 +00002394 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002395 break;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002396 case Intrinsic::ctpop: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002397 // popcount(A) == 0 -> A == 0 and likewise for !=
Amaury Sechet6bea6742016-08-04 05:27:20 +00002398 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002399 bool IsZero = *C == 0;
2400 if (IsZero || *C == C->getBitWidth()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002401 Worklist.Add(II);
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002402 Cmp.setOperand(0, II->getArgOperand(0));
2403 auto *NewOp = IsZero ? Constant::getNullValue(II->getType())
2404 : Constant::getAllOnesValue(II->getType());
2405 Cmp.setOperand(1, NewOp);
2406 return &Cmp;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002407 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002408 break;
Sanjay Patel0a3d72b2016-09-10 15:33:39 +00002409 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002410 default:
2411 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002412 }
Craig Topperf40110f2014-04-25 05:29:35 +00002413 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002414}
2415
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002416/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
2417/// far.
Sanjay Patel43395062016-07-21 18:07:40 +00002418Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002419 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00002420 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002421 Type *SrcTy = LHSCIOp->getType();
2422 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002423 Value *RHSCIOp;
2424
Jim Grosbach129c52a2011-09-30 18:09:53 +00002425 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002426 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002427 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2428 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002429 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002430 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00002431 Value *RHSCIOp = RHSC->getOperand(0);
2432 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2433 LHSCIOp->getType()->getPointerAddressSpace()) {
2434 RHSOp = RHSC->getOperand(0);
2435 // If the pointer types don't match, insert a bitcast.
2436 if (LHSCIOp->getType() != RHSOp->getType())
2437 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2438 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002439 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002440 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002441 }
Chris Lattner2188e402010-01-04 07:37:31 +00002442
2443 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002444 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002445 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002446
Chris Lattner2188e402010-01-04 07:37:31 +00002447 // The code below only handles extension cast instructions, so far.
2448 // Enforce this.
2449 if (LHSCI->getOpcode() != Instruction::ZExt &&
2450 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002451 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002452
2453 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002454 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00002455
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002456 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002457 // Not an extension from the same type?
2458 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002459 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002460 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002461
Chris Lattner2188e402010-01-04 07:37:31 +00002462 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2463 // and the other is a zext), then we can't handle this.
2464 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002465 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002466
2467 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002468 if (ICmp.isEquality())
2469 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002470
2471 // A signed comparison of sign extended values simplifies into a
2472 // signed comparison.
2473 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002474 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002475
2476 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002477 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002478 }
2479
Sanjay Patel4c204232016-06-04 20:39:22 +00002480 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002481 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
2482 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00002483 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002484
2485 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002486 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002487 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002488 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002489
2490 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002491 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00002492 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002493 if (ICmp.isEquality())
2494 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002495
2496 // A signed comparison of sign extended values simplifies into a
2497 // signed comparison.
2498 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002499 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002500
2501 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002502 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002503 }
2504
Sanjay Patel6a333c32016-06-06 16:56:57 +00002505 // The re-extended constant changed, partly changed (in the case of a vector),
2506 // or could not be determined to be equal (in the case of a constant
2507 // expression), so the constant cannot be represented in the shorter type.
2508 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002509 // All the cases that fold to true or false will have already been handled
2510 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002511
Sanjay Patel6a333c32016-06-06 16:56:57 +00002512 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00002513 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002514
2515 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2516 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002517
2518 // We're performing an unsigned comp with a sign extended value.
2519 // This is true if the input is >= 0. [aka >s -1]
2520 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002521 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002522
2523 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002524 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
2525 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002526
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002527 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002528 return BinaryOperator::CreateNot(Result);
2529}
2530
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002531/// The caller has matched a pattern of the form:
Chris Lattneree61c1d2010-12-19 17:52:50 +00002532/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002533/// If this is of the form:
2534/// sum = a + b
2535/// if (sum+128 >u 255)
2536/// Then replace it with llvm.sadd.with.overflow.i8.
2537///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002538static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2539 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002540 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002541 // The transformation we're trying to do here is to transform this into an
2542 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2543 // with a narrower add, and discard the add-with-constant that is part of the
2544 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002545
Chris Lattnerf29562d2010-12-19 17:59:02 +00002546 // In order to eliminate the add-with-constant, the compare can be its only
2547 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002548 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002549 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002550
Chris Lattnerc56c8452010-12-19 18:22:06 +00002551 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002552 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002553 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002554 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002555
Chris Lattnerc56c8452010-12-19 18:22:06 +00002556 // The width of the new add formed is 1 more than the bias.
2557 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002558
Chris Lattnerc56c8452010-12-19 18:22:06 +00002559 // Check to see that CI1 is an all-ones value with NewWidth bits.
2560 if (CI1->getBitWidth() == NewWidth ||
2561 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002562 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002563
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002564 // This is only really a signed overflow check if the inputs have been
2565 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2566 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2567 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002568 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2569 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002570 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002571
Jim Grosbach129c52a2011-09-30 18:09:53 +00002572 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002573 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2574 // and truncates that discard the high bits of the add. Verify that this is
2575 // the case.
2576 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002577 for (User *U : OrigAdd->users()) {
2578 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002579
Chris Lattnerc56c8452010-12-19 18:22:06 +00002580 // Only accept truncates for now. We would really like a nice recursive
2581 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2582 // chain to see which bits of a value are actually demanded. If the
2583 // original add had another add which was then immediately truncated, we
2584 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002585 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002586 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2587 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002588 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002589
Chris Lattneree61c1d2010-12-19 17:52:50 +00002590 // If the pattern matches, truncate the inputs to the narrower type and
2591 // use the sadd_with_overflow intrinsic to efficiently compute both the
2592 // result and the overflow bit.
Jay Foadb804a2b2011-07-12 14:06:48 +00002593 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002594 Value *F = Intrinsic::getDeclaration(I.getModule(),
2595 Intrinsic::sadd_with_overflow, NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002596
Chris Lattnerce2995a2010-12-19 18:38:44 +00002597 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002598
Chris Lattner79874562010-12-19 18:35:09 +00002599 // Put the new code above the original add, in case there are any uses of the
2600 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002601 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002602
Chris Lattner79874562010-12-19 18:35:09 +00002603 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2604 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002605 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002606 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2607 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002608
Chris Lattneree61c1d2010-12-19 17:52:50 +00002609 // The inner add was the result of the narrow add, zero extended to the
2610 // wider type. Replace it with the result computed by the intrinsic.
Sanjay Patel4b198802016-02-01 22:23:39 +00002611 IC.replaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002612
Chris Lattner79874562010-12-19 18:35:09 +00002613 // The original icmp gets replaced with the overflow value.
2614 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002615}
Chris Lattner2188e402010-01-04 07:37:31 +00002616
Sanjoy Dasb0984472015-04-08 04:27:22 +00002617bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2618 Value *RHS, Instruction &OrigI,
2619 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002620 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2621 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002622
2623 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2624 Result = OpResult;
2625 Overflow = OverflowVal;
2626 if (ReuseName)
2627 Result->takeName(&OrigI);
2628 return true;
2629 };
2630
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002631 // If the overflow check was an add followed by a compare, the insertion point
2632 // may be pointing to the compare. We want to insert the new instructions
2633 // before the add in case there are uses of the add between the add and the
2634 // compare.
2635 Builder->SetInsertPoint(&OrigI);
2636
Sanjoy Dasb0984472015-04-08 04:27:22 +00002637 switch (OCF) {
2638 case OCF_INVALID:
2639 llvm_unreachable("bad overflow check kind!");
2640
2641 case OCF_UNSIGNED_ADD: {
2642 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2643 if (OR == OverflowResult::NeverOverflows)
2644 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2645 true);
2646
2647 if (OR == OverflowResult::AlwaysOverflows)
2648 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002649
2650 // Fall through uadd into sadd
2651 LLVM_FALLTHROUGH;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002652 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00002653 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002654 // X + 0 -> {X, false}
2655 if (match(RHS, m_Zero()))
2656 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002657
2658 // We can strength reduce this signed add into a regular add if we can prove
2659 // that it will never overflow.
2660 if (OCF == OCF_SIGNED_ADD)
2661 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2662 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2663 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002664 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002665 }
2666
2667 case OCF_UNSIGNED_SUB:
2668 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002669 // X - 0 -> {X, false}
2670 if (match(RHS, m_Zero()))
2671 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002672
2673 if (OCF == OCF_SIGNED_SUB) {
2674 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2675 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2676 true);
2677 } else {
2678 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2679 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2680 true);
2681 }
2682 break;
2683 }
2684
2685 case OCF_UNSIGNED_MUL: {
2686 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2687 if (OR == OverflowResult::NeverOverflows)
2688 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2689 true);
2690 if (OR == OverflowResult::AlwaysOverflows)
2691 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002692 LLVM_FALLTHROUGH;
2693 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00002694 case OCF_SIGNED_MUL:
2695 // X * undef -> undef
2696 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002697 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002698
David Majnemer27e89ba2015-05-21 23:04:21 +00002699 // X * 0 -> {0, false}
2700 if (match(RHS, m_Zero()))
2701 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002702
David Majnemer27e89ba2015-05-21 23:04:21 +00002703 // X * 1 -> {X, false}
2704 if (match(RHS, m_One()))
2705 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002706
2707 if (OCF == OCF_SIGNED_MUL)
2708 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2709 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2710 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002711 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002712 }
2713
2714 return false;
2715}
2716
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002717/// \brief Recognize and process idiom involving test for multiplication
2718/// overflow.
2719///
2720/// The caller has matched a pattern of the form:
2721/// I = cmp u (mul(zext A, zext B), V
2722/// The function checks if this is a test for overflow and if so replaces
2723/// multiplication with call to 'mul.with.overflow' intrinsic.
2724///
2725/// \param I Compare instruction.
2726/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2727/// the compare instruction. Must be of integer type.
2728/// \param OtherVal The other argument of compare instruction.
2729/// \returns Instruction which must replace the compare instruction, NULL if no
2730/// replacement required.
2731static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2732 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002733 // Don't bother doing this transformation for pointers, don't do it for
2734 // vectors.
2735 if (!isa<IntegerType>(MulVal->getType()))
2736 return nullptr;
2737
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002738 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2739 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002740 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2741 if (!MulInstr)
2742 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002743 assert(MulInstr->getOpcode() == Instruction::Mul);
2744
David Majnemer634ca232014-11-01 23:46:05 +00002745 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2746 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002747 assert(LHS->getOpcode() == Instruction::ZExt);
2748 assert(RHS->getOpcode() == Instruction::ZExt);
2749 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2750
2751 // Calculate type and width of the result produced by mul.with.overflow.
2752 Type *TyA = A->getType(), *TyB = B->getType();
2753 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2754 WidthB = TyB->getPrimitiveSizeInBits();
2755 unsigned MulWidth;
2756 Type *MulType;
2757 if (WidthB > WidthA) {
2758 MulWidth = WidthB;
2759 MulType = TyB;
2760 } else {
2761 MulWidth = WidthA;
2762 MulType = TyA;
2763 }
2764
2765 // In order to replace the original mul with a narrower mul.with.overflow,
2766 // all uses must ignore upper bits of the product. The number of used low
2767 // bits must be not greater than the width of mul.with.overflow.
2768 if (MulVal->hasNUsesOrMore(2))
2769 for (User *U : MulVal->users()) {
2770 if (U == &I)
2771 continue;
2772 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2773 // Check if truncation ignores bits above MulWidth.
2774 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2775 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002776 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002777 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2778 // Check if AND ignores bits above MulWidth.
2779 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002780 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002781 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2782 const APInt &CVal = CI->getValue();
2783 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002784 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002785 }
2786 } else {
2787 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002788 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002789 }
2790 }
2791
2792 // Recognize patterns
2793 switch (I.getPredicate()) {
2794 case ICmpInst::ICMP_EQ:
2795 case ICmpInst::ICMP_NE:
2796 // Recognize pattern:
2797 // mulval = mul(zext A, zext B)
2798 // cmp eq/neq mulval, zext trunc mulval
2799 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2800 if (Zext->hasOneUse()) {
2801 Value *ZextArg = Zext->getOperand(0);
2802 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2803 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2804 break; //Recognized
2805 }
2806
2807 // Recognize pattern:
2808 // mulval = mul(zext A, zext B)
2809 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2810 ConstantInt *CI;
2811 Value *ValToMask;
2812 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2813 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002814 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002815 const APInt &CVal = CI->getValue() + 1;
2816 if (CVal.isPowerOf2()) {
2817 unsigned MaskWidth = CVal.logBase2();
2818 if (MaskWidth == MulWidth)
2819 break; // Recognized
2820 }
2821 }
Craig Topperf40110f2014-04-25 05:29:35 +00002822 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002823
2824 case ICmpInst::ICMP_UGT:
2825 // Recognize pattern:
2826 // mulval = mul(zext A, zext B)
2827 // cmp ugt mulval, max
2828 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2829 APInt MaxVal = APInt::getMaxValue(MulWidth);
2830 MaxVal = MaxVal.zext(CI->getBitWidth());
2831 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 case ICmpInst::ICMP_UGE:
2837 // Recognize pattern:
2838 // mulval = mul(zext A, zext B)
2839 // cmp uge mulval, max+1
2840 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2841 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2842 if (MaxVal.eq(CI->getValue()))
2843 break; // Recognized
2844 }
Craig Topperf40110f2014-04-25 05:29:35 +00002845 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002846
2847 case ICmpInst::ICMP_ULE:
2848 // Recognize pattern:
2849 // mulval = mul(zext A, zext B)
2850 // cmp ule mulval, max
2851 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2852 APInt MaxVal = APInt::getMaxValue(MulWidth);
2853 MaxVal = MaxVal.zext(CI->getBitWidth());
2854 if (MaxVal.eq(CI->getValue()))
2855 break; // Recognized
2856 }
Craig Topperf40110f2014-04-25 05:29:35 +00002857 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002858
2859 case ICmpInst::ICMP_ULT:
2860 // Recognize pattern:
2861 // mulval = mul(zext A, zext B)
2862 // cmp ule mulval, max + 1
2863 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002864 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002865 if (MaxVal.eq(CI->getValue()))
2866 break; // Recognized
2867 }
Craig Topperf40110f2014-04-25 05:29:35 +00002868 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002869
2870 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002871 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002872 }
2873
2874 InstCombiner::BuilderTy *Builder = IC.Builder;
2875 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002876
2877 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2878 Value *MulA = A, *MulB = B;
2879 if (WidthA < MulWidth)
2880 MulA = Builder->CreateZExt(A, MulType);
2881 if (WidthB < MulWidth)
2882 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002883 Value *F = Intrinsic::getDeclaration(I.getModule(),
2884 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002885 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002886 IC.Worklist.Add(MulInstr);
2887
2888 // If there are uses of mul result other than the comparison, we know that
2889 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002890 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002891 if (MulVal->hasNUsesOrMore(2)) {
2892 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2893 for (User *U : MulVal->users()) {
2894 if (U == &I || U == OtherVal)
2895 continue;
2896 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2897 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00002898 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002899 else
2900 TI->setOperand(0, Mul);
2901 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2902 assert(BO->getOpcode() == Instruction::And);
2903 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2904 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2905 APInt ShortMask = CI->getValue().trunc(MulWidth);
2906 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2907 Instruction *Zext =
2908 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2909 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00002910 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002911 } else {
2912 llvm_unreachable("Unexpected Binary operation");
2913 }
2914 IC.Worklist.Add(cast<Instruction>(U));
2915 }
2916 }
2917 if (isa<Instruction>(OtherVal))
2918 IC.Worklist.Add(cast<Instruction>(OtherVal));
2919
2920 // The original icmp gets replaced with the overflow value, maybe inverted
2921 // depending on predicate.
2922 bool Inverse = false;
2923 switch (I.getPredicate()) {
2924 case ICmpInst::ICMP_NE:
2925 break;
2926 case ICmpInst::ICMP_EQ:
2927 Inverse = true;
2928 break;
2929 case ICmpInst::ICMP_UGT:
2930 case ICmpInst::ICMP_UGE:
2931 if (I.getOperand(0) == MulVal)
2932 break;
2933 Inverse = true;
2934 break;
2935 case ICmpInst::ICMP_ULT:
2936 case ICmpInst::ICMP_ULE:
2937 if (I.getOperand(1) == MulVal)
2938 break;
2939 Inverse = true;
2940 break;
2941 default:
2942 llvm_unreachable("Unexpected predicate");
2943 }
2944 if (Inverse) {
2945 Value *Res = Builder->CreateExtractValue(Call, 1);
2946 return BinaryOperator::CreateNot(Res);
2947 }
2948
2949 return ExtractValueInst::Create(Call, 1);
2950}
2951
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002952/// When performing a comparison against a constant, it is possible that not all
2953/// the bits in the LHS are demanded. This helper method computes the mask that
2954/// IS demanded.
Owen Andersond490c2d2011-01-11 00:36:45 +00002955static APInt DemandedBitsLHSMask(ICmpInst &I,
2956 unsigned BitWidth, bool isSignCheck) {
2957 if (isSignCheck)
2958 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002959
Owen Andersond490c2d2011-01-11 00:36:45 +00002960 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2961 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00002962 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00002963
Owen Andersond490c2d2011-01-11 00:36:45 +00002964 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00002965 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00002966 // correspond to the trailing ones of the comparand. The value of these
2967 // bits doesn't impact the outcome of the comparison, because any value
2968 // greater than the RHS must differ in a bit higher than these due to carry.
2969 case ICmpInst::ICMP_UGT: {
2970 unsigned trailingOnes = RHS.countTrailingOnes();
2971 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2972 return ~lowBitsSet;
2973 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002974
Owen Andersond490c2d2011-01-11 00:36:45 +00002975 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2976 // Any value less than the RHS must differ in a higher bit because of carries.
2977 case ICmpInst::ICMP_ULT: {
2978 unsigned trailingZeros = RHS.countTrailingZeros();
2979 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2980 return ~lowBitsSet;
2981 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002982
Owen Andersond490c2d2011-01-11 00:36:45 +00002983 default:
2984 return APInt::getAllOnesValue(BitWidth);
2985 }
Owen Andersond490c2d2011-01-11 00:36:45 +00002986}
Chris Lattner2188e402010-01-04 07:37:31 +00002987
Quentin Colombet5ab55552013-09-09 20:56:48 +00002988/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2989/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00002990/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00002991/// as subtract operands and their positions in those instructions.
2992/// The rational is that several architectures use the same instruction for
2993/// both subtract and cmp, thus it is better if the order of those operands
2994/// match.
2995/// \return true if Op0 and Op1 should be swapped.
2996static bool swapMayExposeCSEOpportunities(const Value * Op0,
2997 const Value * Op1) {
2998 // Filter out pointer value as those cannot appears directly in subtract.
2999 // FIXME: we may want to go through inttoptrs or bitcasts.
3000 if (Op0->getType()->isPointerTy())
3001 return false;
3002 // Count every uses of both Op0 and Op1 in a subtract.
3003 // Each time Op0 is the first operand, count -1: swapping is bad, the
3004 // subtract has already the same layout as the compare.
3005 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00003006 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003007 // At the end, if the benefit is greater than 0, Op0 should come second to
3008 // expose more CSE opportunities.
3009 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003010 for (const User *U : Op0->users()) {
3011 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003012 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
3013 continue;
3014 // If Op0 is the first argument, this is not beneficial to swap the
3015 // arguments.
3016 int LocalSwapBenefits = -1;
3017 unsigned Op1Idx = 1;
3018 if (BinOp->getOperand(Op1Idx) == Op0) {
3019 Op1Idx = 0;
3020 LocalSwapBenefits = 1;
3021 }
3022 if (BinOp->getOperand(Op1Idx) != Op1)
3023 continue;
3024 GlobalSwapBenefits += LocalSwapBenefits;
3025 }
3026 return GlobalSwapBenefits > 0;
3027}
3028
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003029/// \brief Check that one use is in the same block as the definition and all
Sanjay Patel53523312016-09-12 14:25:46 +00003030/// other uses are in blocks dominated by a given block.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003031///
3032/// \param DI Definition
3033/// \param UI Use
3034/// \param DB Block that must dominate all uses of \p DI outside
3035/// the parent block
3036/// \return true when \p UI is the only use of \p DI in the parent block
3037/// and all other uses of \p DI are in blocks dominated by \p DB.
3038///
3039bool InstCombiner::dominatesAllUses(const Instruction *DI,
3040 const Instruction *UI,
3041 const BasicBlock *DB) const {
3042 assert(DI && UI && "Instruction not defined\n");
Sanjay Patel53523312016-09-12 14:25:46 +00003043 // Ignore incomplete definitions.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003044 if (!DI->getParent())
3045 return false;
Sanjay Patel53523312016-09-12 14:25:46 +00003046 // DI and UI must be in the same block.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003047 if (DI->getParent() != UI->getParent())
3048 return false;
Sanjay Patel53523312016-09-12 14:25:46 +00003049 // Protect from self-referencing blocks.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003050 if (DI->getParent() == DB)
3051 return false;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003052 for (const User *U : DI->users()) {
3053 auto *Usr = cast<Instruction>(U);
Justin Bogner99798402016-08-05 01:06:44 +00003054 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003055 return false;
3056 }
3057 return true;
3058}
3059
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003060/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003061static bool isChainSelectCmpBranch(const SelectInst *SI) {
3062 const BasicBlock *BB = SI->getParent();
3063 if (!BB)
3064 return false;
3065 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3066 if (!BI || BI->getNumSuccessors() != 2)
3067 return false;
3068 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3069 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3070 return false;
3071 return true;
3072}
3073
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003074/// \brief True when a select result is replaced by one of its operands
3075/// in select-icmp sequence. This will eventually result in the elimination
3076/// of the select.
3077///
3078/// \param SI Select instruction
3079/// \param Icmp Compare instruction
3080/// \param SIOpd Operand that replaces the select
3081///
3082/// Notes:
3083/// - The replacement is global and requires dominator information
3084/// - The caller is responsible for the actual replacement
3085///
3086/// Example:
3087///
3088/// entry:
3089/// %4 = select i1 %3, %C* %0, %C* null
3090/// %5 = icmp eq %C* %4, null
3091/// br i1 %5, label %9, label %7
3092/// ...
3093/// ; <label>:7 ; preds = %entry
3094/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3095/// ...
3096///
3097/// can be transformed to
3098///
3099/// %5 = icmp eq %C* %0, null
3100/// %6 = select i1 %3, i1 %5, i1 true
3101/// br i1 %6, label %9, label %7
3102/// ...
3103/// ; <label>:7 ; preds = %entry
3104/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3105///
3106/// Similar when the first operand of the select is a constant or/and
3107/// the compare is for not equal rather than equal.
3108///
3109/// NOTE: The function is only called when the select and compare constants
3110/// are equal, the optimization can work only for EQ predicates. This is not a
3111/// major restriction since a NE compare should be 'normalized' to an equal
3112/// compare, which usually happens in the combiner and test case
Sanjay Patel53523312016-09-12 14:25:46 +00003113/// select-cmp-br.ll checks for it.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003114bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3115 const ICmpInst *Icmp,
3116 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003117 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003118 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3119 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3120 // The check for the unique predecessor is not the best that can be
Sanjay Patel53523312016-09-12 14:25:46 +00003121 // done. But it protects efficiently against cases like when SI's
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003122 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3123 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3124 // replaced can be reached on either path. So the uniqueness check
3125 // guarantees that the path all uses of SI (outside SI's parent) are on
3126 // is disjoint from all other paths out of SI. But that information
3127 // is more expensive to compute, and the trade-off here is in favor
3128 // of compile-time.
3129 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3130 NumSel++;
3131 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3132 return true;
3133 }
3134 }
3135 return false;
3136}
3137
Sanjay Patel3151dec2016-09-12 15:24:31 +00003138/// Try to fold the comparison based on range information we can get by checking
3139/// whether bits are known to be zero or one in the inputs.
3140Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) {
3141 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3142 Type *Ty = Op0->getType();
3143
3144 // Get scalar or pointer size.
3145 unsigned BitWidth = Ty->isIntOrIntVectorTy()
3146 ? Ty->getScalarSizeInBits()
3147 : DL.getTypeSizeInBits(Ty->getScalarType());
3148
3149 if (!BitWidth)
3150 return nullptr;
3151
3152 // If this is a normal comparison, it demands all bits. If it is a sign bit
3153 // comparison, it only demands the sign bit.
3154 bool IsSignBit = false;
3155 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3156 bool UnusedBit;
3157 IsSignBit = isSignBitCheck(I.getPredicate(), CI->getValue(), UnusedBit);
3158 }
3159
3160 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3161 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3162
3163 if (SimplifyDemandedBits(I.getOperandUse(0),
3164 DemandedBitsLHSMask(I, BitWidth, IsSignBit),
3165 Op0KnownZero, Op0KnownOne, 0))
3166 return &I;
3167
3168 if (SimplifyDemandedBits(I.getOperandUse(1), APInt::getAllOnesValue(BitWidth),
3169 Op1KnownZero, Op1KnownOne, 0))
3170 return &I;
3171
3172 // Given the known and unknown bits, compute a range that the LHS could be
3173 // in. Compute the Min, Max and RHS values based on the known bits. For the
3174 // EQ and NE we use unsigned values.
3175 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3176 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3177 if (I.isSigned()) {
3178 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min,
3179 Op0Max);
3180 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min,
3181 Op1Max);
3182 } else {
3183 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min,
3184 Op0Max);
3185 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min,
3186 Op1Max);
3187 }
3188
3189 // If Min and Max are known to be the same, then SimplifyDemandedBits
3190 // figured out that the LHS is a constant. Just constant fold this now so
3191 // that code below can assume that Min != Max.
3192 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3193 return new ICmpInst(I.getPredicate(),
3194 ConstantInt::get(Op0->getType(), Op0Min), Op1);
3195 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3196 return new ICmpInst(I.getPredicate(), Op0,
3197 ConstantInt::get(Op1->getType(), Op1Min));
3198
3199 // Based on the range information we know about the LHS, see if we can
3200 // simplify this comparison. For example, (x&4) < 8 is always true.
3201 switch (I.getPredicate()) {
3202 default:
3203 llvm_unreachable("Unknown icmp opcode!");
3204 case ICmpInst::ICMP_EQ: {
3205 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
3206 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3207
3208 // If all bits are known zero except for one, then we know at most one
3209 // bit is set. If the comparison is against zero, then this is a check
3210 // to see if *that* bit is set.
3211 APInt Op0KnownZeroInverted = ~Op0KnownZero;
3212 if (~Op1KnownZero == 0) {
3213 // If the LHS is an AND with the same constant, look through it.
3214 Value *LHS = nullptr;
3215 ConstantInt *LHSC = nullptr;
3216 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3217 LHSC->getValue() != Op0KnownZeroInverted)
3218 LHS = Op0;
3219
3220 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
3221 // then turn "((1 << x)&8) == 0" into "x != 3".
3222 // or turn "((1 << x)&7) == 0" into "x > 2".
3223 Value *X = nullptr;
3224 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
3225 APInt ValToCheck = Op0KnownZeroInverted;
3226 if (ValToCheck.isPowerOf2()) {
3227 unsigned CmpVal = ValToCheck.countTrailingZeros();
3228 return new ICmpInst(ICmpInst::ICMP_NE, X,
3229 ConstantInt::get(X->getType(), CmpVal));
3230 } else if ((++ValToCheck).isPowerOf2()) {
3231 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3232 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3233 ConstantInt::get(X->getType(), CmpVal));
3234 }
3235 }
3236
3237 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
3238 // then turn "((8 >>u x)&1) == 0" into "x != 3".
3239 const APInt *CI;
3240 if (Op0KnownZeroInverted == 1 &&
3241 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
3242 return new ICmpInst(
3243 ICmpInst::ICMP_NE, X,
3244 ConstantInt::get(X->getType(), CI->countTrailingZeros()));
3245 }
3246 break;
3247 }
3248 case ICmpInst::ICMP_NE: {
3249 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
3250 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3251
3252 // If all bits are known zero except for one, then we know at most one
3253 // bit is set. If the comparison is against zero, then this is a check
3254 // to see if *that* bit is set.
3255 APInt Op0KnownZeroInverted = ~Op0KnownZero;
3256 if (~Op1KnownZero == 0) {
3257 // If the LHS is an AND with the same constant, look through it.
3258 Value *LHS = nullptr;
3259 ConstantInt *LHSC = nullptr;
3260 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3261 LHSC->getValue() != Op0KnownZeroInverted)
3262 LHS = Op0;
3263
3264 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
3265 // then turn "((1 << x)&8) != 0" into "x == 3".
3266 // or turn "((1 << x)&7) != 0" into "x < 3".
3267 Value *X = nullptr;
3268 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
3269 APInt ValToCheck = Op0KnownZeroInverted;
3270 if (ValToCheck.isPowerOf2()) {
3271 unsigned CmpVal = ValToCheck.countTrailingZeros();
3272 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3273 ConstantInt::get(X->getType(), CmpVal));
3274 } else if ((++ValToCheck).isPowerOf2()) {
3275 unsigned CmpVal = ValToCheck.countTrailingZeros();
3276 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3277 ConstantInt::get(X->getType(), CmpVal));
3278 }
3279 }
3280
3281 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
3282 // then turn "((8 >>u x)&1) != 0" into "x == 3".
3283 const APInt *CI;
3284 if (Op0KnownZeroInverted == 1 &&
3285 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
3286 return new ICmpInst(
3287 ICmpInst::ICMP_EQ, X,
3288 ConstantInt::get(X->getType(), CI->countTrailingZeros()));
3289 }
3290 break;
3291 }
3292 case ICmpInst::ICMP_ULT: {
3293 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
3294 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3295 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
3296 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3297 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3298 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3299
3300 const APInt *CmpC;
3301 if (match(Op1, m_APInt(CmpC))) {
3302 // A <u C -> A == C-1 if min(A)+1 == C
3303 if (Op1Max == Op0Min + 1) {
3304 Constant *CMinus1 = ConstantInt::get(Op0->getType(), *CmpC - 1);
3305 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, CMinus1);
3306 }
3307 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3308 if (CmpC->isMinSignedValue()) {
3309 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
3310 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
3311 }
3312 }
3313 break;
3314 }
3315 case ICmpInst::ICMP_UGT: {
3316 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
3317 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3318
3319 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
3320 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3321
3322 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3323 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3324
3325 const APInt *CmpC;
3326 if (match(Op1, m_APInt(CmpC))) {
3327 // A >u C -> A == C+1 if max(a)-1 == C
3328 if (*CmpC == Op0Max - 1)
3329 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3330 ConstantInt::get(Op1->getType(), *CmpC + 1));
3331
3332 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3333 if (CmpC->isMaxSignedValue())
3334 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3335 Constant::getNullValue(Op0->getType()));
3336 }
3337 break;
3338 }
3339 case ICmpInst::ICMP_SLT:
3340 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
3341 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3342 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
3343 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3344 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3345 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3346 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3347 if (Op1Max == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
3348 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3349 Builder->getInt(CI->getValue() - 1));
3350 }
3351 break;
3352 case ICmpInst::ICMP_SGT:
3353 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
3354 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3355 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
3356 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3357
3358 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3359 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3360 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3361 if (Op1Min == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
3362 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
3363 Builder->getInt(CI->getValue() + 1));
3364 }
3365 break;
3366 case ICmpInst::ICMP_SGE:
3367 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3368 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
3369 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3370 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
3371 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3372 break;
3373 case ICmpInst::ICMP_SLE:
3374 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3375 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
3376 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3377 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
3378 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3379 break;
3380 case ICmpInst::ICMP_UGE:
3381 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3382 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
3383 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3384 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
3385 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3386 break;
3387 case ICmpInst::ICMP_ULE:
3388 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3389 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
3390 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
3391 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
3392 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
3393 break;
3394 }
3395
3396 // Turn a signed comparison into an unsigned one if both operands are known to
3397 // have the same sign.
3398 if (I.isSigned() &&
3399 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3400 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3401 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3402
3403 return nullptr;
3404}
3405
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003406/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3407/// it into the appropriate icmp lt or icmp gt instruction. This transform
3408/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00003409static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
3410 ICmpInst::Predicate Pred = I.getPredicate();
3411 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
3412 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
3413 return nullptr;
3414
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003415 Value *Op0 = I.getOperand(0);
3416 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003417 auto *Op1C = dyn_cast<Constant>(Op1);
3418 if (!Op1C)
3419 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003420
Sanjay Patele9b2c322016-05-17 00:57:57 +00003421 // Check if the constant operand can be safely incremented/decremented without
3422 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
3423 // the edge cases for us, so we just assert on them. For vectors, we must
3424 // handle the edge cases.
3425 Type *Op1Type = Op1->getType();
3426 bool IsSigned = I.isSigned();
3427 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00003428 auto *CI = dyn_cast<ConstantInt>(Op1C);
3429 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00003430 // A <= MAX -> TRUE ; A >= MIN -> TRUE
3431 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
3432 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00003433 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00003434 // are for scalar, we could remove the min/max checks. However, to do that,
3435 // we would have to use insertelement/shufflevector to replace edge values.
3436 unsigned NumElts = Op1Type->getVectorNumElements();
3437 for (unsigned i = 0; i != NumElts; ++i) {
3438 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00003439 if (!Elt)
3440 return nullptr;
3441
Sanjay Patele9b2c322016-05-17 00:57:57 +00003442 if (isa<UndefValue>(Elt))
3443 continue;
3444 // Bail out if we can't determine if this constant is min/max or if we
3445 // know that this constant is min/max.
3446 auto *CI = dyn_cast<ConstantInt>(Elt);
3447 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
3448 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003449 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00003450 } else {
3451 // ConstantExpr?
3452 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003453 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003454
Sanjay Patele9b2c322016-05-17 00:57:57 +00003455 // Increment or decrement the constant and set the new comparison predicate:
3456 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00003457 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003458 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
3459 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
3460 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003461}
3462
Chris Lattner2188e402010-01-04 07:37:31 +00003463Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3464 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003465 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003466 unsigned Op0Cplxity = getComplexity(Op0);
3467 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003468
Chris Lattner2188e402010-01-04 07:37:31 +00003469 /// Orders the operands of the compare so that they are listed from most
3470 /// complex to least complex. This puts constants before unary operators,
3471 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003472 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00003473 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003474 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003475 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003476 Changed = true;
3477 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003478
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003479 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +00003480 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003481 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003482
Pete Cooperbc5c5242011-12-01 03:58:40 +00003483 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003484 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00003485 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003486 Value *Cond, *SelectTrue, *SelectFalse;
3487 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003488 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003489 if (Value *V = dyn_castNegVal(SelectTrue)) {
3490 if (V == SelectFalse)
3491 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3492 }
3493 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3494 if (V == SelectTrue)
3495 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003496 }
3497 }
3498 }
3499
Chris Lattner229907c2011-07-18 04:54:35 +00003500 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003501
3502 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00003503 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003504 switch (I.getPredicate()) {
3505 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003506 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3507 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003508 return BinaryOperator::CreateNot(Xor);
3509 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003510 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00003511 return BinaryOperator::CreateXor(Op0, Op1);
3512
3513 case ICmpInst::ICMP_UGT:
3514 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003515 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003516 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3517 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003518 return BinaryOperator::CreateAnd(Not, Op1);
3519 }
3520 case ICmpInst::ICMP_SGT:
3521 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003522 LLVM_FALLTHROUGH;
Chris Lattner2188e402010-01-04 07:37:31 +00003523 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003524 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003525 return BinaryOperator::CreateAnd(Not, Op0);
3526 }
3527 case ICmpInst::ICMP_UGE:
3528 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003529 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003530 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3531 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003532 return BinaryOperator::CreateOr(Not, Op1);
3533 }
3534 case ICmpInst::ICMP_SGE:
3535 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003536 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003537 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3538 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003539 return BinaryOperator::CreateOr(Not, Op0);
3540 }
3541 }
3542 }
3543
Sanjay Patele9b2c322016-05-17 00:57:57 +00003544 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003545 return NewICmp;
3546
Chris Lattner2188e402010-01-04 07:37:31 +00003547 // See if we are doing a comparison with a constant.
3548 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00003549 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003550
Owen Anderson1294ea72010-12-17 18:08:00 +00003551 // Match the following pattern, which is a common idiom when writing
3552 // overflow-safe integer arithmetic function. The source performs an
3553 // addition in wider type, and explicitly checks for overflow using
3554 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
3555 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00003556 //
3557 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00003558 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00003559 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003560 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00003561 // sum = a + b
3562 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00003563 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00003564 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00003565 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00003566 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00003567 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00003568 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00003569 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003570
Philip Reamesec8a8b52016-03-09 21:05:07 +00003571 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3572 if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3573 if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3574 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3575 if (SPR.Flavor == SPF_SMIN) {
Philip Reames8f12eba2016-03-09 21:31:47 +00003576 if (isKnownPositive(A, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003577 return new ICmpInst(I.getPredicate(), B, CI);
Philip Reames8f12eba2016-03-09 21:31:47 +00003578 if (isKnownPositive(B, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003579 return new ICmpInst(I.getPredicate(), A, CI);
3580 }
3581 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00003582
Philip Reamesec8a8b52016-03-09 21:05:07 +00003583
David Majnemera0afb552015-01-14 19:26:56 +00003584 // The following transforms are only 'worth it' if the only user of the
3585 // subtraction is the icmp.
3586 if (Op0->hasOneUse()) {
3587 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3588 if (I.isEquality() && CI->isZero() &&
3589 match(Op0, m_Sub(m_Value(A), m_Value(B))))
3590 return new ICmpInst(I.getPredicate(), A, B);
3591
3592 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3593 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3594 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3595 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3596
3597 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3598 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3599 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3600 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3601
3602 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3603 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3604 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3605 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3606
3607 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3608 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3609 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3610 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00003611 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003612
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003613 if (I.isEquality()) {
3614 ConstantInt *CI2;
3615 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3616 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00003617 // (icmp eq/ne (ashr/lshr const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003618 if (Instruction *Inst = foldICmpCstShrConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003619 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003620 }
David Majnemer59939ac2014-10-19 08:23:08 +00003621 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3622 // (icmp eq/ne (shl const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003623 if (Instruction *Inst = foldICmpCstShlConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003624 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00003625 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003626 }
3627
Balaram Makam569eaec2016-05-04 21:32:14 +00003628 // Canonicalize icmp instructions based on dominating conditions.
3629 BasicBlock *Parent = I.getParent();
3630 BasicBlock *Dom = Parent->getSinglePredecessor();
3631 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
3632 ICmpInst::Predicate Pred;
3633 BasicBlock *TrueBB, *FalseBB;
3634 ConstantInt *CI2;
3635 if (BI && match(BI, m_Br(m_ICmp(Pred, m_Specific(Op0), m_ConstantInt(CI2)),
3636 TrueBB, FalseBB)) &&
3637 TrueBB != FalseBB) {
3638 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(I.getPredicate(),
3639 CI->getValue());
3640 ConstantRange DominatingCR =
3641 (Parent == TrueBB)
3642 ? ConstantRange::makeExactICmpRegion(Pred, CI2->getValue())
3643 : ConstantRange::makeExactICmpRegion(
3644 CmpInst::getInversePredicate(Pred), CI2->getValue());
3645 ConstantRange Intersection = DominatingCR.intersectWith(CR);
3646 ConstantRange Difference = DominatingCR.difference(CR);
3647 if (Intersection.isEmptySet())
3648 return replaceInstUsesWith(I, Builder->getFalse());
3649 if (Difference.isEmptySet())
3650 return replaceInstUsesWith(I, Builder->getTrue());
Sanjay Patel3151dec2016-09-12 15:24:31 +00003651
3652 // If this is a normal comparison, it demands all bits. If it is a sign
3653 // bit comparison, it only demands the sign bit.
3654 bool UnusedBit;
3655 bool IsSignBit =
3656 isSignBitCheck(I.getPredicate(), CI->getValue(), UnusedBit);
3657
Balaram Makam569eaec2016-05-04 21:32:14 +00003658 // Canonicalizing a sign bit comparison that gets used in a branch,
3659 // pessimizes codegen by generating branch on zero instruction instead
3660 // of a test and branch. So we avoid canonicalizing in such situations
3661 // because test and branch instruction has better branch displacement
3662 // than compare and branch instruction.
Sanjay Patel3151dec2016-09-12 15:24:31 +00003663 if (!isBranchOnSignBitCheck(I, IsSignBit) && !I.isEquality()) {
Balaram Makam569eaec2016-05-04 21:32:14 +00003664 if (auto *AI = Intersection.getSingleElement())
3665 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Builder->getInt(*AI));
3666 if (auto *AD = Difference.getSingleElement())
3667 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Builder->getInt(*AD));
3668 }
3669 }
Chris Lattner2188e402010-01-04 07:37:31 +00003670 }
3671
Sanjay Patel3151dec2016-09-12 15:24:31 +00003672 if (Instruction *Res = foldICmpUsingKnownBits(I))
3673 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00003674
3675 // Test if the ICmpInst instruction is used exclusively by a select as
3676 // part of a minimum or maximum operation. If so, refrain from doing
3677 // any other folding. This helps out other analyses which understand
3678 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3679 // and CodeGen. And in this case, at least one of the comparison
3680 // operands has at least one user besides the compare (the select),
3681 // which would often largely negate the benefit of folding anyway.
3682 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003683 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003684 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3685 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003686 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003687
Sanjay Patelf58f68c2016-09-10 15:03:44 +00003688 if (Instruction *Res = foldICmpInstWithConstant(I))
Sanjay Patel1271bf92016-07-23 13:06:49 +00003689 return Res;
3690
Chris Lattner2188e402010-01-04 07:37:31 +00003691 // Handle icmp with constant (but not simple integer constant) RHS
3692 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3693 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3694 switch (LHSI->getOpcode()) {
3695 case Instruction::GetElementPtr:
3696 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3697 if (RHSC->isNullValue() &&
3698 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3699 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3700 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3701 break;
3702 case Instruction::PHI:
3703 // Only fold icmp into the PHI if the phi and icmp are in the same
3704 // block. If in the same block, we're encouraging jump threading. If
3705 // not, we are just pessimizing the code by making an i1 phi.
3706 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003707 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003708 return NV;
3709 break;
3710 case Instruction::Select: {
3711 // If either operand of the select is a constant, we can fold the
3712 // comparison into the select arms, which will cause one to be
3713 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003714 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003715 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003716 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003717 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003718 CI = dyn_cast<ConstantInt>(Op1);
3719 }
3720 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003721 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003722 CI = dyn_cast<ConstantInt>(Op2);
3723 }
Chris Lattner2188e402010-01-04 07:37:31 +00003724
3725 // We only want to perform this transformation if it will not lead to
3726 // additional code. This is true if either both sides of the select
3727 // fold to a constant (in which case the icmp is replaced with a select
3728 // which will usually simplify) or this is the only user of the
3729 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003730 // select+icmp) or all uses of the select can be replaced based on
3731 // dominance information ("Global cases").
3732 bool Transform = false;
3733 if (Op1 && Op2)
3734 Transform = true;
3735 else if (Op1 || Op2) {
3736 // Local case
3737 if (LHSI->hasOneUse())
3738 Transform = true;
3739 // Global cases
3740 else if (CI && !CI->isZero())
3741 // When Op1 is constant try replacing select with second operand.
3742 // Otherwise Op2 is constant and try replacing select with first
3743 // operand.
3744 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3745 Op1 ? 2 : 1);
3746 }
3747 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003748 if (!Op1)
3749 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3750 RHSC, I.getName());
3751 if (!Op2)
3752 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3753 RHSC, I.getName());
3754 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3755 }
3756 break;
3757 }
Chris Lattner2188e402010-01-04 07:37:31 +00003758 case Instruction::IntToPtr:
3759 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003760 if (RHSC->isNullValue() &&
3761 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003762 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3763 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3764 break;
3765
3766 case Instruction::Load:
3767 // Try to optimize things like "A[i] > 4" to index computations.
3768 if (GetElementPtrInst *GEP =
3769 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3770 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3771 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3772 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00003773 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Chris Lattner2188e402010-01-04 07:37:31 +00003774 return Res;
3775 }
3776 break;
3777 }
3778 }
3779
3780 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3781 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00003782 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner2188e402010-01-04 07:37:31 +00003783 return NI;
3784 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003785 if (Instruction *NI = foldGEPICmp(GEP, Op0,
Chris Lattner2188e402010-01-04 07:37:31 +00003786 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3787 return NI;
3788
Hans Wennborgf1f36512015-10-07 00:20:07 +00003789 // Try to optimize equality comparisons against alloca-based pointers.
3790 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3791 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3792 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003793 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003794 return New;
3795 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003796 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003797 return New;
3798 }
3799
Chris Lattner2188e402010-01-04 07:37:31 +00003800 // Test to see if the operands of the icmp are casted versions of other
3801 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3802 // now.
3803 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003804 if (Op0->getType()->isPointerTy() &&
3805 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003806 // We keep moving the cast from the left operand over to the right
3807 // operand, where it can often be eliminated completely.
3808 Op0 = CI->getOperand(0);
3809
3810 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3811 // so eliminate it as well.
3812 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3813 Op1 = CI2->getOperand(0);
3814
3815 // If Op1 is a constant, we can fold the cast into the constant.
3816 if (Op0->getType() != Op1->getType()) {
3817 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3818 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3819 } else {
3820 // Otherwise, cast the RHS right before the icmp
3821 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3822 }
3823 }
3824 return new ICmpInst(I.getPredicate(), Op0, Op1);
3825 }
3826 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003827
Chris Lattner2188e402010-01-04 07:37:31 +00003828 if (isa<CastInst>(Op0)) {
3829 // Handle the special case of: icmp (cast bool to X), <cst>
3830 // This comes up when you have code like
3831 // int X = A < B;
3832 // if (X) ...
3833 // For generality, we handle any zero-extension of any operand comparison
3834 // with a constant or another cast from the same type.
3835 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003836 if (Instruction *R = foldICmpWithCastAndCast(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003837 return R;
3838 }
Chris Lattner2188e402010-01-04 07:37:31 +00003839
Duncan Sandse5220012011-02-17 07:46:37 +00003840 // Special logic for binary operators.
3841 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3842 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3843 if (BO0 || BO1) {
3844 CmpInst::Predicate Pred = I.getPredicate();
3845 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3846 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3847 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3848 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3849 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3850 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3851 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3852 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3853 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3854
3855 // Analyze the case when either Op0 or Op1 is an add instruction.
3856 // 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 +00003857 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003858 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3859 A = BO0->getOperand(0);
3860 B = BO0->getOperand(1);
3861 }
3862 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3863 C = BO1->getOperand(0);
3864 D = BO1->getOperand(1);
3865 }
Duncan Sandse5220012011-02-17 07:46:37 +00003866
David Majnemer549f4f22014-11-01 09:09:51 +00003867 // icmp (X+cst) < 0 --> X < -cst
3868 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3869 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3870 if (!RHSC->isMinValue(/*isSigned=*/true))
3871 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3872
Duncan Sandse5220012011-02-17 07:46:37 +00003873 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3874 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3875 return new ICmpInst(Pred, A == Op1 ? B : A,
3876 Constant::getNullValue(Op1->getType()));
3877
3878 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3879 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3880 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3881 C == Op0 ? D : C);
3882
Duncan Sands84653b32011-02-18 16:25:37 +00003883 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003884 if (A && C && (A == C || A == D || B == C || B == D) &&
3885 NoOp0WrapProblem && NoOp1WrapProblem &&
3886 // Try not to increase register pressure.
3887 BO0->hasOneUse() && BO1->hasOneUse()) {
3888 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003889 Value *Y, *Z;
3890 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003891 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003892 Y = B;
3893 Z = D;
3894 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003895 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003896 Y = B;
3897 Z = C;
3898 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003899 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003900 Y = A;
3901 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003902 } else {
3903 assert(B == D);
3904 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003905 Y = A;
3906 Z = C;
3907 }
Duncan Sandse5220012011-02-17 07:46:37 +00003908 return new ICmpInst(Pred, Y, Z);
3909 }
3910
David Majnemerb81cd632013-04-11 20:05:46 +00003911 // icmp slt (X + -1), Y -> icmp sle X, Y
3912 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3913 match(B, m_AllOnes()))
3914 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3915
3916 // icmp sge (X + -1), Y -> icmp sgt X, Y
3917 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3918 match(B, m_AllOnes()))
3919 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3920
3921 // icmp sle (X + 1), Y -> icmp slt X, Y
3922 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3923 match(B, m_One()))
3924 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3925
3926 // icmp sgt (X + 1), Y -> icmp sge X, Y
3927 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3928 match(B, m_One()))
3929 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3930
Michael Liaoc65d3862015-10-19 22:08:14 +00003931 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3932 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3933 match(D, m_AllOnes()))
3934 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3935
3936 // icmp sle X, (Y + -1) -> icmp slt X, Y
3937 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3938 match(D, m_AllOnes()))
3939 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3940
3941 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3942 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3943 match(D, m_One()))
3944 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3945
3946 // icmp slt X, (Y + 1) -> icmp sle X, Y
3947 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3948 match(D, m_One()))
3949 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3950
David Majnemerb81cd632013-04-11 20:05:46 +00003951 // if C1 has greater magnitude than C2:
3952 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3953 // s.t. C3 = C1 - C2
3954 //
3955 // if C2 has greater magnitude than C1:
3956 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
3957 // s.t. C3 = C2 - C1
3958 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3959 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
3960 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
3961 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
3962 const APInt &AP1 = C1->getValue();
3963 const APInt &AP2 = C2->getValue();
3964 if (AP1.isNegative() == AP2.isNegative()) {
3965 APInt AP1Abs = C1->getValue().abs();
3966 APInt AP2Abs = C2->getValue().abs();
3967 if (AP1Abs.uge(AP2Abs)) {
3968 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
3969 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
3970 return new ICmpInst(Pred, NewAdd, C);
3971 } else {
3972 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
3973 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
3974 return new ICmpInst(Pred, A, NewAdd);
3975 }
3976 }
3977 }
3978
3979
Duncan Sandse5220012011-02-17 07:46:37 +00003980 // Analyze the case when either Op0 or Op1 is a sub instruction.
3981 // 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 +00003982 A = nullptr;
3983 B = nullptr;
3984 C = nullptr;
3985 D = nullptr;
3986 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
3987 A = BO0->getOperand(0);
3988 B = BO0->getOperand(1);
3989 }
3990 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3991 C = BO1->getOperand(0);
3992 D = BO1->getOperand(1);
3993 }
Duncan Sandse5220012011-02-17 07:46:37 +00003994
Duncan Sands84653b32011-02-18 16:25:37 +00003995 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
3996 if (A == Op1 && NoOp0WrapProblem)
3997 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
3998
3999 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
4000 if (C == Op0 && NoOp1WrapProblem)
4001 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
4002
4003 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00004004 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
4005 // Try not to increase register pressure.
4006 BO0->hasOneUse() && BO1->hasOneUse())
4007 return new ICmpInst(Pred, A, C);
4008
Duncan Sands84653b32011-02-18 16:25:37 +00004009 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
4010 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
4011 // Try not to increase register pressure.
4012 BO0->hasOneUse() && BO1->hasOneUse())
4013 return new ICmpInst(Pred, D, B);
4014
David Majnemer186c9422014-05-15 00:02:20 +00004015 // icmp (0-X) < cst --> x > -cst
4016 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
4017 Value *X;
4018 if (match(BO0, m_Neg(m_Value(X))))
4019 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
4020 if (!RHSC->isMinValue(/*isSigned=*/true))
4021 return new ICmpInst(I.getSwappedPredicate(), X,
4022 ConstantExpr::getNeg(RHSC));
4023 }
4024
Craig Topperf40110f2014-04-25 05:29:35 +00004025 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004026 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00004027 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
4028 Op1 == BO0->getOperand(1))
4029 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004030 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00004031 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
4032 Op0 == BO1->getOperand(1))
4033 SRem = BO1;
4034 if (SRem) {
4035 // We don't check hasOneUse to avoid increasing register pressure because
4036 // the value we use is the same value this instruction was already using.
4037 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
4038 default: break;
4039 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00004040 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004041 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00004042 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004043 case ICmpInst::ICMP_SGT:
4044 case ICmpInst::ICMP_SGE:
4045 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4046 Constant::getAllOnesValue(SRem->getType()));
4047 case ICmpInst::ICMP_SLT:
4048 case ICmpInst::ICMP_SLE:
4049 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4050 Constant::getNullValue(SRem->getType()));
4051 }
4052 }
4053
Duncan Sandse5220012011-02-17 07:46:37 +00004054 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
4055 BO0->hasOneUse() && BO1->hasOneUse() &&
4056 BO0->getOperand(1) == BO1->getOperand(1)) {
4057 switch (BO0->getOpcode()) {
4058 default: break;
4059 case Instruction::Add:
4060 case Instruction::Sub:
4061 case Instruction::Xor:
4062 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4063 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4064 BO1->getOperand(0));
4065 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
4066 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4067 if (CI->getValue().isSignBit()) {
4068 ICmpInst::Predicate Pred = I.isSigned()
4069 ? I.getUnsignedPredicate()
4070 : I.getSignedPredicate();
4071 return new ICmpInst(Pred, BO0->getOperand(0),
4072 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00004073 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004074
David Majnemerf8853ae2016-02-01 17:37:56 +00004075 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00004076 ICmpInst::Predicate Pred = I.isSigned()
4077 ? I.getUnsignedPredicate()
4078 : I.getSignedPredicate();
4079 Pred = I.getSwappedPredicate(Pred);
4080 return new ICmpInst(Pred, BO0->getOperand(0),
4081 BO1->getOperand(0));
4082 }
Chris Lattner2188e402010-01-04 07:37:31 +00004083 }
Duncan Sandse5220012011-02-17 07:46:37 +00004084 break;
4085 case Instruction::Mul:
4086 if (!I.isEquality())
4087 break;
4088
4089 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4090 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
4091 // Mask = -1 >> count-trailing-zeros(Cst).
4092 if (!CI->isZero() && !CI->isOne()) {
4093 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004094 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00004095 APInt::getLowBitsSet(AP.getBitWidth(),
4096 AP.getBitWidth() -
4097 AP.countTrailingZeros()));
4098 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4099 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4100 return new ICmpInst(I.getPredicate(), And1, And2);
4101 }
4102 }
4103 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00004104 case Instruction::UDiv:
4105 case Instruction::LShr:
4106 if (I.isSigned())
4107 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00004108 LLVM_FALLTHROUGH;
Nick Lewycky9719a712011-03-05 05:19:11 +00004109 case Instruction::SDiv:
4110 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00004111 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00004112 break;
4113 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4114 BO1->getOperand(0));
4115 case Instruction::Shl: {
4116 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4117 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4118 if (!NUW && !NSW)
4119 break;
4120 if (!NSW && I.isSigned())
4121 break;
4122 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4123 BO1->getOperand(0));
4124 }
Chris Lattner2188e402010-01-04 07:37:31 +00004125 }
4126 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00004127
4128 if (BO0) {
4129 // Transform A & (L - 1) `ult` L --> L != 0
4130 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4131 auto BitwiseAnd =
4132 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4133
4134 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4135 auto *Zero = Constant::getNullValue(BO0->getType());
4136 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4137 }
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 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004142 // Transform (A & ~B) == 0 --> (A & B) != 0
4143 // and (A & ~B) != 0 --> (A & B) == 0
4144 // if A is a power of 2.
4145 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004146 match(Op1, m_Zero()) &&
Justin Bogner99798402016-08-05 01:06:44 +00004147 isKnownToBeAPowerOfTwo(A, DL, false, 0, &AC, &I, &DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004148 return new ICmpInst(I.getInversePredicate(),
4149 Builder->CreateAnd(A, B),
4150 Op1);
4151
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004152 // ~x < ~y --> y < x
4153 // ~x < cst --> ~cst < x
4154 if (match(Op0, m_Not(m_Value(A)))) {
4155 if (match(Op1, m_Not(m_Value(B))))
4156 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004157 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004158 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4159 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004160
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004161 Instruction *AddI = nullptr;
4162 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4163 m_Instruction(AddI))) &&
4164 isa<IntegerType>(A->getType())) {
4165 Value *Result;
4166 Constant *Overflow;
4167 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4168 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004169 replaceInstUsesWith(*AddI, Result);
4170 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004171 }
4172 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004173
4174 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4175 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4176 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4177 return R;
4178 }
4179 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4180 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4181 return R;
4182 }
Chris Lattner2188e402010-01-04 07:37:31 +00004183 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004184
Chris Lattner2188e402010-01-04 07:37:31 +00004185 if (I.isEquality()) {
4186 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004187
Chris Lattner2188e402010-01-04 07:37:31 +00004188 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4189 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4190 Value *OtherVal = A == Op1 ? B : A;
4191 return new ICmpInst(I.getPredicate(), OtherVal,
4192 Constant::getNullValue(A->getType()));
4193 }
4194
4195 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4196 // A^c1 == C^c2 --> A == C^(c1^c2)
4197 ConstantInt *C1, *C2;
4198 if (match(B, m_ConstantInt(C1)) &&
4199 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004200 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004201 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004202 return new ICmpInst(I.getPredicate(), A, Xor);
4203 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004204
Chris Lattner2188e402010-01-04 07:37:31 +00004205 // A^B == A^D -> B == D
4206 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4207 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4208 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4209 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4210 }
4211 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004212
Chris Lattner2188e402010-01-04 07:37:31 +00004213 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4214 (A == Op0 || B == Op0)) {
4215 // A == (A^B) -> B == 0
4216 Value *OtherVal = A == Op0 ? B : A;
4217 return new ICmpInst(I.getPredicate(), OtherVal,
4218 Constant::getNullValue(A->getType()));
4219 }
4220
Chris Lattner2188e402010-01-04 07:37:31 +00004221 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004222 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004223 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004224 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004225
Chris Lattner2188e402010-01-04 07:37:31 +00004226 if (A == C) {
4227 X = B; Y = D; Z = A;
4228 } else if (A == D) {
4229 X = B; Y = C; Z = A;
4230 } else if (B == C) {
4231 X = A; Y = D; Z = B;
4232 } else if (B == D) {
4233 X = A; Y = C; Z = B;
4234 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004235
Chris Lattner2188e402010-01-04 07:37:31 +00004236 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004237 Op1 = Builder->CreateXor(X, Y);
4238 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004239 I.setOperand(0, Op1);
4240 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4241 return &I;
4242 }
4243 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004244
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004245 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004246 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004247 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004248 if ((Op0->hasOneUse() &&
4249 match(Op0, m_ZExt(m_Value(A))) &&
4250 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4251 (Op1->hasOneUse() &&
4252 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4253 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004254 APInt Pow2 = Cst1->getValue() + 1;
4255 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4256 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4257 return new ICmpInst(I.getPredicate(), A,
4258 Builder->CreateTrunc(B, A->getType()));
4259 }
4260
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004261 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4262 // For lshr and ashr pairs.
4263 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4264 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4265 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4266 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4267 unsigned TypeBits = Cst1->getBitWidth();
4268 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4269 if (ShAmt < TypeBits && ShAmt != 0) {
4270 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4271 ? ICmpInst::ICMP_UGE
4272 : ICmpInst::ICMP_ULT;
4273 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4274 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4275 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4276 }
4277 }
4278
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004279 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4280 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4281 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4282 unsigned TypeBits = Cst1->getBitWidth();
4283 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4284 if (ShAmt < TypeBits && ShAmt != 0) {
4285 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4286 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4287 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4288 I.getName() + ".mask");
4289 return new ICmpInst(I.getPredicate(), And,
4290 Constant::getNullValue(Cst1->getType()));
4291 }
4292 }
4293
Chris Lattner1b06c712011-04-26 20:18:20 +00004294 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4295 // "icmp (and X, mask), cst"
4296 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004297 if (Op0->hasOneUse() &&
4298 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4299 m_ConstantInt(ShAmt))))) &&
4300 match(Op1, m_ConstantInt(Cst1)) &&
4301 // Only do this when A has multiple uses. This is most important to do
4302 // when it exposes other optimizations.
4303 !A->hasOneUse()) {
4304 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004305
Chris Lattner1b06c712011-04-26 20:18:20 +00004306 if (ShAmt < ASize) {
4307 APInt MaskV =
4308 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4309 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004310
Chris Lattner1b06c712011-04-26 20:18:20 +00004311 APInt CmpV = Cst1->getValue().zext(ASize);
4312 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004313
Chris Lattner1b06c712011-04-26 20:18:20 +00004314 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4315 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4316 }
4317 }
Chris Lattner2188e402010-01-04 07:37:31 +00004318 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004319
David Majnemerc1eca5a2014-11-06 23:23:30 +00004320 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4321 // an i1 which indicates whether or not we successfully did the swap.
4322 //
4323 // Replace comparisons between the old value and the expected value with the
4324 // indicator that 'cmpxchg' returns.
4325 //
4326 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4327 // spuriously fail. In those cases, the old value may equal the expected
4328 // value but it is possible for the swap to not occur.
4329 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4330 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4331 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4332 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4333 !ACXI->isWeak())
4334 return ExtractValueInst::Create(ACXI, 1);
4335
Chris Lattner2188e402010-01-04 07:37:31 +00004336 {
4337 Value *X; ConstantInt *Cst;
4338 // icmp X+Cst, X
4339 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004340 return foldICmpAddOpConst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004341
4342 // icmp X, X+Cst
4343 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004344 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004345 }
Craig Topperf40110f2014-04-25 05:29:35 +00004346 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004347}
4348
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004349/// Fold fcmp ([us]itofp x, cst) if possible.
Sanjay Patel43395062016-07-21 18:07:40 +00004350Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
Chris Lattner2188e402010-01-04 07:37:31 +00004351 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004352 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004353 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004354
Chris Lattner2188e402010-01-04 07:37:31 +00004355 // Get the width of the mantissa. We don't want to hack on conversions that
4356 // might lose information from the integer, e.g. "i64 -> float"
4357 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004358 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004359
Matt Arsenault55e73122015-01-06 15:50:59 +00004360 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4361
Chris Lattner2188e402010-01-04 07:37:31 +00004362 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004363
Matt Arsenault55e73122015-01-06 15:50:59 +00004364 if (I.isEquality()) {
4365 FCmpInst::Predicate P = I.getPredicate();
4366 bool IsExact = false;
4367 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4368 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4369
4370 // If the floating point constant isn't an integer value, we know if we will
4371 // ever compare equal / not equal to it.
4372 if (!IsExact) {
4373 // TODO: Can never be -0.0 and other non-representable values
4374 APFloat RHSRoundInt(RHS);
4375 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4376 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4377 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004378 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004379
4380 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004381 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004382 }
4383 }
4384
4385 // TODO: If the constant is exactly representable, is it always OK to do
4386 // equality compares as integer?
4387 }
4388
Arch D. Robison8ed08542015-09-15 17:51:59 +00004389 // Check to see that the input is converted from an integer type that is small
4390 // enough that preserves all bits. TODO: check here for "known" sign bits.
4391 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4392 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004393
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004394 // Following test does NOT adjust InputSize downwards for signed inputs,
4395 // because the most negative value still requires all the mantissa bits
Arch D. Robison8ed08542015-09-15 17:51:59 +00004396 // to distinguish it from one less than that value.
4397 if ((int)InputSize > MantissaWidth) {
4398 // Conversion would lose accuracy. Check if loss can impact comparison.
4399 int Exp = ilogb(RHS);
4400 if (Exp == APFloat::IEK_Inf) {
4401 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004402 if (MaxExponent < (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004403 // Conversion could create infinity.
4404 return nullptr;
4405 } else {
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004406 // Note that if RHS is zero or NaN, then Exp is negative
Arch D. Robison8ed08542015-09-15 17:51:59 +00004407 // and first condition is trivially false.
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004408 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004409 // Conversion could affect comparison.
4410 return nullptr;
4411 }
4412 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004413
Chris Lattner2188e402010-01-04 07:37:31 +00004414 // Otherwise, we can potentially simplify the comparison. We know that it
4415 // will always come through as an integer value and we know the constant is
4416 // not a NAN (it would have been previously simplified).
4417 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004418
Chris Lattner2188e402010-01-04 07:37:31 +00004419 ICmpInst::Predicate Pred;
4420 switch (I.getPredicate()) {
4421 default: llvm_unreachable("Unexpected predicate!");
4422 case FCmpInst::FCMP_UEQ:
4423 case FCmpInst::FCMP_OEQ:
4424 Pred = ICmpInst::ICMP_EQ;
4425 break;
4426 case FCmpInst::FCMP_UGT:
4427 case FCmpInst::FCMP_OGT:
4428 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4429 break;
4430 case FCmpInst::FCMP_UGE:
4431 case FCmpInst::FCMP_OGE:
4432 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4433 break;
4434 case FCmpInst::FCMP_ULT:
4435 case FCmpInst::FCMP_OLT:
4436 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4437 break;
4438 case FCmpInst::FCMP_ULE:
4439 case FCmpInst::FCMP_OLE:
4440 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4441 break;
4442 case FCmpInst::FCMP_UNE:
4443 case FCmpInst::FCMP_ONE:
4444 Pred = ICmpInst::ICMP_NE;
4445 break;
4446 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004447 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004448 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004449 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004450 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004451
Chris Lattner2188e402010-01-04 07:37:31 +00004452 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004453
Chris Lattner2188e402010-01-04 07:37:31 +00004454 // See if the FP constant is too large for the integer. For example,
4455 // comparing an i8 to 300.0.
4456 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004457
Chris Lattner2188e402010-01-04 07:37:31 +00004458 if (!LHSUnsigned) {
4459 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4460 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004461 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004462 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4463 APFloat::rmNearestTiesToEven);
4464 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4465 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4466 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004467 return replaceInstUsesWith(I, Builder->getTrue());
4468 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004469 }
4470 } else {
4471 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4472 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004473 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004474 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4475 APFloat::rmNearestTiesToEven);
4476 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4477 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4478 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004479 return replaceInstUsesWith(I, Builder->getTrue());
4480 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004481 }
4482 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004483
Chris Lattner2188e402010-01-04 07:37:31 +00004484 if (!LHSUnsigned) {
4485 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004486 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004487 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4488 APFloat::rmNearestTiesToEven);
4489 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4490 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4491 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004492 return replaceInstUsesWith(I, Builder->getTrue());
4493 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004494 }
Devang Patel698452b2012-02-13 23:05:18 +00004495 } else {
4496 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004497 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004498 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4499 APFloat::rmNearestTiesToEven);
4500 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4501 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4502 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004503 return replaceInstUsesWith(I, Builder->getTrue());
4504 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004505 }
Chris Lattner2188e402010-01-04 07:37:31 +00004506 }
4507
4508 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4509 // [0, UMAX], but it may still be fractional. See if it is fractional by
4510 // casting the FP value to the integer value and back, checking for equality.
4511 // Don't do this for zero, because -0.0 is not fractional.
4512 Constant *RHSInt = LHSUnsigned
4513 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4514 : ConstantExpr::getFPToSI(RHSC, IntTy);
4515 if (!RHS.isZero()) {
4516 bool Equal = LHSUnsigned
4517 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4518 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4519 if (!Equal) {
4520 // If we had a comparison against a fractional value, we have to adjust
4521 // the compare predicate and sometimes the value. RHSC is rounded towards
4522 // zero at this point.
4523 switch (Pred) {
4524 default: llvm_unreachable("Unexpected integer comparison!");
4525 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004526 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004527 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004528 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004529 case ICmpInst::ICMP_ULE:
4530 // (float)int <= 4.4 --> int <= 4
4531 // (float)int <= -4.4 --> false
4532 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004533 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004534 break;
4535 case ICmpInst::ICMP_SLE:
4536 // (float)int <= 4.4 --> int <= 4
4537 // (float)int <= -4.4 --> int < -4
4538 if (RHS.isNegative())
4539 Pred = ICmpInst::ICMP_SLT;
4540 break;
4541 case ICmpInst::ICMP_ULT:
4542 // (float)int < -4.4 --> false
4543 // (float)int < 4.4 --> int <= 4
4544 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004545 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004546 Pred = ICmpInst::ICMP_ULE;
4547 break;
4548 case ICmpInst::ICMP_SLT:
4549 // (float)int < -4.4 --> int < -4
4550 // (float)int < 4.4 --> int <= 4
4551 if (!RHS.isNegative())
4552 Pred = ICmpInst::ICMP_SLE;
4553 break;
4554 case ICmpInst::ICMP_UGT:
4555 // (float)int > 4.4 --> int > 4
4556 // (float)int > -4.4 --> true
4557 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004558 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004559 break;
4560 case ICmpInst::ICMP_SGT:
4561 // (float)int > 4.4 --> int > 4
4562 // (float)int > -4.4 --> int >= -4
4563 if (RHS.isNegative())
4564 Pred = ICmpInst::ICMP_SGE;
4565 break;
4566 case ICmpInst::ICMP_UGE:
4567 // (float)int >= -4.4 --> true
4568 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004569 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004570 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004571 Pred = ICmpInst::ICMP_UGT;
4572 break;
4573 case ICmpInst::ICMP_SGE:
4574 // (float)int >= -4.4 --> int >= -4
4575 // (float)int >= 4.4 --> int > 4
4576 if (!RHS.isNegative())
4577 Pred = ICmpInst::ICMP_SGT;
4578 break;
4579 }
4580 }
4581 }
4582
4583 // Lower this FP comparison into an appropriate integer version of the
4584 // comparison.
4585 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4586}
4587
4588Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4589 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004590
Chris Lattner2188e402010-01-04 07:37:31 +00004591 /// Orders the operands of the compare so that they are listed from most
4592 /// complex to least complex. This puts constants before unary operators,
4593 /// before binary operators.
4594 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4595 I.swapOperands();
4596 Changed = true;
4597 }
4598
4599 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004600
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004601 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
Justin Bogner99798402016-08-05 01:06:44 +00004602 I.getFastMathFlags(), DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004603 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004604
4605 // Simplify 'fcmp pred X, X'
4606 if (Op0 == Op1) {
4607 switch (I.getPredicate()) {
4608 default: llvm_unreachable("Unknown predicate!");
4609 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4610 case FCmpInst::FCMP_ULT: // True if unordered or less than
4611 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4612 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4613 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4614 I.setPredicate(FCmpInst::FCMP_UNO);
4615 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4616 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004617
Chris Lattner2188e402010-01-04 07:37:31 +00004618 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4619 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4620 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4621 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4622 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4623 I.setPredicate(FCmpInst::FCMP_ORD);
4624 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4625 return &I;
4626 }
4627 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004628
James Molloy2b21a7c2015-05-20 18:41:25 +00004629 // Test if the FCmpInst instruction is used exclusively by a select as
4630 // part of a minimum or maximum operation. If so, refrain from doing
4631 // any other folding. This helps out other analyses which understand
4632 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4633 // and CodeGen. And in this case, at least one of the comparison
4634 // operands has at least one user besides the compare (the select),
4635 // which would often largely negate the benefit of folding anyway.
4636 if (I.hasOneUse())
4637 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4638 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4639 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4640 return nullptr;
4641
Chris Lattner2188e402010-01-04 07:37:31 +00004642 // Handle fcmp with constant RHS
4643 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4644 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4645 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004646 case Instruction::FPExt: {
4647 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4648 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4649 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4650 if (!RHSF)
4651 break;
4652
4653 const fltSemantics *Sem;
4654 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004655 if (LHSExt->getSrcTy()->isHalfTy())
4656 Sem = &APFloat::IEEEhalf;
4657 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004658 Sem = &APFloat::IEEEsingle;
4659 else if (LHSExt->getSrcTy()->isDoubleTy())
4660 Sem = &APFloat::IEEEdouble;
4661 else if (LHSExt->getSrcTy()->isFP128Ty())
4662 Sem = &APFloat::IEEEquad;
4663 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4664 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004665 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4666 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004667 else
4668 break;
4669
4670 bool Lossy;
4671 APFloat F = RHSF->getValueAPF();
4672 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4673
Jim Grosbach24ff8342011-09-30 18:45:50 +00004674 // Avoid lossy conversions and denormals. Zero is a special case
4675 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004676 APFloat Fabs = F;
4677 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004678 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004679 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4680 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004681
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004682 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4683 ConstantFP::get(RHSC->getContext(), F));
4684 break;
4685 }
Chris Lattner2188e402010-01-04 07:37:31 +00004686 case Instruction::PHI:
4687 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4688 // block. If in the same block, we're encouraging jump threading. If
4689 // not, we are just pessimizing the code by making an i1 phi.
4690 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004691 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004692 return NV;
4693 break;
4694 case Instruction::SIToFP:
4695 case Instruction::UIToFP:
Sanjay Patel43395062016-07-21 18:07:40 +00004696 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
Chris Lattner2188e402010-01-04 07:37:31 +00004697 return NV;
4698 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004699 case Instruction::FSub: {
4700 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4701 Value *Op;
4702 if (match(LHSI, m_FNeg(m_Value(Op))))
4703 return new FCmpInst(I.getSwappedPredicate(), Op,
4704 ConstantExpr::getFNeg(RHSC));
4705 break;
4706 }
Dan Gohman94732022010-02-24 06:46:09 +00004707 case Instruction::Load:
4708 if (GetElementPtrInst *GEP =
4709 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4710 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4711 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4712 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00004713 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Dan Gohman94732022010-02-24 06:46:09 +00004714 return Res;
4715 }
4716 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004717 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004718 if (!RHSC->isNullValue())
4719 break;
4720
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004721 CallInst *CI = cast<CallInst>(LHSI);
Justin Bogner99798402016-08-05 01:06:44 +00004722 Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004723 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004724 break;
4725
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004726 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004727 switch (I.getPredicate()) {
4728 default:
4729 break;
4730 // fabs(x) < 0 --> false
4731 case FCmpInst::FCMP_OLT:
4732 llvm_unreachable("handled by SimplifyFCmpInst");
4733 // fabs(x) > 0 --> x != 0
4734 case FCmpInst::FCMP_OGT:
4735 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4736 // fabs(x) <= 0 --> x == 0
4737 case FCmpInst::FCMP_OLE:
4738 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4739 // fabs(x) >= 0 --> !isnan(x)
4740 case FCmpInst::FCMP_OGE:
4741 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4742 // fabs(x) == 0 --> x == 0
4743 // fabs(x) != 0 --> x != 0
4744 case FCmpInst::FCMP_OEQ:
4745 case FCmpInst::FCMP_UEQ:
4746 case FCmpInst::FCMP_ONE:
4747 case FCmpInst::FCMP_UNE:
4748 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004749 }
4750 }
Chris Lattner2188e402010-01-04 07:37:31 +00004751 }
Chris Lattner2188e402010-01-04 07:37:31 +00004752 }
4753
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004754 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004755 Value *X, *Y;
4756 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004757 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004758
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004759 // fcmp (fpext x), (fpext y) -> fcmp x, y
4760 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4761 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4762 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4763 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4764 RHSExt->getOperand(0));
4765
Craig Topperf40110f2014-04-25 05:29:35 +00004766 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004767}