blob: 261c9eedf85e55eb4a3f06d1d609634a36268210 [file] [log] [blame]
Chris Lattner2188e402010-01-04 07:37:31 +00001//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitICmp and visitFCmp functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Matt Arsenault55e73122015-01-06 15:50:59 +000015#include "llvm/ADT/APSInt.h"
Silviu Barangaf29dfd32016-01-15 15:52:05 +000016#include "llvm/ADT/SetVector.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000017#include "llvm/ADT/Statistic.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000018#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner2188e402010-01-04 07:37:31 +000019#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/MemoryBuiltins.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000025#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000027#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000028#include "llvm/Support/Debug.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000029
Chris Lattner2188e402010-01-04 07:37:31 +000030using namespace llvm;
31using namespace PatternMatch;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "instcombine"
34
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000035// How many times is a select replaced by one of its operands?
36STATISTIC(NumSel, "Number of select opts");
37
38// Initialization Routines
39
Chris Lattner98457102011-02-10 05:23:05 +000040static ConstantInt *getOne(Constant *C) {
41 return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
42}
43
Chris Lattner2188e402010-01-04 07:37:31 +000044static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
45 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
46}
47
48static bool HasAddOverflow(ConstantInt *Result,
49 ConstantInt *In1, ConstantInt *In2,
50 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000051 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000052 return Result->getValue().ult(In1->getValue());
Chris Lattnerb1a15122011-07-15 06:08:15 +000053
54 if (In2->isNegative())
55 return Result->getValue().sgt(In1->getValue());
56 return Result->getValue().slt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000057}
58
Sanjay Patel5f0217f2016-06-05 16:46:18 +000059/// Compute Result = In1+In2, returning true if the result overflowed for this
60/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000061static bool AddWithOverflow(Constant *&Result, Constant *In1,
62 Constant *In2, bool IsSigned = false) {
63 Result = ConstantExpr::getAdd(In1, In2);
64
Chris Lattner229907c2011-07-18 04:54:35 +000065 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +000066 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
67 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
68 if (HasAddOverflow(ExtractElement(Result, Idx),
69 ExtractElement(In1, Idx),
70 ExtractElement(In2, Idx),
71 IsSigned))
72 return true;
73 }
74 return false;
75 }
76
77 return HasAddOverflow(cast<ConstantInt>(Result),
78 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
79 IsSigned);
80}
81
82static bool HasSubOverflow(ConstantInt *Result,
83 ConstantInt *In1, ConstantInt *In2,
84 bool IsSigned) {
Chris Lattnerb1a15122011-07-15 06:08:15 +000085 if (!IsSigned)
Chris Lattner2188e402010-01-04 07:37:31 +000086 return Result->getValue().ugt(In1->getValue());
Jim Grosbach129c52a2011-09-30 18:09:53 +000087
Chris Lattnerb1a15122011-07-15 06:08:15 +000088 if (In2->isNegative())
89 return Result->getValue().slt(In1->getValue());
90
91 return Result->getValue().sgt(In1->getValue());
Chris Lattner2188e402010-01-04 07:37:31 +000092}
93
Sanjay Patel5f0217f2016-06-05 16:46:18 +000094/// Compute Result = In1-In2, returning true if the result overflowed for this
95/// type.
Chris Lattner2188e402010-01-04 07:37:31 +000096static bool SubWithOverflow(Constant *&Result, Constant *In1,
97 Constant *In2, bool IsSigned = false) {
98 Result = ConstantExpr::getSub(In1, In2);
99
Chris Lattner229907c2011-07-18 04:54:35 +0000100 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
Chris Lattner2188e402010-01-04 07:37:31 +0000101 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
102 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
103 if (HasSubOverflow(ExtractElement(Result, Idx),
104 ExtractElement(In1, Idx),
105 ExtractElement(In2, Idx),
106 IsSigned))
107 return true;
108 }
109 return false;
110 }
111
112 return HasSubOverflow(cast<ConstantInt>(Result),
113 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
114 IsSigned);
115}
116
Balaram Makam569eaec2016-05-04 21:32:14 +0000117/// Given an icmp instruction, return true if any use of this comparison is a
118/// branch on sign bit comparison.
119static bool isBranchOnSignBitCheck(ICmpInst &I, bool isSignBit) {
120 for (auto *U : I.users())
121 if (isa<BranchInst>(U))
122 return isSignBit;
123 return false;
124}
125
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000126/// Given an exploded icmp instruction, return true if the comparison only
127/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the
128/// result of the comparison is true when the input value is signed.
129static bool isSignBitCheck(ICmpInst::Predicate Pred, ConstantInt *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000130 bool &TrueIfSigned) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000131 switch (Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +0000132 case ICmpInst::ICMP_SLT: // True if LHS s< 0
133 TrueIfSigned = true;
134 return RHS->isZero();
135 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
136 TrueIfSigned = true;
137 return RHS->isAllOnesValue();
138 case ICmpInst::ICMP_SGT: // True if LHS s> -1
139 TrueIfSigned = false;
140 return RHS->isAllOnesValue();
141 case ICmpInst::ICMP_UGT:
142 // True if LHS u> RHS and RHS == high-bit-mask - 1
143 TrueIfSigned = true;
Chris Lattnerb1a15122011-07-15 06:08:15 +0000144 return RHS->isMaxValue(true);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000145 case ICmpInst::ICMP_UGE:
Chris Lattner2188e402010-01-04 07:37:31 +0000146 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
147 TrueIfSigned = true;
148 return RHS->getValue().isSignBit();
149 default:
150 return false;
151 }
152}
153
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000154/// Returns true if the exploded icmp can be expressed as a signed comparison
155/// to zero and updates the predicate accordingly.
156/// The signedness of the comparison is preserved.
Sanjay Patel5b112842016-08-18 14:59:14 +0000157/// TODO: Refactor with decomposeBitTestICmp()?
158static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000159 if (!ICmpInst::isSigned(Pred))
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000160 return false;
161
Sanjay Patel5b112842016-08-18 14:59:14 +0000162 if (C == 0)
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000163 return ICmpInst::isRelational(Pred);
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000164
Sanjay Patel5b112842016-08-18 14:59:14 +0000165 if (C == 1) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000166 if (Pred == ICmpInst::ICMP_SLT) {
167 Pred = ICmpInst::ICMP_SLE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000168 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000169 }
Sanjay Patel5b112842016-08-18 14:59:14 +0000170 } else if (C.isAllOnesValue()) {
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000171 if (Pred == ICmpInst::ICMP_SGT) {
172 Pred = ICmpInst::ICMP_SGE;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000173 return true;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000174 }
Arnaud A. de Grandmaison3ee88e82013-03-25 11:47:38 +0000175 }
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +0000176
177 return false;
178}
179
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000180/// Given a signed integer type and a set of known zero and one bits, compute
181/// the maximum and minimum values that could have the specified known zero and
182/// known one bits, returning them in Min/Max.
183static void ComputeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
184 const APInt &KnownOne,
185 APInt &Min, APInt &Max) {
Chris Lattner2188e402010-01-04 07:37:31 +0000186 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
187 KnownZero.getBitWidth() == Min.getBitWidth() &&
188 KnownZero.getBitWidth() == Max.getBitWidth() &&
189 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
190 APInt UnknownBits = ~(KnownZero|KnownOne);
191
192 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
193 // bit if it is unknown.
194 Min = KnownOne;
195 Max = KnownOne|UnknownBits;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000196
Chris Lattner2188e402010-01-04 07:37:31 +0000197 if (UnknownBits.isNegative()) { // Sign bit is unknown
Jay Foad25a5e4c2010-12-01 08:53:58 +0000198 Min.setBit(Min.getBitWidth()-1);
199 Max.clearBit(Max.getBitWidth()-1);
Chris Lattner2188e402010-01-04 07:37:31 +0000200 }
201}
202
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000203/// Given an unsigned integer type and a set of known zero and one bits, compute
204/// the maximum and minimum values that could have the specified known zero and
205/// known one bits, returning them in Min/Max.
Chris Lattner2188e402010-01-04 07:37:31 +0000206static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
207 const APInt &KnownOne,
208 APInt &Min, APInt &Max) {
209 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
210 KnownZero.getBitWidth() == Min.getBitWidth() &&
211 KnownZero.getBitWidth() == Max.getBitWidth() &&
212 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
213 APInt UnknownBits = ~(KnownZero|KnownOne);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000214
Chris Lattner2188e402010-01-04 07:37:31 +0000215 // The minimum value is when the unknown bits are all zeros.
216 Min = KnownOne;
217 // The maximum value is when the unknown bits are all ones.
218 Max = KnownOne|UnknownBits;
219}
220
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000221/// This is called when we see this pattern:
Chris Lattner2188e402010-01-04 07:37:31 +0000222/// cmp pred (load (gep GV, ...)), cmpcst
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000223/// where GV is a global variable with a constant initializer. Try to simplify
224/// this into some simple computation that does not need the load. For example
Chris Lattner2188e402010-01-04 07:37:31 +0000225/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
226///
227/// If AndCst is non-null, then the loaded value is masked with that constant
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000228/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Sanjay Patel43395062016-07-21 18:07:40 +0000229Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
230 GlobalVariable *GV,
231 CmpInst &ICI,
232 ConstantInt *AndCst) {
Chris Lattnerfe741762012-01-31 02:55:06 +0000233 Constant *Init = GV->getInitializer();
234 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
Craig Topperf40110f2014-04-25 05:29:35 +0000235 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000236
Chris Lattnerfe741762012-01-31 02:55:06 +0000237 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +0000238 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000239
Chris Lattner2188e402010-01-04 07:37:31 +0000240 // There are many forms of this optimization we can handle, for now, just do
241 // the simple index into a single-dimensional array.
242 //
243 // Require: GEP GV, 0, i {{, constant indices}}
244 if (GEP->getNumOperands() < 3 ||
245 !isa<ConstantInt>(GEP->getOperand(1)) ||
246 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
247 isa<Constant>(GEP->getOperand(2)))
Craig Topperf40110f2014-04-25 05:29:35 +0000248 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000249
250 // Check that indices after the variable are constants and in-range for the
251 // type they index. Collect the indices. This is typically for arrays of
252 // structs.
253 SmallVector<unsigned, 4> LaterIndices;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000254
Chris Lattnerfe741762012-01-31 02:55:06 +0000255 Type *EltTy = Init->getType()->getArrayElementType();
Chris Lattner2188e402010-01-04 07:37:31 +0000256 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
257 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000258 if (!Idx) return nullptr; // Variable index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000259
Chris Lattner2188e402010-01-04 07:37:31 +0000260 uint64_t IdxVal = Idx->getZExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +0000261 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000262
Chris Lattner229907c2011-07-18 04:54:35 +0000263 if (StructType *STy = dyn_cast<StructType>(EltTy))
Chris Lattner2188e402010-01-04 07:37:31 +0000264 EltTy = STy->getElementType(IdxVal);
Chris Lattner229907c2011-07-18 04:54:35 +0000265 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000266 if (IdxVal >= ATy->getNumElements()) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000267 EltTy = ATy->getElementType();
268 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000269 return nullptr; // Unknown type.
Chris Lattner2188e402010-01-04 07:37:31 +0000270 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000271
Chris Lattner2188e402010-01-04 07:37:31 +0000272 LaterIndices.push_back(IdxVal);
273 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000274
Chris Lattner2188e402010-01-04 07:37:31 +0000275 enum { Overdefined = -3, Undefined = -2 };
276
277 // Variables for our state machines.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000278
Chris Lattner2188e402010-01-04 07:37:31 +0000279 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
280 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
281 // and 87 is the second (and last) index. FirstTrueElement is -2 when
282 // undefined, otherwise set to the first true element. SecondTrueElement is
283 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
284 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
285
286 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
287 // form "i != 47 & i != 87". Same state transitions as for true elements.
288 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000289
Chris Lattner2188e402010-01-04 07:37:31 +0000290 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
291 /// define a state machine that triggers for ranges of values that the index
292 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
293 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
294 /// index in the range (inclusive). We use -2 for undefined here because we
295 /// use relative comparisons and don't want 0-1 to match -1.
296 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000297
Chris Lattner2188e402010-01-04 07:37:31 +0000298 // MagicBitvector - This is a magic bitvector where we set a bit if the
299 // comparison is true for element 'i'. If there are 64 elements or less in
300 // the array, this will fully represent all the comparison results.
301 uint64_t MagicBitvector = 0;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000302
Chris Lattner2188e402010-01-04 07:37:31 +0000303 // Scan the array and see if one of our patterns matches.
304 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
Chris Lattnerfe741762012-01-31 02:55:06 +0000305 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
306 Constant *Elt = Init->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +0000307 if (!Elt) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000308
Chris Lattner2188e402010-01-04 07:37:31 +0000309 // If this is indexing an array of structures, get the structure element.
310 if (!LaterIndices.empty())
Jay Foad57aa6362011-07-13 10:26:04 +0000311 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000312
Chris Lattner2188e402010-01-04 07:37:31 +0000313 // If the element is masked, handle it.
314 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000315
Chris Lattner2188e402010-01-04 07:37:31 +0000316 // Find out if the comparison would be true or false for the i'th element.
317 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Justin Bogner99798402016-08-05 01:06:44 +0000318 CompareRHS, DL, &TLI);
Chris Lattner2188e402010-01-04 07:37:31 +0000319 // If the result is undef for this element, ignore it.
320 if (isa<UndefValue>(C)) {
321 // Extend range state machines to cover this element in case there is an
322 // undef in the middle of the range.
323 if (TrueRangeEnd == (int)i-1)
324 TrueRangeEnd = i;
325 if (FalseRangeEnd == (int)i-1)
326 FalseRangeEnd = i;
327 continue;
328 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000329
Chris Lattner2188e402010-01-04 07:37:31 +0000330 // If we can't compute the result for any of the elements, we have to give
331 // up evaluating the entire conditional.
Craig Topperf40110f2014-04-25 05:29:35 +0000332 if (!isa<ConstantInt>(C)) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000333
Chris Lattner2188e402010-01-04 07:37:31 +0000334 // Otherwise, we know if the comparison is true or false for this element,
335 // update our state machines.
336 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
Jim Grosbach129c52a2011-09-30 18:09:53 +0000337
Chris Lattner2188e402010-01-04 07:37:31 +0000338 // State machine for single/double/range index comparison.
339 if (IsTrueForElt) {
340 // Update the TrueElement state machine.
341 if (FirstTrueElement == Undefined)
342 FirstTrueElement = TrueRangeEnd = i; // First true element.
343 else {
344 // Update double-compare state machine.
345 if (SecondTrueElement == Undefined)
346 SecondTrueElement = i;
347 else
348 SecondTrueElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000349
Chris Lattner2188e402010-01-04 07:37:31 +0000350 // Update range state machine.
351 if (TrueRangeEnd == (int)i-1)
352 TrueRangeEnd = i;
353 else
354 TrueRangeEnd = Overdefined;
355 }
356 } else {
357 // Update the FalseElement state machine.
358 if (FirstFalseElement == Undefined)
359 FirstFalseElement = FalseRangeEnd = i; // First false element.
360 else {
361 // Update double-compare state machine.
362 if (SecondFalseElement == Undefined)
363 SecondFalseElement = i;
364 else
365 SecondFalseElement = Overdefined;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000366
Chris Lattner2188e402010-01-04 07:37:31 +0000367 // Update range state machine.
368 if (FalseRangeEnd == (int)i-1)
369 FalseRangeEnd = i;
370 else
371 FalseRangeEnd = Overdefined;
372 }
373 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000374
Chris Lattner2188e402010-01-04 07:37:31 +0000375 // If this element is in range, update our magic bitvector.
376 if (i < 64 && IsTrueForElt)
377 MagicBitvector |= 1ULL << i;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000378
Chris Lattner2188e402010-01-04 07:37:31 +0000379 // If all of our states become overdefined, bail out early. Since the
380 // predicate is expensive, only check it every 8 elements. This is only
381 // really useful for really huge arrays.
382 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
383 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
384 FalseRangeEnd == Overdefined)
Craig Topperf40110f2014-04-25 05:29:35 +0000385 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000386 }
387
388 // Now that we've scanned the entire array, emit our new comparison(s). We
389 // order the state machines in complexity of the generated code.
390 Value *Idx = GEP->getOperand(2);
391
Matt Arsenault5aeae182013-08-19 21:40:31 +0000392 // If the index is larger than the pointer size of the target, truncate the
393 // index down like the GEP would do implicitly. We don't have to do this for
394 // an inbounds GEP because the index can't be out of range.
Matt Arsenault84680622013-09-30 21:11:01 +0000395 if (!GEP->isInBounds()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000396 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
Matt Arsenault84680622013-09-30 21:11:01 +0000397 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
398 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
399 Idx = Builder->CreateTrunc(Idx, IntPtrTy);
400 }
Matt Arsenault5aeae182013-08-19 21:40:31 +0000401
Chris Lattner2188e402010-01-04 07:37:31 +0000402 // If the comparison is only true for one or two elements, emit direct
403 // comparisons.
404 if (SecondTrueElement != Overdefined) {
405 // None true -> false.
406 if (FirstTrueElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000407 return replaceInstUsesWith(ICI, Builder->getFalse());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000408
Chris Lattner2188e402010-01-04 07:37:31 +0000409 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000410
Chris Lattner2188e402010-01-04 07:37:31 +0000411 // True for one element -> 'i == 47'.
412 if (SecondTrueElement == Undefined)
413 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000414
Chris Lattner2188e402010-01-04 07:37:31 +0000415 // True for two elements -> 'i == 47 | i == 72'.
416 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
417 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
418 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
419 return BinaryOperator::CreateOr(C1, C2);
420 }
421
422 // If the comparison is only false for one or two elements, emit direct
423 // comparisons.
424 if (SecondFalseElement != Overdefined) {
425 // None false -> true.
426 if (FirstFalseElement == Undefined)
Sanjay Patel4b198802016-02-01 22:23:39 +0000427 return replaceInstUsesWith(ICI, Builder->getTrue());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000428
Chris Lattner2188e402010-01-04 07:37:31 +0000429 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
430
431 // False for one element -> 'i != 47'.
432 if (SecondFalseElement == Undefined)
433 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000434
Chris Lattner2188e402010-01-04 07:37:31 +0000435 // False for two elements -> 'i != 47 & i != 72'.
436 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
437 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
438 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
439 return BinaryOperator::CreateAnd(C1, C2);
440 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000441
Chris Lattner2188e402010-01-04 07:37:31 +0000442 // If the comparison can be replaced with a range comparison for the elements
443 // where it is true, emit the range check.
444 if (TrueRangeEnd != Overdefined) {
445 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
Jim Grosbach129c52a2011-09-30 18:09:53 +0000446
Chris Lattner2188e402010-01-04 07:37:31 +0000447 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
448 if (FirstTrueElement) {
449 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
450 Idx = Builder->CreateAdd(Idx, Offs);
451 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000452
Chris Lattner2188e402010-01-04 07:37:31 +0000453 Value *End = ConstantInt::get(Idx->getType(),
454 TrueRangeEnd-FirstTrueElement+1);
455 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
456 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000457
Chris Lattner2188e402010-01-04 07:37:31 +0000458 // False range check.
459 if (FalseRangeEnd != Overdefined) {
460 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
461 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
462 if (FirstFalseElement) {
463 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
464 Idx = Builder->CreateAdd(Idx, Offs);
465 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000466
Chris Lattner2188e402010-01-04 07:37:31 +0000467 Value *End = ConstantInt::get(Idx->getType(),
468 FalseRangeEnd-FirstFalseElement);
469 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
470 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000471
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000472 // If a magic bitvector captures the entire comparison state
Chris Lattner2188e402010-01-04 07:37:31 +0000473 // of this load, replace it with computation that does:
474 // ((magic_cst >> i) & 1) != 0
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000475 {
Craig Topperf40110f2014-04-25 05:29:35 +0000476 Type *Ty = nullptr;
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000477
478 // Look for an appropriate type:
479 // - The type of Idx if the magic fits
480 // - The smallest fitting legal type if we have a DataLayout
481 // - Default to i32
482 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
483 Ty = Idx->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000484 else
485 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000486
Craig Topperf40110f2014-04-25 05:29:35 +0000487 if (Ty) {
Arnaud A. de Grandmaisonf364bc62013-03-22 08:25:01 +0000488 Value *V = Builder->CreateIntCast(Idx, Ty, false);
489 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
490 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
491 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
492 }
Chris Lattner2188e402010-01-04 07:37:31 +0000493 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000494
Craig Topperf40110f2014-04-25 05:29:35 +0000495 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +0000496}
497
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000498/// Return a value that can be used to compare the *offset* implied by a GEP to
499/// zero. For example, if we have &A[i], we want to return 'i' for
500/// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
501/// are involved. The above expression would also be legal to codegen as
502/// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
503/// This latter form is less amenable to optimization though, and we are allowed
Chris Lattner2188e402010-01-04 07:37:31 +0000504/// to generate the first by knowing that pointer arithmetic doesn't overflow.
505///
506/// If we can't emit an optimized form for this expression, this returns null.
Jim Grosbach129c52a2011-09-30 18:09:53 +0000507///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000508static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC,
509 const DataLayout &DL) {
Chris Lattner2188e402010-01-04 07:37:31 +0000510 gep_type_iterator GTI = gep_type_begin(GEP);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000511
Chris Lattner2188e402010-01-04 07:37:31 +0000512 // Check to see if this gep only has a single variable index. If so, and if
513 // any constant indices are a multiple of its scale, then we can compute this
514 // in terms of the scale of the variable index. For example, if the GEP
515 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
516 // because the expression will cross zero at the same point.
517 unsigned i, e = GEP->getNumOperands();
518 int64_t Offset = 0;
519 for (i = 1; i != e; ++i, ++GTI) {
520 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
521 // Compute the aggregate offset of constant indices.
522 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000523
Chris Lattner2188e402010-01-04 07:37:31 +0000524 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000525 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000526 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000527 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000528 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000529 Offset += Size*CI->getSExtValue();
530 }
531 } else {
532 // Found our variable index.
533 break;
534 }
535 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000536
Chris Lattner2188e402010-01-04 07:37:31 +0000537 // If there are no variable indices, we must have a constant offset, just
538 // evaluate it the general way.
Craig Topperf40110f2014-04-25 05:29:35 +0000539 if (i == e) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000540
Chris Lattner2188e402010-01-04 07:37:31 +0000541 Value *VariableIdx = GEP->getOperand(i);
542 // Determine the scale factor of the variable element. For example, this is
543 // 4 if the variable index is into an array of i32.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000544 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
Jim Grosbach129c52a2011-09-30 18:09:53 +0000545
Chris Lattner2188e402010-01-04 07:37:31 +0000546 // Verify that there are no other variable indices. If so, emit the hard way.
547 for (++i, ++GTI; i != e; ++i, ++GTI) {
548 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000549 if (!CI) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000550
Chris Lattner2188e402010-01-04 07:37:31 +0000551 // Compute the aggregate offset of constant indices.
552 if (CI->isZero()) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000553
Chris Lattner2188e402010-01-04 07:37:31 +0000554 // Handle a struct index, which adds its field offset to the pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000555 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000556 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
Chris Lattner2188e402010-01-04 07:37:31 +0000557 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000558 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner2188e402010-01-04 07:37:31 +0000559 Offset += Size*CI->getSExtValue();
560 }
561 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000562
Chris Lattner2188e402010-01-04 07:37:31 +0000563 // Okay, we know we have a single variable index, which must be a
564 // pointer/array/vector index. If there is no offset, life is simple, return
565 // the index.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000566 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
Matt Arsenault745101d2013-08-21 19:53:10 +0000567 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
Chris Lattner2188e402010-01-04 07:37:31 +0000568 if (Offset == 0) {
569 // Cast to intptrty in case a truncation occurs. If an extension is needed,
570 // we don't need to bother extending: the extension won't affect where the
571 // computation crosses zero.
Eli Friedman1754a252011-05-18 23:11:30 +0000572 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
Eli Friedman1754a252011-05-18 23:11:30 +0000573 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
574 }
Chris Lattner2188e402010-01-04 07:37:31 +0000575 return VariableIdx;
576 }
Jim Grosbach129c52a2011-09-30 18:09:53 +0000577
Chris Lattner2188e402010-01-04 07:37:31 +0000578 // Otherwise, there is an index. The computation we will do will be modulo
579 // the pointer size, so get it.
580 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000581
Chris Lattner2188e402010-01-04 07:37:31 +0000582 Offset &= PtrSizeMask;
583 VariableScale &= PtrSizeMask;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000584
Chris Lattner2188e402010-01-04 07:37:31 +0000585 // To do this transformation, any constant index must be a multiple of the
586 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
587 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
588 // multiple of the variable scale.
589 int64_t NewOffs = Offset / (int64_t)VariableScale;
590 if (Offset != NewOffs*(int64_t)VariableScale)
Craig Topperf40110f2014-04-25 05:29:35 +0000591 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +0000592
Chris Lattner2188e402010-01-04 07:37:31 +0000593 // Okay, we can do this evaluation. Start by converting the index to intptr.
Chris Lattner2188e402010-01-04 07:37:31 +0000594 if (VariableIdx->getType() != IntPtrTy)
Eli Friedman1754a252011-05-18 23:11:30 +0000595 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
596 true /*Signed*/);
Chris Lattner2188e402010-01-04 07:37:31 +0000597 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Eli Friedman1754a252011-05-18 23:11:30 +0000598 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
Chris Lattner2188e402010-01-04 07:37:31 +0000599}
600
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000601/// Returns true if we can rewrite Start as a GEP with pointer Base
602/// and some integer offset. The nodes that need to be re-written
603/// for this transformation will be added to Explored.
604static bool canRewriteGEPAsOffset(Value *Start, Value *Base,
605 const DataLayout &DL,
606 SetVector<Value *> &Explored) {
607 SmallVector<Value *, 16> WorkList(1, Start);
608 Explored.insert(Base);
609
610 // The following traversal gives us an order which can be used
611 // when doing the final transformation. Since in the final
612 // transformation we create the PHI replacement instructions first,
613 // we don't have to get them in any particular order.
614 //
615 // However, for other instructions we will have to traverse the
616 // operands of an instruction first, which means that we have to
617 // do a post-order traversal.
618 while (!WorkList.empty()) {
619 SetVector<PHINode *> PHIs;
620
621 while (!WorkList.empty()) {
622 if (Explored.size() >= 100)
623 return false;
624
625 Value *V = WorkList.back();
626
627 if (Explored.count(V) != 0) {
628 WorkList.pop_back();
629 continue;
630 }
631
632 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
633 !isa<GEPOperator>(V) && !isa<PHINode>(V))
634 // We've found some value that we can't explore which is different from
635 // the base. Therefore we can't do this transformation.
636 return false;
637
638 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
639 auto *CI = dyn_cast<CastInst>(V);
640 if (!CI->isNoopCast(DL))
641 return false;
642
643 if (Explored.count(CI->getOperand(0)) == 0)
644 WorkList.push_back(CI->getOperand(0));
645 }
646
647 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
648 // We're limiting the GEP to having one index. This will preserve
649 // the original pointer type. We could handle more cases in the
650 // future.
651 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
652 GEP->getType() != Start->getType())
653 return false;
654
655 if (Explored.count(GEP->getOperand(0)) == 0)
656 WorkList.push_back(GEP->getOperand(0));
657 }
658
659 if (WorkList.back() == V) {
660 WorkList.pop_back();
661 // We've finished visiting this node, mark it as such.
662 Explored.insert(V);
663 }
664
665 if (auto *PN = dyn_cast<PHINode>(V)) {
David Majnemercdf28732016-03-19 04:39:52 +0000666 // We cannot transform PHIs on unsplittable basic blocks.
667 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
668 return false;
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000669 Explored.insert(PN);
670 PHIs.insert(PN);
671 }
672 }
673
674 // Explore the PHI nodes further.
675 for (auto *PN : PHIs)
676 for (Value *Op : PN->incoming_values())
677 if (Explored.count(Op) == 0)
678 WorkList.push_back(Op);
679 }
680
681 // Make sure that we can do this. Since we can't insert GEPs in a basic
682 // block before a PHI node, we can't easily do this transformation if
683 // we have PHI node users of transformed instructions.
684 for (Value *Val : Explored) {
685 for (Value *Use : Val->uses()) {
686
687 auto *PHI = dyn_cast<PHINode>(Use);
688 auto *Inst = dyn_cast<Instruction>(Val);
689
690 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
691 Explored.count(PHI) == 0)
692 continue;
693
694 if (PHI->getParent() == Inst->getParent())
695 return false;
696 }
697 }
698 return true;
699}
700
701// Sets the appropriate insert point on Builder where we can add
702// a replacement Instruction for V (if that is possible).
703static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
704 bool Before = true) {
705 if (auto *PHI = dyn_cast<PHINode>(V)) {
706 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
707 return;
708 }
709 if (auto *I = dyn_cast<Instruction>(V)) {
710 if (!Before)
711 I = &*std::next(I->getIterator());
712 Builder.SetInsertPoint(I);
713 return;
714 }
715 if (auto *A = dyn_cast<Argument>(V)) {
716 // Set the insertion point in the entry block.
717 BasicBlock &Entry = A->getParent()->getEntryBlock();
718 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
719 return;
720 }
721 // Otherwise, this is a constant and we don't need to set a new
722 // insertion point.
723 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
724}
725
726/// Returns a re-written value of Start as an indexed GEP using Base as a
727/// pointer.
728static Value *rewriteGEPAsOffset(Value *Start, Value *Base,
729 const DataLayout &DL,
730 SetVector<Value *> &Explored) {
731 // Perform all the substitutions. This is a bit tricky because we can
732 // have cycles in our use-def chains.
733 // 1. Create the PHI nodes without any incoming values.
734 // 2. Create all the other values.
735 // 3. Add the edges for the PHI nodes.
736 // 4. Emit GEPs to get the original pointers.
737 // 5. Remove the original instructions.
738 Type *IndexType = IntegerType::get(
739 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType()));
740
741 DenseMap<Value *, Value *> NewInsts;
742 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
743
744 // Create the new PHI nodes, without adding any incoming values.
745 for (Value *Val : Explored) {
746 if (Val == Base)
747 continue;
748 // Create empty phi nodes. This avoids cyclic dependencies when creating
749 // the remaining instructions.
750 if (auto *PHI = dyn_cast<PHINode>(Val))
751 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
752 PHI->getName() + ".idx", PHI);
753 }
754 IRBuilder<> Builder(Base->getContext());
755
756 // Create all the other instructions.
757 for (Value *Val : Explored) {
758
759 if (NewInsts.find(Val) != NewInsts.end())
760 continue;
761
762 if (auto *CI = dyn_cast<CastInst>(Val)) {
763 NewInsts[CI] = NewInsts[CI->getOperand(0)];
764 continue;
765 }
766 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
767 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
768 : GEP->getOperand(1);
769 setInsertionPoint(Builder, GEP);
770 // Indices might need to be sign extended. GEPs will magically do
771 // this, but we need to do it ourselves here.
772 if (Index->getType()->getScalarSizeInBits() !=
773 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
774 Index = Builder.CreateSExtOrTrunc(
775 Index, NewInsts[GEP->getOperand(0)]->getType(),
776 GEP->getOperand(0)->getName() + ".sext");
777 }
778
779 auto *Op = NewInsts[GEP->getOperand(0)];
780 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero())
781 NewInsts[GEP] = Index;
782 else
783 NewInsts[GEP] = Builder.CreateNSWAdd(
784 Op, Index, GEP->getOperand(0)->getName() + ".add");
785 continue;
786 }
787 if (isa<PHINode>(Val))
788 continue;
789
790 llvm_unreachable("Unexpected instruction type");
791 }
792
793 // Add the incoming values to the PHI nodes.
794 for (Value *Val : Explored) {
795 if (Val == Base)
796 continue;
797 // All the instructions have been created, we can now add edges to the
798 // phi nodes.
799 if (auto *PHI = dyn_cast<PHINode>(Val)) {
800 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
801 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
802 Value *NewIncoming = PHI->getIncomingValue(I);
803
804 if (NewInsts.find(NewIncoming) != NewInsts.end())
805 NewIncoming = NewInsts[NewIncoming];
806
807 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
808 }
809 }
810 }
811
812 for (Value *Val : Explored) {
813 if (Val == Base)
814 continue;
815
816 // Depending on the type, for external users we have to emit
817 // a GEP or a GEP + ptrtoint.
818 setInsertionPoint(Builder, Val, false);
819
820 // If required, create an inttoptr instruction for Base.
821 Value *NewBase = Base;
822 if (!Base->getType()->isPointerTy())
823 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(),
824 Start->getName() + "to.ptr");
825
826 Value *GEP = Builder.CreateInBoundsGEP(
827 Start->getType()->getPointerElementType(), NewBase,
828 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
829
830 if (!Val->getType()->isPointerTy()) {
831 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(),
832 Val->getName() + ".conv");
833 GEP = Cast;
834 }
835 Val->replaceAllUsesWith(GEP);
836 }
837
838 return NewInsts[Start];
839}
840
841/// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
842/// the input Value as a constant indexed GEP. Returns a pair containing
843/// the GEPs Pointer and Index.
844static std::pair<Value *, Value *>
845getAsConstantIndexedAddress(Value *V, const DataLayout &DL) {
846 Type *IndexType = IntegerType::get(V->getContext(),
847 DL.getPointerTypeSizeInBits(V->getType()));
848
849 Constant *Index = ConstantInt::getNullValue(IndexType);
850 while (true) {
851 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
852 // We accept only inbouds GEPs here to exclude the possibility of
853 // overflow.
854 if (!GEP->isInBounds())
855 break;
856 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
857 GEP->getType() == V->getType()) {
858 V = GEP->getOperand(0);
859 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
860 Index = ConstantExpr::getAdd(
861 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType));
862 continue;
863 }
864 break;
865 }
866 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
867 if (!CI->isNoopCast(DL))
868 break;
869 V = CI->getOperand(0);
870 continue;
871 }
872 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
873 if (!CI->isNoopCast(DL))
874 break;
875 V = CI->getOperand(0);
876 continue;
877 }
878 break;
879 }
880 return {V, Index};
881}
882
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000883/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
884/// We can look through PHIs, GEPs and casts in order to determine a common base
885/// between GEPLHS and RHS.
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000886static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
887 ICmpInst::Predicate Cond,
888 const DataLayout &DL) {
889 if (!GEPLHS->hasAllConstantIndices())
890 return nullptr;
891
892 Value *PtrBase, *Index;
893 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL);
894
895 // The set of nodes that will take part in this transformation.
896 SetVector<Value *> Nodes;
897
898 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))
899 return nullptr;
900
901 // We know we can re-write this as
902 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
903 // Since we've only looked through inbouds GEPs we know that we
904 // can't have overflow on either side. We can therefore re-write
905 // this as:
906 // OFFSET1 cmp OFFSET2
907 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes);
908
909 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
910 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
911 // offset. Since Index is the offset of LHS to the base pointer, we will now
912 // compare the offsets instead of comparing the pointers.
913 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
914}
915
Sanjay Patel5f0217f2016-06-05 16:46:18 +0000916/// Fold comparisons between a GEP instruction and something else. At this point
917/// we know that the GEP is on the LHS of the comparison.
Sanjay Patel43395062016-07-21 18:07:40 +0000918Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Chris Lattner2188e402010-01-04 07:37:31 +0000919 ICmpInst::Predicate Cond,
920 Instruction &I) {
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000921 // Don't transform signed compares of GEPs into index compares. Even if the
922 // GEP is inbounds, the final add of the base pointer can have signed overflow
923 // and would change the result of the icmp.
924 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
Benjamin Kramerc7a22fe2012-02-21 13:40:06 +0000925 // the maximum signed value for the pointer type.
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000926 if (ICmpInst::isSigned(Cond))
Craig Topperf40110f2014-04-25 05:29:35 +0000927 return nullptr;
Benjamin Kramer6ee86902012-02-21 13:31:09 +0000928
Matt Arsenault44f60d02014-06-09 19:20:29 +0000929 // Look through bitcasts and addrspacecasts. We do not however want to remove
930 // 0 GEPs.
931 if (!isa<GetElementPtrInst>(RHS))
932 RHS = RHS->stripPointerCasts();
Chris Lattner2188e402010-01-04 07:37:31 +0000933
934 Value *PtrBase = GEPLHS->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000935 if (PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner2188e402010-01-04 07:37:31 +0000936 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
937 // This transformation (ignoring the base and scales) is valid because we
938 // know pointers can't overflow since the gep is inbounds. See if we can
939 // output an optimized form.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000940 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL);
Jim Grosbach129c52a2011-09-30 18:09:53 +0000941
Chris Lattner2188e402010-01-04 07:37:31 +0000942 // If not, synthesize the offset the hard way.
Craig Topperf40110f2014-04-25 05:29:35 +0000943 if (!Offset)
Chris Lattner2188e402010-01-04 07:37:31 +0000944 Offset = EmitGEPOffset(GEPLHS);
945 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
946 Constant::getNullValue(Offset->getType()));
947 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
948 // If the base pointers are different, but the indices are the same, just
949 // compare the base pointer.
950 if (PtrBase != GEPRHS->getOperand(0)) {
951 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
952 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
953 GEPRHS->getOperand(0)->getType();
954 if (IndicesTheSame)
955 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
956 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
957 IndicesTheSame = false;
958 break;
959 }
960
961 // If all indices are the same, just compare the base pointers.
962 if (IndicesTheSame)
David Majnemer5953d372013-06-29 10:28:04 +0000963 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +0000964
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000965 // If we're comparing GEPs with two base pointers that only differ in type
966 // and both GEPs have only constant indices or just one use, then fold
967 // the compare with the adjusted indices.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000968 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000969 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
970 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
971 PtrBase->stripPointerCasts() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000972 GEPRHS->getOperand(0)->stripPointerCasts()) {
Matt Arsenault44f60d02014-06-09 19:20:29 +0000973 Value *LOffset = EmitGEPOffset(GEPLHS);
974 Value *ROffset = EmitGEPOffset(GEPRHS);
975
976 // If we looked through an addrspacecast between different sized address
977 // spaces, the LHS and RHS pointers are different sized
978 // integers. Truncate to the smaller one.
979 Type *LHSIndexTy = LOffset->getType();
980 Type *RHSIndexTy = ROffset->getType();
981 if (LHSIndexTy != RHSIndexTy) {
982 if (LHSIndexTy->getPrimitiveSizeInBits() <
983 RHSIndexTy->getPrimitiveSizeInBits()) {
984 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy);
985 } else
986 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy);
987 }
988
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000989 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
Matt Arsenault44f60d02014-06-09 19:20:29 +0000990 LOffset, ROffset);
Sanjay Patel4b198802016-02-01 22:23:39 +0000991 return replaceInstUsesWith(I, Cmp);
Benjamin Kramer7adb1892012-02-20 15:07:47 +0000992 }
993
Chris Lattner2188e402010-01-04 07:37:31 +0000994 // Otherwise, the base pointers are different and the indices are
Silviu Barangaf29dfd32016-01-15 15:52:05 +0000995 // different. Try convert this to an indexed compare by looking through
996 // PHIs/casts.
997 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +0000998 }
999
1000 // If one of the GEPs has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001001 if (GEPLHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001002 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
David Majnemer92a8a7d2013-06-29 09:45:35 +00001003 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner2188e402010-01-04 07:37:31 +00001004
1005 // If the other GEP has all zero indices, recurse.
Benjamin Kramerd0993e02014-07-07 11:01:16 +00001006 if (GEPRHS->hasAllZeroIndices())
Sanjay Patel43395062016-07-21 18:07:40 +00001007 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner2188e402010-01-04 07:37:31 +00001008
Stuart Hastings66a82b92011-05-14 05:55:10 +00001009 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
Chris Lattner2188e402010-01-04 07:37:31 +00001010 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
1011 // If the GEPs only differ by one index, compare it.
1012 unsigned NumDifferences = 0; // Keep track of # differences.
1013 unsigned DiffOperand = 0; // The operand that differs.
1014 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
1015 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
1016 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
1017 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
1018 // Irreconcilable differences.
1019 NumDifferences = 2;
1020 break;
1021 } else {
1022 if (NumDifferences++) break;
1023 DiffOperand = i;
1024 }
1025 }
1026
Rafael Espindolaa7bbc0b2013-06-06 17:03:05 +00001027 if (NumDifferences == 0) // SAME GEP?
Sanjay Patel4b198802016-02-01 22:23:39 +00001028 return replaceInstUsesWith(I, // No comparison is needed here.
Jakub Staszakbddea112013-06-06 20:18:46 +00001029 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
Chris Lattner2188e402010-01-04 07:37:31 +00001030
Stuart Hastings66a82b92011-05-14 05:55:10 +00001031 else if (NumDifferences == 1 && GEPsInBounds) {
Chris Lattner2188e402010-01-04 07:37:31 +00001032 Value *LHSV = GEPLHS->getOperand(DiffOperand);
1033 Value *RHSV = GEPRHS->getOperand(DiffOperand);
1034 // Make sure we do a signed comparison here.
1035 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
1036 }
1037 }
1038
1039 // Only lower this if the icmp is the only user of the GEP or if we expect
1040 // the result to fold to a constant!
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001041 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner2188e402010-01-04 07:37:31 +00001042 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1043 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
1044 Value *L = EmitGEPOffset(GEPLHS);
1045 Value *R = EmitGEPOffset(GEPRHS);
1046 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1047 }
1048 }
Silviu Barangaf29dfd32016-01-15 15:52:05 +00001049
1050 // Try convert this to an indexed compare by looking through PHIs/casts as a
1051 // last resort.
1052 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
Chris Lattner2188e402010-01-04 07:37:31 +00001053}
1054
Pete Cooper980a9352016-08-12 17:13:28 +00001055Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI,
1056 const AllocaInst *Alloca,
1057 const Value *Other) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001058 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1059
1060 // It would be tempting to fold away comparisons between allocas and any
1061 // pointer not based on that alloca (e.g. an argument). However, even
1062 // though such pointers cannot alias, they can still compare equal.
1063 //
1064 // But LLVM doesn't specify where allocas get their memory, so if the alloca
1065 // doesn't escape we can argue that it's impossible to guess its value, and we
1066 // can therefore act as if any such guesses are wrong.
1067 //
1068 // The code below checks that the alloca doesn't escape, and that it's only
1069 // used in a comparison once (the current instruction). The
1070 // single-comparison-use condition ensures that we're trivially folding all
1071 // comparisons against the alloca consistently, and avoids the risk of
1072 // erroneously folding a comparison of the pointer with itself.
1073
1074 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1075
Pete Cooper980a9352016-08-12 17:13:28 +00001076 SmallVector<const Use *, 32> Worklist;
1077 for (const Use &U : Alloca->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001078 if (Worklist.size() >= MaxIter)
1079 return nullptr;
1080 Worklist.push_back(&U);
1081 }
1082
1083 unsigned NumCmps = 0;
1084 while (!Worklist.empty()) {
1085 assert(Worklist.size() <= MaxIter);
Pete Cooper980a9352016-08-12 17:13:28 +00001086 const Use *U = Worklist.pop_back_val();
1087 const Value *V = U->getUser();
Hans Wennborgf1f36512015-10-07 00:20:07 +00001088 --MaxIter;
1089
1090 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1091 isa<SelectInst>(V)) {
1092 // Track the uses.
1093 } else if (isa<LoadInst>(V)) {
1094 // Loading from the pointer doesn't escape it.
1095 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001096 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001097 // Storing *to* the pointer is fine, but storing the pointer escapes it.
1098 if (SI->getValueOperand() == U->get())
1099 return nullptr;
1100 continue;
1101 } else if (isa<ICmpInst>(V)) {
1102 if (NumCmps++)
1103 return nullptr; // Found more than one cmp.
1104 continue;
Pete Cooper980a9352016-08-12 17:13:28 +00001105 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001106 switch (Intrin->getIntrinsicID()) {
1107 // These intrinsics don't escape or compare the pointer. Memset is safe
1108 // because we don't allow ptrtoint. Memcpy and memmove are safe because
1109 // we don't allow stores, so src cannot point to V.
1110 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1111 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
1112 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1113 continue;
1114 default:
1115 return nullptr;
1116 }
1117 } else {
1118 return nullptr;
1119 }
Pete Cooper980a9352016-08-12 17:13:28 +00001120 for (const Use &U : V->uses()) {
Hans Wennborgf1f36512015-10-07 00:20:07 +00001121 if (Worklist.size() >= MaxIter)
1122 return nullptr;
1123 Worklist.push_back(&U);
1124 }
1125 }
1126
1127 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001128 return replaceInstUsesWith(
Hans Wennborgf1f36512015-10-07 00:20:07 +00001129 ICI,
1130 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate())));
1131}
1132
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001133/// Fold "icmp pred (X+CI), X".
Sanjay Patel43395062016-07-21 18:07:40 +00001134Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI,
1135 Value *X, ConstantInt *CI,
1136 ICmpInst::Predicate Pred) {
Chris Lattner2188e402010-01-04 07:37:31 +00001137 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001138 // so the values can never be equal. Similarly for all other "or equals"
Chris Lattner2188e402010-01-04 07:37:31 +00001139 // operators.
Jim Grosbach129c52a2011-09-30 18:09:53 +00001140
Chris Lattner8c92b572010-01-08 17:48:19 +00001141 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
Chris Lattner2188e402010-01-04 07:37:31 +00001142 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1143 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1144 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00001145 Value *R =
Chris Lattner8c92b572010-01-08 17:48:19 +00001146 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
Chris Lattner2188e402010-01-04 07:37:31 +00001147 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1148 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001149
Chris Lattner2188e402010-01-04 07:37:31 +00001150 // (X+1) >u X --> X <u (0-1) --> X != 255
1151 // (X+2) >u X --> X <u (0-2) --> X <u 254
1152 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Duncan Sandse5220012011-02-17 07:46:37 +00001153 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
Chris Lattner2188e402010-01-04 07:37:31 +00001154 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001155
Chris Lattner2188e402010-01-04 07:37:31 +00001156 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
1157 ConstantInt *SMax = ConstantInt::get(X->getContext(),
1158 APInt::getSignedMaxValue(BitWidth));
1159
1160 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1161 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1162 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1163 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1164 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1165 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Duncan Sandse5220012011-02-17 07:46:37 +00001166 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
Chris Lattner2188e402010-01-04 07:37:31 +00001167 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001168
Chris Lattner2188e402010-01-04 07:37:31 +00001169 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1170 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1171 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1172 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1173 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1174 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Jim Grosbach129c52a2011-09-30 18:09:53 +00001175
Chris Lattner2188e402010-01-04 07:37:31 +00001176 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
Jakub Staszakbddea112013-06-06 20:18:46 +00001177 Constant *C = Builder->getInt(CI->getValue()-1);
Chris Lattner2188e402010-01-04 07:37:31 +00001178 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
1179}
1180
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001181/// Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS and CmpRHS are
1182/// both known to be integer constants.
Sanjay Patela3f4f082016-08-16 17:54:36 +00001183Instruction *InstCombiner::foldICmpDivConstConst(ICmpInst &ICI,
1184 BinaryOperator *DivI,
1185 ConstantInt *DivRHS) {
Chris Lattner2188e402010-01-04 07:37:31 +00001186 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
1187 const APInt &CmpRHSV = CmpRHS->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001188
1189 // FIXME: If the operand types don't match the type of the divide
Chris Lattner2188e402010-01-04 07:37:31 +00001190 // then don't attempt this transform. The code below doesn't have the
1191 // logic to deal with a signed divide and an unsigned compare (and
Jim Grosbach129c52a2011-09-30 18:09:53 +00001192 // vice versa). This is because (x /s C1) <s C2 produces different
Chris Lattner2188e402010-01-04 07:37:31 +00001193 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
Jim Grosbach129c52a2011-09-30 18:09:53 +00001194 // (x /u C1) <u C2. Simply casting the operands and result won't
1195 // work. :( The if statement below tests that condition and bails
Chris Lattner98457102011-02-10 05:23:05 +00001196 // if it finds it.
Chris Lattner2188e402010-01-04 07:37:31 +00001197 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
1198 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Craig Topperf40110f2014-04-25 05:29:35 +00001199 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00001200 if (DivRHS->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +00001201 return nullptr; // The ProdOV computation fails on divide by zero.
Chris Lattner2188e402010-01-04 07:37:31 +00001202 if (DivIsSigned && DivRHS->isAllOnesValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001203 return nullptr; // The overflow computation also screws up here
Chris Lattner43273af2011-02-13 08:07:21 +00001204 if (DivRHS->isOne()) {
1205 // This eliminates some funny cases with INT_MIN.
1206 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X.
1207 return &ICI;
1208 }
Chris Lattner2188e402010-01-04 07:37:31 +00001209
1210 // Compute Prod = CI * DivRHS. We are essentially solving an equation
Jim Grosbach129c52a2011-09-30 18:09:53 +00001211 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
1212 // C2 (CI). By solving for X we can turn this into a range check
1213 // instead of computing a divide.
Chris Lattner2188e402010-01-04 07:37:31 +00001214 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
1215
1216 // Determine if the product overflows by seeing if the product is
1217 // not equal to the divide. Make sure we do the same kind of divide
Jim Grosbach129c52a2011-09-30 18:09:53 +00001218 // as in the LHS instruction that we're folding.
Chris Lattner2188e402010-01-04 07:37:31 +00001219 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
1220 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
1221
1222 // Get the ICmp opcode
1223 ICmpInst::Predicate Pred = ICI.getPredicate();
1224
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001225 // If the division is known to be exact, then there is no remainder from the
1226 // divide, so the covered range size is unit, otherwise it is the divisor.
Chris Lattner98457102011-02-10 05:23:05 +00001227 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001228
Chris Lattner2188e402010-01-04 07:37:31 +00001229 // Figure out the interval that is being checked. For example, a comparison
Jim Grosbach129c52a2011-09-30 18:09:53 +00001230 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
Chris Lattner2188e402010-01-04 07:37:31 +00001231 // Compute this interval based on the constants involved and the signedness of
1232 // the compare/divide. This computes a half-open interval, keeping track of
1233 // whether either value in the interval overflows. After analysis each
1234 // overflow variable is set to 0 if it's corresponding bound variable is valid
1235 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
1236 int LoOverflow = 0, HiOverflow = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001237 Constant *LoBound = nullptr, *HiBound = nullptr;
Chris Lattner98457102011-02-10 05:23:05 +00001238
Chris Lattner2188e402010-01-04 07:37:31 +00001239 if (!DivIsSigned) { // udiv
1240 // e.g. X/5 op 3 --> [15, 20)
1241 LoBound = Prod;
1242 HiOverflow = LoOverflow = ProdOV;
Chris Lattner98457102011-02-10 05:23:05 +00001243 if (!HiOverflow) {
1244 // If this is not an exact divide, then many values in the range collapse
1245 // to the same result value.
1246 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
1247 }
Chris Lattner2188e402010-01-04 07:37:31 +00001248 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
1249 if (CmpRHSV == 0) { // (X / pos) op 0
1250 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner98457102011-02-10 05:23:05 +00001251 LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
1252 HiBound = RangeSize;
Chris Lattner2188e402010-01-04 07:37:31 +00001253 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
1254 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
1255 HiOverflow = LoOverflow = ProdOV;
1256 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001257 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001258 } else { // (X / pos) op neg
1259 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
1260 HiBound = AddOne(Prod);
1261 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
1262 if (!LoOverflow) {
Chris Lattner98457102011-02-10 05:23:05 +00001263 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001264 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattner98457102011-02-10 05:23:05 +00001265 }
Chris Lattner2188e402010-01-04 07:37:31 +00001266 }
Chris Lattnerb1a15122011-07-15 06:08:15 +00001267 } else if (DivRHS->isNegative()) { // Divisor is < 0.
Chris Lattner98457102011-02-10 05:23:05 +00001268 if (DivI->isExact())
1269 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001270 if (CmpRHSV == 0) { // (X / neg) op 0
1271 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner98457102011-02-10 05:23:05 +00001272 LoBound = AddOne(RangeSize);
1273 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
Chris Lattner2188e402010-01-04 07:37:31 +00001274 if (HiBound == DivRHS) { // -INTMIN = INTMIN
1275 HiOverflow = 1; // [INTMIN+1, overflow)
Craig Topperf40110f2014-04-25 05:29:35 +00001276 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN
Chris Lattner2188e402010-01-04 07:37:31 +00001277 }
1278 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
1279 // e.g. X/-5 op 3 --> [-19, -14)
1280 HiBound = AddOne(Prod);
1281 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
1282 if (!LoOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001283 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
Chris Lattner2188e402010-01-04 07:37:31 +00001284 } else { // (X / neg) op neg
1285 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
1286 LoOverflow = HiOverflow = ProdOV;
1287 if (!HiOverflow)
Chris Lattner98457102011-02-10 05:23:05 +00001288 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
Chris Lattner2188e402010-01-04 07:37:31 +00001289 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001290
Chris Lattner2188e402010-01-04 07:37:31 +00001291 // Dividing by a negative swaps the condition. LT <-> GT
1292 Pred = ICmpInst::getSwappedPredicate(Pred);
1293 }
1294
1295 Value *X = DivI->getOperand(0);
1296 switch (Pred) {
1297 default: llvm_unreachable("Unhandled icmp opcode!");
1298 case ICmpInst::ICMP_EQ:
1299 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001300 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner067459c2010-03-05 08:46:26 +00001301 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001302 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1303 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001304 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001305 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1306 ICmpInst::ICMP_ULT, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001307 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner98457102011-02-10 05:23:05 +00001308 DivIsSigned, true));
Chris Lattner2188e402010-01-04 07:37:31 +00001309 case ICmpInst::ICMP_NE:
1310 if (LoOverflow && HiOverflow)
Sanjay Patel4b198802016-02-01 22:23:39 +00001311 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner067459c2010-03-05 08:46:26 +00001312 if (HiOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001313 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
1314 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner067459c2010-03-05 08:46:26 +00001315 if (LoOverflow)
Chris Lattner2188e402010-01-04 07:37:31 +00001316 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
1317 ICmpInst::ICMP_UGE, X, HiBound);
Sanjay Patel4b198802016-02-01 22:23:39 +00001318 return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
Chris Lattner067459c2010-03-05 08:46:26 +00001319 DivIsSigned, false));
Chris Lattner2188e402010-01-04 07:37:31 +00001320 case ICmpInst::ICMP_ULT:
1321 case ICmpInst::ICMP_SLT:
1322 if (LoOverflow == +1) // Low bound is greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001323 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001324 if (LoOverflow == -1) // Low bound is less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001325 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00001326 return new ICmpInst(Pred, X, LoBound);
1327 case ICmpInst::ICMP_UGT:
1328 case ICmpInst::ICMP_SGT:
1329 if (HiOverflow == +1) // High bound greater than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001330 return replaceInstUsesWith(ICI, Builder->getFalse());
Chris Lattner98457102011-02-10 05:23:05 +00001331 if (HiOverflow == -1) // High bound less than input range.
Sanjay Patel4b198802016-02-01 22:23:39 +00001332 return replaceInstUsesWith(ICI, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00001333 if (Pred == ICmpInst::ICMP_UGT)
1334 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner98457102011-02-10 05:23:05 +00001335 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner2188e402010-01-04 07:37:31 +00001336 }
1337}
1338
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001339/// Handle "icmp(([al]shr X, cst1), cst2)".
Sanjay Patela3f4f082016-08-16 17:54:36 +00001340Instruction *InstCombiner::foldICmpShrConstConst(ICmpInst &ICI,
1341 BinaryOperator *Shr,
1342 ConstantInt *ShAmt) {
Chris Lattnerd369f572011-02-13 07:43:07 +00001343 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00001344
Chris Lattnerd369f572011-02-13 07:43:07 +00001345 // Check that the shift amount is in range. If not, don't perform
1346 // undefined shifts. When the shift is visited it will be
1347 // simplified.
1348 uint32_t TypeBits = CmpRHSV.getBitWidth();
1349 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattner43273af2011-02-13 08:07:21 +00001350 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001351 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001352
Chris Lattner43273af2011-02-13 08:07:21 +00001353 if (!ICI.isEquality()) {
1354 // If we have an unsigned comparison and an ashr, we can't simplify this.
1355 // Similarly for signed comparisons with lshr.
1356 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
Craig Topperf40110f2014-04-25 05:29:35 +00001357 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001358
Eli Friedman865866e2011-05-25 23:26:20 +00001359 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
1360 // by a power of 2. Since we already have logic to simplify these,
1361 // transform to div and then simplify the resultant comparison.
Chris Lattner43273af2011-02-13 08:07:21 +00001362 if (Shr->getOpcode() == Instruction::AShr &&
Eli Friedman865866e2011-05-25 23:26:20 +00001363 (!Shr->isExact() || ShAmtVal == TypeBits - 1))
Craig Topperf40110f2014-04-25 05:29:35 +00001364 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001365
Chris Lattner43273af2011-02-13 08:07:21 +00001366 // Revisit the shift (to delete it).
1367 Worklist.Add(Shr);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001368
Chris Lattner43273af2011-02-13 08:07:21 +00001369 Constant *DivCst =
1370 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
Jim Grosbach129c52a2011-09-30 18:09:53 +00001371
Chris Lattner43273af2011-02-13 08:07:21 +00001372 Value *Tmp =
1373 Shr->getOpcode() == Instruction::AShr ?
1374 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1375 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
Jim Grosbach129c52a2011-09-30 18:09:53 +00001376
Chris Lattner43273af2011-02-13 08:07:21 +00001377 ICI.setOperand(0, Tmp);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001378
Chris Lattner43273af2011-02-13 08:07:21 +00001379 // If the builder folded the binop, just return it.
1380 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
Craig Topperf40110f2014-04-25 05:29:35 +00001381 if (!TheDiv)
Chris Lattner43273af2011-02-13 08:07:21 +00001382 return &ICI;
Jim Grosbach129c52a2011-09-30 18:09:53 +00001383
Chris Lattner43273af2011-02-13 08:07:21 +00001384 // Otherwise, fold this div/compare.
1385 assert(TheDiv->getOpcode() == Instruction::SDiv ||
1386 TheDiv->getOpcode() == Instruction::UDiv);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001387
Sanjay Patela3f4f082016-08-16 17:54:36 +00001388 Instruction *Res =
1389 foldICmpDivConstConst(ICI, TheDiv, cast<ConstantInt>(DivCst));
Chris Lattner43273af2011-02-13 08:07:21 +00001390 assert(Res && "This div/cst should have folded!");
1391 return Res;
1392 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001393
Chris Lattnerd369f572011-02-13 07:43:07 +00001394 // If we are comparing against bits always shifted out, the
1395 // comparison cannot succeed.
1396 APInt Comp = CmpRHSV << ShAmtVal;
Jakub Staszakbddea112013-06-06 20:18:46 +00001397 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
Chris Lattnerd369f572011-02-13 07:43:07 +00001398 if (Shr->getOpcode() == Instruction::LShr)
1399 Comp = Comp.lshr(ShAmtVal);
1400 else
1401 Comp = Comp.ashr(ShAmtVal);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001402
Chris Lattnerd369f572011-02-13 07:43:07 +00001403 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1404 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Jakub Staszakbddea112013-06-06 20:18:46 +00001405 Constant *Cst = Builder->getInt1(IsICMP_NE);
Sanjay Patel4b198802016-02-01 22:23:39 +00001406 return replaceInstUsesWith(ICI, Cst);
Chris Lattnerd369f572011-02-13 07:43:07 +00001407 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00001408
Chris Lattnerd369f572011-02-13 07:43:07 +00001409 // Otherwise, check to see if the bits shifted out are known to be zero.
1410 // If so, we can compare against the unshifted value:
1411 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Chris Lattner9bd7fdf2011-02-13 18:30:09 +00001412 if (Shr->hasOneUse() && Shr->isExact())
Chris Lattnerd369f572011-02-13 07:43:07 +00001413 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001414
Chris Lattnerd369f572011-02-13 07:43:07 +00001415 if (Shr->hasOneUse()) {
1416 // Otherwise strength reduce the shift into an and.
1417 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Jakub Staszakbddea112013-06-06 20:18:46 +00001418 Constant *Mask = Builder->getInt(Val);
Jim Grosbach129c52a2011-09-30 18:09:53 +00001419
Chris Lattnerd369f572011-02-13 07:43:07 +00001420 Value *And = Builder->CreateAnd(Shr->getOperand(0),
1421 Mask, Shr->getName()+".mask");
1422 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1423 }
Craig Topperf40110f2014-04-25 05:29:35 +00001424 return nullptr;
Chris Lattnerd369f572011-02-13 07:43:07 +00001425}
1426
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001427/// Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" ->
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001428/// (icmp eq/ne A, Log2(const2/const1)) ->
1429/// (icmp eq/ne A, Log2(const2) - Log2(const1)).
Sanjay Patel43395062016-07-21 18:07:40 +00001430Instruction *InstCombiner::foldICmpCstShrConst(ICmpInst &I, Value *Op, Value *A,
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001431 ConstantInt *CI1,
1432 ConstantInt *CI2) {
1433 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1434
1435 auto getConstant = [&I, this](bool IsTrue) {
1436 if (I.getPredicate() == I.ICMP_NE)
1437 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001438 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001439 };
1440
1441 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1442 if (I.getPredicate() == I.ICMP_NE)
1443 Pred = CmpInst::getInversePredicate(Pred);
1444 return new ICmpInst(Pred, LHS, RHS);
1445 };
1446
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001447 const APInt &AP1 = CI1->getValue();
1448 const APInt &AP2 = CI2->getValue();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001449
David Majnemer2abb8182014-10-25 07:13:13 +00001450 // Don't bother doing any work for cases which InstSimplify handles.
1451 if (AP2 == 0)
1452 return nullptr;
1453 bool IsAShr = isa<AShrOperator>(Op);
1454 if (IsAShr) {
1455 if (AP2.isAllOnesValue())
1456 return nullptr;
1457 if (AP2.isNegative() != AP1.isNegative())
1458 return nullptr;
1459 if (AP2.sgt(AP1))
1460 return nullptr;
1461 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001462
David Majnemerd2056022014-10-21 19:51:55 +00001463 if (!AP1)
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001464 // 'A' must be large enough to shift out the highest set bit.
1465 return getICmp(I.ICMP_UGT, A,
1466 ConstantInt::get(A->getType(), AP2.logBase2()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001467
David Majnemerd2056022014-10-21 19:51:55 +00001468 if (AP1 == AP2)
1469 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001470
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001471 int Shift;
David Majnemerd2056022014-10-21 19:51:55 +00001472 if (IsAShr && AP1.isNegative())
David Majnemere5977eb2015-09-19 00:48:26 +00001473 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
Andrea Di Biagio5b92b492014-09-17 11:32:31 +00001474 else
David Majnemere5977eb2015-09-19 00:48:26 +00001475 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001476
David Majnemerd2056022014-10-21 19:51:55 +00001477 if (Shift > 0) {
David Majnemere5977eb2015-09-19 00:48:26 +00001478 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1479 // There are multiple solutions if we are comparing against -1 and the LHS
David Majnemer47ce0b82015-09-19 00:48:31 +00001480 // of the ashr is not a power of two.
David Majnemere5977eb2015-09-19 00:48:26 +00001481 if (AP1.isAllOnesValue() && !AP2.isPowerOf2())
1482 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
David Majnemerd2056022014-10-21 19:51:55 +00001483 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
David Majnemere5977eb2015-09-19 00:48:26 +00001484 } else if (AP1 == AP2.lshr(Shift)) {
1485 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1486 }
David Majnemerd2056022014-10-21 19:51:55 +00001487 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00001488 // Shifting const2 will never be equal to const1.
1489 return getConstant(false);
1490}
Chris Lattner2188e402010-01-04 07:37:31 +00001491
Sanjay Patel5f0217f2016-06-05 16:46:18 +00001492/// Handle "(icmp eq/ne (shl const2, A), const1)" ->
David Majnemer59939ac2014-10-19 08:23:08 +00001493/// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)).
Sanjay Patel43395062016-07-21 18:07:40 +00001494Instruction *InstCombiner::foldICmpCstShlConst(ICmpInst &I, Value *Op, Value *A,
1495 ConstantInt *CI1,
1496 ConstantInt *CI2) {
David Majnemer59939ac2014-10-19 08:23:08 +00001497 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1498
1499 auto getConstant = [&I, this](bool IsTrue) {
1500 if (I.getPredicate() == I.ICMP_NE)
1501 IsTrue = !IsTrue;
Sanjay Patel4b198802016-02-01 22:23:39 +00001502 return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue));
David Majnemer59939ac2014-10-19 08:23:08 +00001503 };
1504
1505 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1506 if (I.getPredicate() == I.ICMP_NE)
1507 Pred = CmpInst::getInversePredicate(Pred);
1508 return new ICmpInst(Pred, LHS, RHS);
1509 };
1510
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001511 const APInt &AP1 = CI1->getValue();
1512 const APInt &AP2 = CI2->getValue();
David Majnemer59939ac2014-10-19 08:23:08 +00001513
David Majnemer2abb8182014-10-25 07:13:13 +00001514 // Don't bother doing any work for cases which InstSimplify handles.
1515 if (AP2 == 0)
1516 return nullptr;
David Majnemer59939ac2014-10-19 08:23:08 +00001517
1518 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1519
1520 if (!AP1 && AP2TrailingZeros != 0)
1521 return getICmp(I.ICMP_UGE, A,
1522 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1523
1524 if (AP1 == AP2)
1525 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1526
1527 // Get the distance between the lowest bits that are set.
1528 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1529
1530 if (Shift > 0 && AP2.shl(Shift) == AP1)
1531 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1532
1533 // Shifting const2 will never be equal to const1.
1534 return getConstant(false);
1535}
1536
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001537/// Fold icmp (trunc X, Y), C.
1538Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp,
1539 Instruction *Trunc,
1540 const APInt *C) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001541 // FIXME: This check restricts all folds under here to scalar types.
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001542 ConstantInt *RHS = dyn_cast<ConstantInt>(Cmp.getOperand(1));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001543 if (!RHS)
1544 return nullptr;
1545
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001546 ICmpInst::Predicate Pred = Cmp.getPredicate();
1547 Value *X = Trunc->getOperand(0);
1548 if (RHS->isOne() && C->getBitWidth() > 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001549 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1550 Value *V = nullptr;
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001551 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001552 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1553 ConstantInt::get(V->getType(), 1));
1554 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001555
1556 if (Cmp.isEquality() && Trunc->hasOneUse()) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001557 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1558 // of the high bits truncated out of x are known.
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001559 unsigned DstBits = Trunc->getType()->getPrimitiveSizeInBits(),
1560 SrcBits = X->getType()->getPrimitiveSizeInBits();
Sanjay Patela3f4f082016-08-16 17:54:36 +00001561 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001562 computeKnownBits(X, KnownZero, KnownOne, 0, &Cmp);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001563
1564 // If all the high bits are known, we can do this xform.
1565 if ((KnownZero | KnownOne).countLeadingOnes() >= SrcBits - DstBits) {
1566 // Pull in the high bits from known-ones set.
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001567 APInt NewRHS = C->zext(SrcBits);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001568 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001569 return new ICmpInst(Pred, X, Builder->getInt(NewRHS));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001570 }
1571 }
Sanjay Patel5f4ce4e2016-08-18 20:25:16 +00001572
Sanjay Patela3f4f082016-08-16 17:54:36 +00001573 return nullptr;
1574}
1575
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001576/// Fold icmp (xor X, Y), C.
1577Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp, Instruction *Xor,
1578 const APInt *C) {
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001579 Value *X = Xor->getOperand(0);
1580 Value *Y = Xor->getOperand(1);
Sanjay Pateldaffec912016-08-17 19:45:18 +00001581 const APInt *XorC;
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001582 if (!match(Y, m_APInt(XorC)))
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001583 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001584
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001585 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1586 // fold the xor.
1587 ICmpInst::Predicate Pred = Cmp.getPredicate();
1588 if ((Pred == ICmpInst::ICMP_SLT && *C == 0) ||
1589 (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001590
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001591 // If the sign bit of the XorCst is not set, there is no change to
1592 // the operation, just stop using the Xor.
Sanjay Pateldaffec912016-08-17 19:45:18 +00001593 if (!XorC->isNegative()) {
1594 Cmp.setOperand(0, X);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001595 Worklist.Add(Xor);
1596 return &Cmp;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001597 }
1598
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001599 // Was the old condition true if the operand is positive?
1600 bool isTrueIfPositive = Pred == ICmpInst::ICMP_SGT;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001601
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001602 // If so, the new one isn't.
1603 isTrueIfPositive ^= true;
Sanjay Patela3f4f082016-08-16 17:54:36 +00001604
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001605 Constant *CmpConstant = cast<Constant>(Cmp.getOperand(1));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001606 if (isTrueIfPositive)
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001607 return new ICmpInst(ICmpInst::ICMP_SGT, X, SubOne(CmpConstant));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001608 else
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001609 return new ICmpInst(ICmpInst::ICMP_SLT, X, AddOne(CmpConstant));
Sanjay Patela3f4f082016-08-16 17:54:36 +00001610 }
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001611
1612 if (Xor->hasOneUse()) {
Sanjay Pateldaffec912016-08-17 19:45:18 +00001613 // (icmp u/s (xor X SignBit), C) -> (icmp s/u X, (xor C SignBit))
1614 if (!Cmp.isEquality() && XorC->isSignBit()) {
1615 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1616 : Cmp.getSignedPredicate();
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001617 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001618 }
1619
Sanjay Pateldaffec912016-08-17 19:45:18 +00001620 // (icmp u/s (xor X ~SignBit), C) -> (icmp s/u X, (xor C ~SignBit))
1621 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1622 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate()
1623 : Cmp.getSignedPredicate();
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001624 Pred = Cmp.getSwappedPredicate(Pred);
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001625 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC));
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001626 }
1627 }
1628
1629 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1630 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001631 if (Pred == ICmpInst::ICMP_UGT && *XorC == ~(*C) && (*C + 1).isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001632 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001633
1634 // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1635 // iff -C is a power of 2
Sanjay Pateldaffec912016-08-17 19:45:18 +00001636 if (Pred == ICmpInst::ICMP_ULT && *XorC == -(*C) && C->isPowerOf2())
Sanjay Patel4c5e60d2016-08-18 14:10:48 +00001637 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
Sanjay Patel6d5f4482016-08-17 19:23:42 +00001638
Sanjay Patela3f4f082016-08-16 17:54:36 +00001639 return nullptr;
1640}
1641
1642Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &ICI, Instruction *LHSI,
1643 const APInt *RHSV) {
1644 // FIXME: This check restricts all folds under here to scalar types.
1645 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
1646 if (!RHS)
1647 return nullptr;
1648
1649 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1650 LHSI->getOperand(0)->hasOneUse()) {
1651 ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
1652
1653 // If the LHS is an AND of a truncating cast, we can widen the
1654 // and/compare to be the input width without changing the value
1655 // produced, eliminating a cast.
1656 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1657 // We can do this transformation if either the AND constant does not
1658 // have its sign bit set or if it is an equality comparison.
1659 // Extending a relational comparison when we're checking the sign
1660 // bit would not work.
1661 if (ICI.isEquality() ||
1662 (!AndCst->isNegative() && RHSV->isNonNegative())) {
1663 Value *NewAnd =
1664 Builder->CreateAnd(Cast->getOperand(0),
1665 ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
1666 NewAnd->takeName(LHSI);
1667 return new ICmpInst(ICI.getPredicate(), NewAnd,
1668 ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1669 }
1670 }
1671
1672 // If the LHS is an AND of a zext, and we have an equality compare, we can
1673 // shrink the and/compare to the smaller type, eliminating the cast.
1674 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1675 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1676 // Make sure we don't compare the upper bits, SimplifyDemandedBits
1677 // should fold the icmp to true/false in that case.
1678 if (ICI.isEquality() && RHSV->getActiveBits() <= Ty->getBitWidth()) {
1679 Value *NewAnd = Builder->CreateAnd(Cast->getOperand(0),
1680 ConstantExpr::getTrunc(AndCst, Ty));
1681 NewAnd->takeName(LHSI);
1682 return new ICmpInst(ICI.getPredicate(), NewAnd,
1683 ConstantExpr::getTrunc(RHS, Ty));
1684 }
1685 }
1686
1687 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1688 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1689 // happens a LOT in code produced by the C front-end, for bitfield
1690 // access.
1691 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1692 if (Shift && !Shift->isShift())
1693 Shift = nullptr;
1694
1695 ConstantInt *ShAmt;
1696 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : nullptr;
1697
1698 // This seemingly simple opportunity to fold away a shift turns out to
1699 // be rather complicated. See PR17827
1700 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
1701 if (ShAmt) {
1702 bool CanFold = false;
1703 unsigned ShiftOpcode = Shift->getOpcode();
1704 if (ShiftOpcode == Instruction::AShr) {
1705 // There may be some constraints that make this possible,
1706 // but nothing simple has been discovered yet.
1707 CanFold = false;
1708 } else if (ShiftOpcode == Instruction::Shl) {
1709 // For a left shift, we can fold if the comparison is not signed.
1710 // We can also fold a signed comparison if the mask value and
1711 // comparison value are not negative. These constraints may not be
1712 // obvious, but we can prove that they are correct using an SMT
1713 // solver.
1714 if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
1715 CanFold = true;
1716 } else if (ShiftOpcode == Instruction::LShr) {
1717 // For a logical right shift, we can fold if the comparison is not
1718 // signed. We can also fold a signed comparison if the shifted mask
1719 // value and the shifted comparison value are not negative.
1720 // These constraints may not be obvious, but we can prove that they
1721 // are correct using an SMT solver.
1722 if (!ICI.isSigned())
1723 CanFold = true;
1724 else {
1725 ConstantInt *ShiftedAndCst =
1726 cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1727 ConstantInt *ShiftedRHSCst =
1728 cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1729
1730 if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1731 CanFold = true;
1732 }
1733 }
1734
1735 if (CanFold) {
1736 Constant *NewCst;
1737 if (ShiftOpcode == Instruction::Shl)
1738 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1739 else
1740 NewCst = ConstantExpr::getShl(RHS, ShAmt);
1741
1742 // Check to see if we are shifting out any of the bits being
1743 // compared.
1744 if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
1745 // If we shifted bits out, the fold is not going to work out.
1746 // As a special case, check to see if this means that the
1747 // result is always true or false now.
1748 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1749 return replaceInstUsesWith(ICI, Builder->getFalse());
1750 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1751 return replaceInstUsesWith(ICI, Builder->getTrue());
1752 } else {
1753 ICI.setOperand(1, NewCst);
1754 Constant *NewAndCst;
1755 if (ShiftOpcode == Instruction::Shl)
1756 NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
1757 else
1758 NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1759 LHSI->setOperand(1, NewAndCst);
1760 LHSI->setOperand(0, Shift->getOperand(0));
1761 Worklist.Add(Shift); // Shift is dead.
1762 return &ICI;
1763 }
1764 }
1765 }
1766
1767 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
1768 // preferable because it allows the C<<Y expression to be hoisted out
1769 // of a loop if Y is invariant and X is not.
1770 if (Shift && Shift->hasOneUse() && *RHSV == 0 && ICI.isEquality() &&
1771 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1772 // Compute C << Y.
1773 Value *NS;
1774 if (Shift->getOpcode() == Instruction::LShr) {
1775 NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
1776 } else {
1777 // Insert a logical shift.
1778 NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
1779 }
1780
1781 // Compute X & (C << Y).
1782 Value *NewAnd =
1783 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1784
1785 ICI.setOperand(0, NewAnd);
1786 return &ICI;
1787 }
1788
1789 // (icmp pred (and (or (lshr X, Y), X), 1), 0) -->
1790 // (icmp pred (and X, (or (shl 1, Y), 1), 0))
1791 //
1792 // iff pred isn't signed
1793 {
1794 Value *X, *Y, *LShr;
1795 if (!ICI.isSigned() && *RHSV == 0) {
1796 if (match(LHSI->getOperand(1), m_One())) {
1797 Constant *One = cast<Constant>(LHSI->getOperand(1));
1798 Value *Or = LHSI->getOperand(0);
1799 if (match(Or, m_Or(m_Value(LShr), m_Value(X))) &&
1800 match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) {
1801 unsigned UsesRemoved = 0;
1802 if (LHSI->hasOneUse())
1803 ++UsesRemoved;
1804 if (Or->hasOneUse())
1805 ++UsesRemoved;
1806 if (LShr->hasOneUse())
1807 ++UsesRemoved;
1808 Value *NewOr = nullptr;
1809 // Compute X & ((1 << Y) | 1)
1810 if (auto *C = dyn_cast<Constant>(Y)) {
1811 if (UsesRemoved >= 1)
1812 NewOr =
1813 ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1814 } else {
1815 if (UsesRemoved >= 3)
1816 NewOr = Builder->CreateOr(Builder->CreateShl(One, Y,
1817 LShr->getName(),
1818 /*HasNUW=*/true),
1819 One, Or->getName());
1820 }
1821 if (NewOr) {
1822 Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName());
1823 ICI.setOperand(0, NewAnd);
1824 return &ICI;
1825 }
1826 }
1827 }
1828 }
1829 }
1830
1831 // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1832 // bit set in (X & AndCst) will produce a result greater than RHSV.
1833 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1834 unsigned NTZ = AndCst->getValue().countTrailingZeros();
1835 if ((NTZ < AndCst->getBitWidth()) &&
1836 APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(*RHSV))
1837 return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1838 Constant::getNullValue(RHS->getType()));
1839 }
1840 }
1841
1842 // Try to optimize things like "A[i]&42 == 0" to index computations.
1843 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1844 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1845 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1846 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1847 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1848 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1849 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, ICI, C))
1850 return Res;
1851 }
1852 }
1853
1854 // X & -C == -C -> X > u ~C
1855 // X & -C != -C -> X <= u ~C
1856 // iff C is a power of 2
1857 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-(*RHSV)).isPowerOf2())
1858 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1859 ? ICmpInst::ICMP_UGT
1860 : ICmpInst::ICMP_ULE,
1861 LHSI->getOperand(0), SubOne(RHS));
1862
1863 // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1)
1864 // iff C is a power of 2
1865 if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) {
1866 if (auto *CI = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1867 const APInt &AI = CI->getValue();
1868 int32_t ExactLogBase2 = AI.exactLogBase2();
1869 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1870 Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1);
1871 Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy);
1872 return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ
1873 ? ICmpInst::ICMP_SGE
1874 : ICmpInst::ICMP_SLT,
1875 Trunc, Constant::getNullValue(NTy));
1876 }
1877 }
1878 }
1879 return nullptr;
1880}
1881
Sanjay Patel943e92e2016-08-17 16:30:43 +00001882/// Fold icmp (or X, Y), C.
1883Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, Instruction *Or,
1884 const APInt *C) {
Sanjay Patel943e92e2016-08-17 16:30:43 +00001885 ICmpInst::Predicate Pred = Cmp.getPredicate();
1886 if (*C == 1) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001887 // icmp slt signum(V) 1 --> icmp slt V, 1
1888 Value *V = nullptr;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001889 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001890 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1891 ConstantInt::get(V->getType(), 1));
1892 }
1893
Sanjay Patel943e92e2016-08-17 16:30:43 +00001894 if (!Cmp.isEquality() || *C != 0 || !Or->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00001895 return nullptr;
1896
1897 Value *P, *Q;
Sanjay Patel943e92e2016-08-17 16:30:43 +00001898 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
Sanjay Patela3f4f082016-08-16 17:54:36 +00001899 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1900 // -> and (icmp eq P, null), (icmp eq Q, null).
Sanjay Patel943e92e2016-08-17 16:30:43 +00001901 Constant *NullVal = ConstantInt::getNullValue(P->getType());
1902 Value *CmpP = Builder->CreateICmp(Pred, P, NullVal);
1903 Value *CmpQ = Builder->CreateICmp(Pred, Q, NullVal);
1904 auto LogicOpc = Pred == ICmpInst::Predicate::ICMP_EQ ? Instruction::And
1905 : Instruction::Or;
1906 return BinaryOperator::Create(LogicOpc, CmpP, CmpQ);
Sanjay Patela3f4f082016-08-16 17:54:36 +00001907 }
Sanjay Patel943e92e2016-08-17 16:30:43 +00001908
Sanjay Patela3f4f082016-08-16 17:54:36 +00001909 return nullptr;
1910}
1911
Sanjay Patel63478072016-08-18 15:44:44 +00001912/// Fold icmp (mul X, Y), C.
1913Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp, Instruction *Mul,
1914 const APInt *C) {
1915 const APInt *MulC;
1916 if (!match(Mul->getOperand(1), m_APInt(MulC)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00001917 return nullptr;
1918
Sanjay Patel63478072016-08-18 15:44:44 +00001919 // If this is a test of the sign bit and the multiply is sign-preserving with
1920 // a constant operand, use the multiply LHS operand instead.
1921 ICmpInst::Predicate Pred = Cmp.getPredicate();
1922 if (isSignTest(Pred, *C) && cast<BinaryOperator>(Mul)->hasNoSignedWrap()) {
1923 if (MulC->isNegative())
1924 Pred = ICmpInst::getSwappedPredicate(Pred);
1925 return new ICmpInst(Pred, Mul->getOperand(0),
1926 Constant::getNullValue(Mul->getType()));
1927 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00001928
1929 return nullptr;
1930}
1931
1932Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &ICI, Instruction *LHSI,
1933 const APInt *RHSV) {
1934 // FIXME: This check restricts all folds under here to scalar types.
1935 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
1936 if (!RHS)
1937 return nullptr;
1938
1939 uint32_t TypeBits = RHSV->getBitWidth();
1940 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1941 if (!ShAmt) {
1942 Value *X;
1943 // (1 << X) pred P2 -> X pred Log2(P2)
1944 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1945 bool RHSVIsPowerOf2 = RHSV->isPowerOf2();
1946 ICmpInst::Predicate Pred = ICI.getPredicate();
1947 if (ICI.isUnsigned()) {
1948 if (!RHSVIsPowerOf2) {
1949 // (1 << X) < 30 -> X <= 4
1950 // (1 << X) <= 30 -> X <= 4
1951 // (1 << X) >= 30 -> X > 4
1952 // (1 << X) > 30 -> X > 4
1953 if (Pred == ICmpInst::ICMP_ULT)
1954 Pred = ICmpInst::ICMP_ULE;
1955 else if (Pred == ICmpInst::ICMP_UGE)
1956 Pred = ICmpInst::ICMP_UGT;
1957 }
1958 unsigned RHSLog2 = RHSV->logBase2();
1959
1960 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1961 // (1 << X) < 2147483648 -> X < 31 -> X != 31
1962 if (RHSLog2 == TypeBits - 1) {
1963 if (Pred == ICmpInst::ICMP_UGE)
1964 Pred = ICmpInst::ICMP_EQ;
1965 else if (Pred == ICmpInst::ICMP_ULT)
1966 Pred = ICmpInst::ICMP_NE;
1967 }
1968
1969 return new ICmpInst(Pred, X, ConstantInt::get(RHS->getType(), RHSLog2));
1970 } else if (ICI.isSigned()) {
1971 if (RHSV->isAllOnesValue()) {
1972 // (1 << X) <= -1 -> X == 31
1973 if (Pred == ICmpInst::ICMP_SLE)
1974 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1975 ConstantInt::get(RHS->getType(), TypeBits - 1));
1976
1977 // (1 << X) > -1 -> X != 31
1978 if (Pred == ICmpInst::ICMP_SGT)
1979 return new ICmpInst(ICmpInst::ICMP_NE, X,
1980 ConstantInt::get(RHS->getType(), TypeBits - 1));
1981 } else if (!(*RHSV)) {
1982 // (1 << X) < 0 -> X == 31
1983 // (1 << X) <= 0 -> X == 31
1984 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1985 return new ICmpInst(ICmpInst::ICMP_EQ, X,
1986 ConstantInt::get(RHS->getType(), TypeBits - 1));
1987
1988 // (1 << X) >= 0 -> X != 31
1989 // (1 << X) > 0 -> X != 31
1990 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1991 return new ICmpInst(ICmpInst::ICMP_NE, X,
1992 ConstantInt::get(RHS->getType(), TypeBits - 1));
1993 }
1994 } else if (ICI.isEquality()) {
1995 if (RHSVIsPowerOf2)
1996 return new ICmpInst(
1997 Pred, X, ConstantInt::get(RHS->getType(), RHSV->logBase2()));
1998 }
1999 }
2000 return nullptr;
2001 }
2002
2003 // Check that the shift amount is in range. If not, don't perform
2004 // undefined shifts. When the shift is visited it will be
2005 // simplified.
2006 if (ShAmt->uge(TypeBits))
2007 return nullptr;
2008
2009 if (ICI.isEquality()) {
2010 // If we are comparing against bits always shifted out, the
2011 // comparison cannot succeed.
2012 Constant *Comp =
2013 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
2014 if (Comp != RHS) { // Comparing against a bit that we know is zero.
2015 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
2016 Constant *Cst = Builder->getInt1(IsICMP_NE);
2017 return replaceInstUsesWith(ICI, Cst);
2018 }
2019
2020 // If the shift is NUW, then it is just shifting out zeros, no need for an
2021 // AND.
2022 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
2023 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2024 ConstantExpr::getLShr(RHS, ShAmt));
2025
2026 // If the shift is NSW and we compare to 0, then it is just shifting out
2027 // sign bits, no need for an AND either.
2028 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && *RHSV == 0)
2029 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
2030 ConstantExpr::getLShr(RHS, ShAmt));
2031
2032 if (LHSI->hasOneUse()) {
2033 // Otherwise strength reduce the shift into an and.
2034 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
2035 Constant *Mask =
2036 Builder->getInt(APInt::getLowBitsSet(TypeBits, TypeBits - ShAmtVal));
2037
2038 Value *And = Builder->CreateAnd(LHSI->getOperand(0), Mask,
2039 LHSI->getName() + ".mask");
2040 return new ICmpInst(ICI.getPredicate(), And,
2041 ConstantExpr::getLShr(RHS, ShAmt));
2042 }
2043 }
2044
2045 // If this is a signed comparison to 0 and the shift is sign preserving,
2046 // use the shift LHS operand instead.
2047 ICmpInst::Predicate pred = ICI.getPredicate();
Sanjay Patel5b112842016-08-18 14:59:14 +00002048 if (isSignTest(pred, *RHSV) && cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
Sanjay Patela3f4f082016-08-16 17:54:36 +00002049 return new ICmpInst(pred, LHSI->getOperand(0),
2050 Constant::getNullValue(RHS->getType()));
2051
2052 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2053 bool TrueIfSigned = false;
2054 if (LHSI->hasOneUse() &&
2055 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
2056 // (X << 31) <s 0 --> (X&1) != 0
2057 Constant *Mask = ConstantInt::get(
2058 LHSI->getOperand(0)->getType(),
2059 APInt::getOneBitSet(TypeBits, TypeBits - ShAmt->getZExtValue() - 1));
2060 Value *And = Builder->CreateAnd(LHSI->getOperand(0), Mask,
2061 LHSI->getName() + ".mask");
2062 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2063 And, Constant::getNullValue(And->getType()));
2064 }
2065
2066 // Transform (icmp pred iM (shl iM %v, N), CI)
2067 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
2068 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
2069 // This enables to get rid of the shift in favor of a trunc which can be
2070 // free on the target. It has the additional benefit of comparing to a
2071 // smaller constant, which will be target friendly.
2072 unsigned Amt = ShAmt->getLimitedValue(TypeBits - 1);
2073 if (LHSI->hasOneUse() && Amt != 0 && RHSV->countTrailingZeros() >= Amt) {
2074 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
2075 Constant *NCI = ConstantExpr::getTrunc(
2076 ConstantExpr::getAShr(RHS, ConstantInt::get(RHS->getType(), Amt)), NTy);
2077 return new ICmpInst(ICI.getPredicate(),
2078 Builder->CreateTrunc(LHSI->getOperand(0), NTy), NCI);
2079 }
2080
2081 return nullptr;
2082}
2083
2084Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &ICI, Instruction *LHSI,
2085 const APInt *RHSV) {
2086 // FIXME: This check restricts all folds under here to scalar types.
2087 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
2088 if (!RHS)
2089 return nullptr;
2090
2091 // Handle equality comparisons of shift-by-constant.
2092 BinaryOperator *BO = cast<BinaryOperator>(LHSI);
2093 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2094 if (Instruction *Res = foldICmpShrConstConst(ICI, BO, ShAmt))
2095 return Res;
2096 }
2097
2098 // Handle exact shr's.
2099 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
2100 if (RHSV->isMinValue())
2101 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
2102 }
2103
2104 return nullptr;
2105}
2106
Sanjay Patel12a41052016-08-18 17:37:26 +00002107/// Fold icmp (udiv X, Y), C.
2108Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp,
2109 Instruction *UDiv,
2110 const APInt *C) {
Sanjay Patelfa5ca2b2016-08-18 17:55:59 +00002111 const APInt *C2;
2112 if (!match(UDiv->getOperand(0), m_APInt(C2)))
2113 return nullptr;
2114
2115 assert(C2 != 0 && "udiv 0, X should have been simplified already.");
2116
2117 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2118 Value *Y = UDiv->getOperand(1);
2119 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) {
2120 assert(!C->isMaxValue() &&
2121 "icmp ugt X, UINT_MAX should have been simplified already.");
2122 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2123 ConstantInt::get(Y->getType(), C2->udiv(*C + 1)));
2124 }
2125
2126 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2127 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) {
2128 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2129 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2130 ConstantInt::get(Y->getType(), C2->udiv(*C)));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002131 }
2132
2133 return nullptr;
2134}
2135
2136Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &ICI, Instruction *LHSI,
2137 const APInt *RHSV) {
2138 // FIXME: This check restricts all folds under here to scalar types.
2139 ConstantInt *RHS = dyn_cast<ConstantInt>(ICI.getOperand(1));
2140 if (!RHS)
2141 return nullptr;
2142
2143 // Fold: icmp pred ([us]div X, C1), C2 -> range test
2144 // Fold this div into the comparison, producing a range check.
2145 // Determine, based on the divide type, what the range is being
2146 // checked. If there is an overflow on the low or high side, remember
2147 // it, otherwise compute the range [low, hi) bounding the new value.
2148 // See: InsertRangeTest above for the kinds of replacements possible.
2149 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
2150 if (Instruction *R =
2151 foldICmpDivConstConst(ICI, cast<BinaryOperator>(LHSI), DivRHS))
2152 return R;
2153
2154 return nullptr;
2155}
2156
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002157/// Fold icmp (sub X, Y), C.
2158Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp, Instruction *Sub,
2159 const APInt *C) {
Sanjay Patele47df1a2016-08-16 21:53:19 +00002160 const APInt *C2;
2161 if (!match(Sub->getOperand(0), m_APInt(C2)) || !Sub->hasOneUse())
Sanjay Patela3f4f082016-08-16 17:54:36 +00002162 return nullptr;
2163
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002164 // C-X <u C2 -> (X|(C2-1)) == C
2165 // iff C & (C2-1) == C2-1
Sanjay Patela3f4f082016-08-16 17:54:36 +00002166 // C2 is a power of 2
Sanjay Patele47df1a2016-08-16 21:53:19 +00002167 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2168 (*C2 & (*C - 1)) == (*C - 1))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002169 return new ICmpInst(ICmpInst::ICMP_EQ,
Sanjay Patele47df1a2016-08-16 21:53:19 +00002170 Builder->CreateOr(Sub->getOperand(1), *C - 1),
2171 Sub->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002172
Sanjay Patelb9aa67b2016-08-16 21:26:10 +00002173 // C-X >u C2 -> (X|C2) != C
2174 // iff C & C2 == C2
Sanjay Patela3f4f082016-08-16 17:54:36 +00002175 // C2+1 is a power of 2
Sanjay Patele47df1a2016-08-16 21:53:19 +00002176 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2177 (*C2 & *C) == *C)
Sanjay Patela3f4f082016-08-16 17:54:36 +00002178 return new ICmpInst(ICmpInst::ICMP_NE,
Sanjay Patele47df1a2016-08-16 21:53:19 +00002179 Builder->CreateOr(Sub->getOperand(1), *C),
2180 Sub->getOperand(0));
Sanjay Patela3f4f082016-08-16 17:54:36 +00002181
2182 return nullptr;
2183}
2184
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002185/// Fold icmp (add X, Y), C.
2186Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp, Instruction *Add,
2187 const APInt *C) {
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002188 Value *Y = Add->getOperand(1);
2189 const APInt *C2;
2190 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
Sanjay Patela3f4f082016-08-16 17:54:36 +00002191 return nullptr;
2192
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002193 // Fold icmp pred (add X, C2), C.
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002194 Value *X = Add->getOperand(0);
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002195 Type *Ty = Add->getType();
2196 auto CR = Cmp.makeConstantRange(Cmp.getPredicate(), *C).subtract(*C2);
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002197 const APInt &Upper = CR.getUpper();
2198 const APInt &Lower = CR.getLower();
2199 if (Cmp.isSigned()) {
2200 if (Lower.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002201 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002202 if (Upper.isSignBit())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002203 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002204 } else {
2205 if (Lower.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002206 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002207 if (Upper.isMinValue())
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002208 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
Sanjay Patel60ea1b42016-08-16 22:34:42 +00002209 }
Sanjay Patela3f4f082016-08-16 17:54:36 +00002210
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002211 if (!Add->hasOneUse())
2212 return nullptr;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002213
Sanjay Patel4f7eb2a2016-08-17 15:24:30 +00002214 // X+C <u C2 -> (X & -C2) == C
2215 // iff C & (C2-1) == 0
2216 // C2 is a power of 2
2217 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() &&
2218 (*C2 & (*C - 1)) == 0)
2219 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(X, -(*C)),
2220 ConstantExpr::getNeg(cast<Constant>(Y)));
2221
2222 // X+C >u C2 -> (X & ~C2) != C
2223 // iff C & C2 == 0
2224 // C2+1 is a power of 2
2225 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() &&
2226 (*C2 & *C) == 0)
2227 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(X, ~(*C)),
2228 ConstantExpr::getNeg(cast<Constant>(Y)));
2229
Sanjay Patela3f4f082016-08-16 17:54:36 +00002230 return nullptr;
2231}
2232
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00002233/// Try to fold integer comparisons with a constant operand: icmp Pred X, C.
2234Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &ICI) {
2235 Instruction *LHSI;
2236 const APInt *RHSV;
2237 if (!match(ICI.getOperand(0), m_Instruction(LHSI)) ||
2238 !match(ICI.getOperand(1), m_APInt(RHSV)))
2239 return nullptr;
2240
Chris Lattner2188e402010-01-04 07:37:31 +00002241 switch (LHSI->getOpcode()) {
2242 case Instruction::Trunc:
Sanjay Patela3f4f082016-08-16 17:54:36 +00002243 if (Instruction *I = foldICmpTruncConstant(ICI, LHSI, RHSV))
2244 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002245 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002246 case Instruction::Xor:
2247 if (Instruction *I = foldICmpXorConstant(ICI, LHSI, RHSV))
2248 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002249 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002250 case Instruction::And:
2251 if (Instruction *I = foldICmpAndConstant(ICI, LHSI, RHSV))
2252 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002253 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002254 case Instruction::Or:
2255 if (Instruction *I = foldICmpOrConstant(ICI, LHSI, RHSV))
2256 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002257 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002258 case Instruction::Mul:
2259 if (Instruction *I = foldICmpMulConstant(ICI, LHSI, RHSV))
2260 return I;
Arnaud A. de Grandmaison9c383d62013-03-25 09:48:49 +00002261 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002262 case Instruction::Shl:
2263 if (Instruction *I = foldICmpShlConstant(ICI, LHSI, RHSV))
2264 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002265 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002266 case Instruction::LShr:
2267 case Instruction::AShr:
2268 if (Instruction *I = foldICmpShrConstant(ICI, LHSI, RHSV))
2269 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002270 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002271 case Instruction::UDiv:
Sanjay Patela3f4f082016-08-16 17:54:36 +00002272 if (Instruction *I = foldICmpUDivConstant(ICI, LHSI, RHSV))
2273 return I;
Justin Bognerb03fd122016-08-17 05:10:15 +00002274 LLVM_FALLTHROUGH;
Chad Rosier4e6cda22016-05-10 20:22:09 +00002275 case Instruction::SDiv:
Sanjay Patela3f4f082016-08-16 17:54:36 +00002276 if (Instruction *I = foldICmpDivConstant(ICI, LHSI, RHSV))
2277 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002278 break;
Sanjay Patela3f4f082016-08-16 17:54:36 +00002279 case Instruction::Sub:
2280 if (Instruction *I = foldICmpSubConstant(ICI, LHSI, RHSV))
2281 return I;
David Majnemerf2a9a512013-07-09 07:50:59 +00002282 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002283 case Instruction::Add:
Sanjay Patela3f4f082016-08-16 17:54:36 +00002284 if (Instruction *I = foldICmpAddConstant(ICI, LHSI, RHSV))
2285 return I;
Chris Lattner2188e402010-01-04 07:37:31 +00002286 break;
2287 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002288
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002289 return nullptr;
2290}
Jim Grosbach129c52a2011-09-30 18:09:53 +00002291
Sanjay Patelab50a932016-08-02 22:38:33 +00002292/// Simplify icmp_eq and icmp_ne instructions with binary operator LHS and
2293/// integer constant RHS.
2294Instruction *InstCombiner::foldICmpEqualityWithConstant(ICmpInst &ICI) {
Sanjay Patelab50a932016-08-02 22:38:33 +00002295 BinaryOperator *BO;
Sanjay Patel43aeb002016-08-03 18:59:03 +00002296 const APInt *RHSV;
2297 // FIXME: Some of these folds could work with arbitrary constants, but this
2298 // match is limited to scalars and vector splat constants.
Sanjay Patelab50a932016-08-02 22:38:33 +00002299 if (!ICI.isEquality() || !match(ICI.getOperand(0), m_BinOp(BO)) ||
Sanjay Patel43aeb002016-08-03 18:59:03 +00002300 !match(ICI.getOperand(1), m_APInt(RHSV)))
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002301 return nullptr;
2302
Sanjay Patel43aeb002016-08-03 18:59:03 +00002303 Constant *RHS = cast<Constant>(ICI.getOperand(1));
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002304 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002305 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002306
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002307 switch (BO->getOpcode()) {
2308 case Instruction::SRem:
2309 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Sanjay Patel2e9675f2016-08-03 19:48:40 +00002310 if (*RHSV == 0 && BO->hasOneUse()) {
2311 const APInt *BOC;
2312 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002313 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName());
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002314 return new ICmpInst(ICI.getPredicate(), NewRem,
2315 Constant::getNullValue(BO->getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00002316 }
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002317 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002318 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002319 case Instruction::Add: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002320 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
Sanjay Patel00a324e2016-08-03 22:08:44 +00002321 const APInt *BOC;
2322 if (match(BOp1, m_APInt(BOC))) {
2323 if (BO->hasOneUse()) {
2324 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1));
2325 return new ICmpInst(ICI.getPredicate(), BOp0, SubC);
2326 }
Sanjay Patel43aeb002016-08-03 18:59:03 +00002327 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002328 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2329 // efficiently invertible, or if the add has just this one use.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002330 if (Value *NegVal = dyn_castNegVal(BOp1))
2331 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
2332 if (Value *NegVal = dyn_castNegVal(BOp0))
2333 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
2334 if (BO->hasOneUse()) {
2335 Value *Neg = Builder->CreateNeg(BOp1);
2336 Neg->takeName(BO);
2337 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
2338 }
2339 }
2340 break;
Sanjay Patel00a324e2016-08-03 22:08:44 +00002341 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002342 case Instruction::Xor:
2343 if (BO->hasOneUse()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002344 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002345 // For the xor case, we can xor two constants together, eliminating
2346 // the explicit xor.
Sanjay Patel51a767c2016-08-03 17:23:08 +00002347 return new ICmpInst(ICI.getPredicate(), BOp0,
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002348 ConstantExpr::getXor(RHS, BOC));
Sanjay Patel43aeb002016-08-03 18:59:03 +00002349 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002350 // Replace ((xor A, B) != 0) with (A != B)
Sanjay Patel51a767c2016-08-03 17:23:08 +00002351 return new ICmpInst(ICI.getPredicate(), BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002352 }
2353 }
2354 break;
2355 case Instruction::Sub:
2356 if (BO->hasOneUse()) {
Sanjay Patel9d591d12016-08-04 15:19:25 +00002357 const APInt *BOC;
2358 if (match(BOp0, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002359 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
Sanjay Patel9d591d12016-08-04 15:19:25 +00002360 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS);
2361 return new ICmpInst(ICI.getPredicate(), BOp1, SubC);
Sanjay Patel43aeb002016-08-03 18:59:03 +00002362 } else if (*RHSV == 0) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002363 // Replace ((sub A, B) != 0) with (A != B)
Sanjay Patel51a767c2016-08-03 17:23:08 +00002364 return new ICmpInst(ICI.getPredicate(), BOp0, BOp1);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002365 }
2366 }
2367 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002368 case Instruction::Or: {
2369 const APInt *BOC;
2370 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002371 // Comparing if all bits outside of a constant mask are set?
2372 // Replace (X | C) == -1 with (X & ~C) == ~C.
2373 // This removes the -1 constant.
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002374 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
2375 Value *And = Builder->CreateAnd(BOp0, NotBOC);
2376 return new ICmpInst(ICI.getPredicate(), And, NotBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002377 }
2378 break;
Sanjay Patelb3de75d2016-08-04 19:12:12 +00002379 }
Sanjay Pateld938e882016-08-04 20:05:02 +00002380 case Instruction::And: {
2381 const APInt *BOC;
2382 if (match(BOp1, m_APInt(BOC))) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002383 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Sanjay Pateld938e882016-08-04 20:05:02 +00002384 if (RHSV == BOC && RHSV->isPowerOf2())
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002385 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
Sanjay Patelab50a932016-08-02 22:38:33 +00002386 BO, Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002387
2388 // Don't perform the following transforms if the AND has multiple uses
2389 if (!BO->hasOneUse())
2390 break;
2391
2392 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Sanjay Pateld938e882016-08-04 20:05:02 +00002393 if (BOC->isSignBit()) {
Sanjay Patel51a767c2016-08-03 17:23:08 +00002394 Constant *Zero = Constant::getNullValue(BOp0->getType());
2395 ICmpInst::Predicate Pred =
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002396 isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002397 return new ICmpInst(Pred, BOp0, Zero);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002398 }
2399
2400 // ((X & ~7) == 0) --> X < 8
Sanjay Pateld938e882016-08-04 20:05:02 +00002401 if (*RHSV == 0 && (~(*BOC) + 1).isPowerOf2()) {
2402 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1));
Sanjay Patel51a767c2016-08-03 17:23:08 +00002403 ICmpInst::Predicate Pred =
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002404 isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Sanjay Pateld938e882016-08-04 20:05:02 +00002405 return new ICmpInst(Pred, BOp0, NegBOC);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002406 }
2407 }
2408 break;
Sanjay Pateld938e882016-08-04 20:05:02 +00002409 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002410 case Instruction::Mul:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002411 if (*RHSV == 0 && BO->hasNoSignedWrap()) {
Sanjay Patel3bade132016-08-04 22:19:27 +00002412 const APInt *BOC;
2413 if (match(BOp1, m_APInt(BOC)) && *BOC != 0) {
2414 // The trivial case (mul X, 0) is handled by InstSimplify.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002415 // General case : (mul X, C) != 0 iff X != 0
2416 // (mul X, C) == 0 iff X == 0
Sanjay Patel3bade132016-08-04 22:19:27 +00002417 return new ICmpInst(ICI.getPredicate(), BOp0,
2418 Constant::getNullValue(RHS->getType()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002419 }
2420 }
2421 break;
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002422 case Instruction::UDiv:
Sanjay Patel43aeb002016-08-03 18:59:03 +00002423 if (*RHSV == 0) {
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002424 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
2425 ICmpInst::Predicate Pred =
2426 isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
Sanjay Patel51a767c2016-08-03 17:23:08 +00002427 return new ICmpInst(Pred, BOp1, BOp0);
Sanjay Patel6ebd5852016-07-23 00:28:39 +00002428 }
2429 break;
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002430 default:
2431 break;
2432 }
2433 return nullptr;
2434}
2435
Sanjay Patel1271bf92016-07-23 13:06:49 +00002436Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &ICI) {
2437 IntrinsicInst *II = dyn_cast<IntrinsicInst>(ICI.getOperand(0));
2438 const APInt *Op1C;
2439 if (!II || !ICI.isEquality() || !match(ICI.getOperand(1), m_APInt(Op1C)))
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002440 return nullptr;
2441
2442 // Handle icmp {eq|ne} <intrinsic>, intcst.
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002443 switch (II->getIntrinsicID()) {
2444 case Intrinsic::bswap:
2445 Worklist.Add(II);
2446 ICI.setOperand(0, II->getArgOperand(0));
Sanjay Patel1271bf92016-07-23 13:06:49 +00002447 ICI.setOperand(1, Builder->getInt(Op1C->byteSwap()));
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002448 return &ICI;
2449 case Intrinsic::ctlz:
2450 case Intrinsic::cttz:
Amaury Sechet6bea6742016-08-04 05:27:20 +00002451 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
Sanjay Patel1271bf92016-07-23 13:06:49 +00002452 if (*Op1C == Op1C->getBitWidth()) {
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002453 Worklist.Add(II);
2454 ICI.setOperand(0, II->getArgOperand(0));
Sanjay Patel1271bf92016-07-23 13:06:49 +00002455 ICI.setOperand(1, ConstantInt::getNullValue(II->getType()));
Sanjay Patel1710e7c2016-07-21 17:15:49 +00002456 return &ICI;
Chris Lattner2188e402010-01-04 07:37:31 +00002457 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002458 break;
Amaury Sechet6bea6742016-08-04 05:27:20 +00002459 case Intrinsic::ctpop: {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002460 // popcount(A) == 0 -> A == 0 and likewise for !=
Amaury Sechet6bea6742016-08-04 05:27:20 +00002461 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
2462 bool IsZero = *Op1C == 0;
2463 if (IsZero || *Op1C == Op1C->getBitWidth()) {
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002464 Worklist.Add(II);
2465 ICI.setOperand(0, II->getArgOperand(0));
Amaury Sechet6bea6742016-08-04 05:27:20 +00002466 auto *NewOp = IsZero
2467 ? ConstantInt::getNullValue(II->getType())
2468 : ConstantInt::getAllOnesValue(II->getType());
2469 ICI.setOperand(1, NewOp);
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002470 return &ICI;
2471 }
Amaury Sechet6bea6742016-08-04 05:27:20 +00002472 }
Sanjay Patel18fa9d32016-07-21 23:27:36 +00002473 break;
2474 default:
2475 break;
Chris Lattner2188e402010-01-04 07:37:31 +00002476 }
Craig Topperf40110f2014-04-25 05:29:35 +00002477 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002478}
2479
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002480/// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so
2481/// far.
Sanjay Patel43395062016-07-21 18:07:40 +00002482Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) {
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002483 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00002484 Value *LHSCIOp = LHSCI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002485 Type *SrcTy = LHSCIOp->getType();
2486 Type *DestTy = LHSCI->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00002487 Value *RHSCIOp;
2488
Jim Grosbach129c52a2011-09-30 18:09:53 +00002489 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
Chris Lattner2188e402010-01-04 07:37:31 +00002490 // integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002491 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
2492 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002493 Value *RHSOp = nullptr;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002494 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
Michael Liaod266b922015-02-13 04:51:26 +00002495 Value *RHSCIOp = RHSC->getOperand(0);
2496 if (RHSCIOp->getType()->getPointerAddressSpace() ==
2497 LHSCIOp->getType()->getPointerAddressSpace()) {
2498 RHSOp = RHSC->getOperand(0);
2499 // If the pointer types don't match, insert a bitcast.
2500 if (LHSCIOp->getType() != RHSOp->getType())
2501 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
2502 }
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002503 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002504 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002505 }
Chris Lattner2188e402010-01-04 07:37:31 +00002506
2507 if (RHSOp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002508 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002509 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002510
Chris Lattner2188e402010-01-04 07:37:31 +00002511 // The code below only handles extension cast instructions, so far.
2512 // Enforce this.
2513 if (LHSCI->getOpcode() != Instruction::ZExt &&
2514 LHSCI->getOpcode() != Instruction::SExt)
Craig Topperf40110f2014-04-25 05:29:35 +00002515 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002516
2517 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002518 bool isSignedCmp = ICmp.isSigned();
Chris Lattner2188e402010-01-04 07:37:31 +00002519
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002520 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00002521 // Not an extension from the same type?
2522 RHSCIOp = CI->getOperand(0);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002523 if (RHSCIOp->getType() != LHSCIOp->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00002524 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002525
Chris Lattner2188e402010-01-04 07:37:31 +00002526 // If the signedness of the two casts doesn't agree (i.e. one is a sext
2527 // and the other is a zext), then we can't handle this.
2528 if (CI->getOpcode() != LHSCI->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +00002529 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002530
2531 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002532 if (ICmp.isEquality())
2533 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002534
2535 // A signed comparison of sign extended values simplifies into a
2536 // signed comparison.
2537 if (isSignedCmp && isSignedExt)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002538 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002539
2540 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002541 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Chris Lattner2188e402010-01-04 07:37:31 +00002542 }
2543
Sanjay Patel4c204232016-06-04 20:39:22 +00002544 // If we aren't dealing with a constant on the RHS, exit early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002545 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
2546 if (!C)
Craig Topperf40110f2014-04-25 05:29:35 +00002547 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002548
2549 // Compute the constant that would happen if we truncated to SrcTy then
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002550 // re-extended to DestTy.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002551 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
Sanjay Patelc774f8c2016-06-04 21:20:44 +00002552 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner2188e402010-01-04 07:37:31 +00002553
2554 // If the re-extended constant didn't change...
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002555 if (Res2 == C) {
Chris Lattner2188e402010-01-04 07:37:31 +00002556 // Deal with equality cases early.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002557 if (ICmp.isEquality())
2558 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002559
2560 // A signed comparison of sign extended values simplifies into a
2561 // signed comparison.
2562 if (isSignedExt && isSignedCmp)
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002563 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002564
2565 // The other three cases all fold into an unsigned comparison.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002566 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1);
Chris Lattner2188e402010-01-04 07:37:31 +00002567 }
2568
Sanjay Patel6a333c32016-06-06 16:56:57 +00002569 // The re-extended constant changed, partly changed (in the case of a vector),
2570 // or could not be determined to be equal (in the case of a constant
2571 // expression), so the constant cannot be represented in the shorter type.
2572 // Consequently, we cannot emit a simple comparison.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002573 // All the cases that fold to true or false will have already been handled
2574 // by SimplifyICmpInst, so only deal with the tricky case.
Chris Lattner2188e402010-01-04 07:37:31 +00002575
Sanjay Patel6a333c32016-06-06 16:56:57 +00002576 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
Craig Topperf40110f2014-04-25 05:29:35 +00002577 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00002578
2579 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
2580 // should have been folded away previously and not enter in here.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002581
2582 // We're performing an unsigned comp with a sign extended value.
2583 // This is true if the input is >= 0. [aka >s -1]
2584 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002585 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName());
Chris Lattner2188e402010-01-04 07:37:31 +00002586
2587 // Finally, return the value computed.
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002588 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
2589 return replaceInstUsesWith(ICmp, Result);
Chris Lattner2188e402010-01-04 07:37:31 +00002590
Sanjay Patel6f8f47b2016-06-05 00:12:32 +00002591 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
Chris Lattner2188e402010-01-04 07:37:31 +00002592 return BinaryOperator::CreateNot(Result);
2593}
2594
Sanjay Patel5f0217f2016-06-05 16:46:18 +00002595/// The caller has matched a pattern of the form:
Chris Lattneree61c1d2010-12-19 17:52:50 +00002596/// I = icmp ugt (add (add A, B), CI2), CI1
Chris Lattnerc56c8452010-12-19 18:22:06 +00002597/// If this is of the form:
2598/// sum = a + b
2599/// if (sum+128 >u 255)
2600/// Then replace it with llvm.sadd.with.overflow.i8.
2601///
Chris Lattneree61c1d2010-12-19 17:52:50 +00002602static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
2603 ConstantInt *CI2, ConstantInt *CI1,
Chris Lattnerce2995a2010-12-19 18:38:44 +00002604 InstCombiner &IC) {
Chris Lattnerf29562d2010-12-19 17:59:02 +00002605 // The transformation we're trying to do here is to transform this into an
2606 // llvm.sadd.with.overflow. To do this, we have to replace the original add
2607 // with a narrower add, and discard the add-with-constant that is part of the
2608 // range check (if we can't eliminate it, this isn't profitable).
Jim Grosbach129c52a2011-09-30 18:09:53 +00002609
Chris Lattnerf29562d2010-12-19 17:59:02 +00002610 // In order to eliminate the add-with-constant, the compare can be its only
2611 // use.
Chris Lattnerc56c8452010-12-19 18:22:06 +00002612 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00002613 if (!AddWithCst->hasOneUse()) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002614
Chris Lattnerc56c8452010-12-19 18:22:06 +00002615 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
Craig Topperf40110f2014-04-25 05:29:35 +00002616 if (!CI2->getValue().isPowerOf2()) return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002617 unsigned NewWidth = CI2->getValue().countTrailingZeros();
Craig Topperf40110f2014-04-25 05:29:35 +00002618 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002619
Chris Lattnerc56c8452010-12-19 18:22:06 +00002620 // The width of the new add formed is 1 more than the bias.
2621 ++NewWidth;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002622
Chris Lattnerc56c8452010-12-19 18:22:06 +00002623 // Check to see that CI1 is an all-ones value with NewWidth bits.
2624 if (CI1->getBitWidth() == NewWidth ||
2625 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
Craig Topperf40110f2014-04-25 05:29:35 +00002626 return nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002627
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002628 // This is only really a signed overflow check if the inputs have been
2629 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
2630 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
2631 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
Hal Finkel60db0582014-09-07 18:57:58 +00002632 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits ||
2633 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits)
Craig Topperf40110f2014-04-25 05:29:35 +00002634 return nullptr;
Eli Friedmanb3f9b062011-11-28 23:32:19 +00002635
Jim Grosbach129c52a2011-09-30 18:09:53 +00002636 // In order to replace the original add with a narrower
Chris Lattnerc56c8452010-12-19 18:22:06 +00002637 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
2638 // and truncates that discard the high bits of the add. Verify that this is
2639 // the case.
2640 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
Chandler Carruthcdf47882014-03-09 03:16:01 +00002641 for (User *U : OrigAdd->users()) {
2642 if (U == AddWithCst) continue;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002643
Chris Lattnerc56c8452010-12-19 18:22:06 +00002644 // Only accept truncates for now. We would really like a nice recursive
2645 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
2646 // chain to see which bits of a value are actually demanded. If the
2647 // original add had another add which was then immediately truncated, we
2648 // could still do the transformation.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002649 TruncInst *TI = dyn_cast<TruncInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00002650 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
2651 return nullptr;
Chris Lattnerc56c8452010-12-19 18:22:06 +00002652 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00002653
Chris Lattneree61c1d2010-12-19 17:52:50 +00002654 // If the pattern matches, truncate the inputs to the narrower type and
2655 // use the sadd_with_overflow intrinsic to efficiently compute both the
2656 // result and the overflow bit.
Jay Foadb804a2b2011-07-12 14:06:48 +00002657 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002658 Value *F = Intrinsic::getDeclaration(I.getModule(),
2659 Intrinsic::sadd_with_overflow, NewType);
Chris Lattner79874562010-12-19 18:35:09 +00002660
Chris Lattnerce2995a2010-12-19 18:38:44 +00002661 InstCombiner::BuilderTy *Builder = IC.Builder;
Jim Grosbach129c52a2011-09-30 18:09:53 +00002662
Chris Lattner79874562010-12-19 18:35:09 +00002663 // Put the new code above the original add, in case there are any uses of the
2664 // add between the add and the compare.
Chris Lattner5e0c0c72010-12-19 19:37:52 +00002665 Builder->SetInsertPoint(OrigAdd);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002666
Chris Lattner79874562010-12-19 18:35:09 +00002667 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
2668 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
David Blaikieff6409d2015-05-18 22:13:54 +00002669 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd");
Chris Lattner79874562010-12-19 18:35:09 +00002670 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
2671 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00002672
Chris Lattneree61c1d2010-12-19 17:52:50 +00002673 // The inner add was the result of the narrow add, zero extended to the
2674 // wider type. Replace it with the result computed by the intrinsic.
Sanjay Patel4b198802016-02-01 22:23:39 +00002675 IC.replaceInstUsesWith(*OrigAdd, ZExt);
Jim Grosbach129c52a2011-09-30 18:09:53 +00002676
Chris Lattner79874562010-12-19 18:35:09 +00002677 // The original icmp gets replaced with the overflow value.
2678 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
Chris Lattneree61c1d2010-12-19 17:52:50 +00002679}
Chris Lattner2188e402010-01-04 07:37:31 +00002680
Sanjoy Dasb0984472015-04-08 04:27:22 +00002681bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS,
2682 Value *RHS, Instruction &OrigI,
2683 Value *&Result, Constant *&Overflow) {
Sanjoy Das827529e2015-08-11 21:33:55 +00002684 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
2685 std::swap(LHS, RHS);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002686
2687 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) {
2688 Result = OpResult;
2689 Overflow = OverflowVal;
2690 if (ReuseName)
2691 Result->takeName(&OrigI);
2692 return true;
2693 };
2694
Sanjoy Das6f5dca72015-08-28 19:09:31 +00002695 // If the overflow check was an add followed by a compare, the insertion point
2696 // may be pointing to the compare. We want to insert the new instructions
2697 // before the add in case there are uses of the add between the add and the
2698 // compare.
2699 Builder->SetInsertPoint(&OrigI);
2700
Sanjoy Dasb0984472015-04-08 04:27:22 +00002701 switch (OCF) {
2702 case OCF_INVALID:
2703 llvm_unreachable("bad overflow check kind!");
2704
2705 case OCF_UNSIGNED_ADD: {
2706 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI);
2707 if (OR == OverflowResult::NeverOverflows)
2708 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(),
2709 true);
2710
2711 if (OR == OverflowResult::AlwaysOverflows)
2712 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002713
2714 // Fall through uadd into sadd
2715 LLVM_FALLTHROUGH;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002716 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00002717 case OCF_SIGNED_ADD: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002718 // X + 0 -> {X, false}
2719 if (match(RHS, m_Zero()))
2720 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002721
2722 // We can strength reduce this signed add into a regular add if we can prove
2723 // that it will never overflow.
2724 if (OCF == OCF_SIGNED_ADD)
2725 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI))
2726 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(),
2727 true);
Sanjoy Das72cb5e12015-06-05 18:04:42 +00002728 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002729 }
2730
2731 case OCF_UNSIGNED_SUB:
2732 case OCF_SIGNED_SUB: {
David Majnemer27e89ba2015-05-21 23:04:21 +00002733 // X - 0 -> {X, false}
2734 if (match(RHS, m_Zero()))
2735 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002736
2737 if (OCF == OCF_SIGNED_SUB) {
2738 if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
2739 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
2740 true);
2741 } else {
2742 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
2743 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
2744 true);
2745 }
2746 break;
2747 }
2748
2749 case OCF_UNSIGNED_MUL: {
2750 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
2751 if (OR == OverflowResult::NeverOverflows)
2752 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
2753 true);
2754 if (OR == OverflowResult::AlwaysOverflows)
2755 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002756 LLVM_FALLTHROUGH;
2757 }
Sanjoy Dasb0984472015-04-08 04:27:22 +00002758 case OCF_SIGNED_MUL:
2759 // X * undef -> undef
2760 if (isa<UndefValue>(RHS))
David Majnemer27e89ba2015-05-21 23:04:21 +00002761 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002762
David Majnemer27e89ba2015-05-21 23:04:21 +00002763 // X * 0 -> {0, false}
2764 if (match(RHS, m_Zero()))
2765 return SetResult(RHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002766
David Majnemer27e89ba2015-05-21 23:04:21 +00002767 // X * 1 -> {X, false}
2768 if (match(RHS, m_One()))
2769 return SetResult(LHS, Builder->getFalse(), false);
Sanjoy Dasb0984472015-04-08 04:27:22 +00002770
2771 if (OCF == OCF_SIGNED_MUL)
2772 if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
2773 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
2774 true);
Sanjoy Dasc80dad62015-06-05 18:04:46 +00002775 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002776 }
2777
2778 return false;
2779}
2780
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002781/// \brief Recognize and process idiom involving test for multiplication
2782/// overflow.
2783///
2784/// The caller has matched a pattern of the form:
2785/// I = cmp u (mul(zext A, zext B), V
2786/// The function checks if this is a test for overflow and if so replaces
2787/// multiplication with call to 'mul.with.overflow' intrinsic.
2788///
2789/// \param I Compare instruction.
2790/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
2791/// the compare instruction. Must be of integer type.
2792/// \param OtherVal The other argument of compare instruction.
2793/// \returns Instruction which must replace the compare instruction, NULL if no
2794/// replacement required.
2795static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
2796 Value *OtherVal, InstCombiner &IC) {
Benjamin Kramerc96a7f82014-06-24 10:47:52 +00002797 // Don't bother doing this transformation for pointers, don't do it for
2798 // vectors.
2799 if (!isa<IntegerType>(MulVal->getType()))
2800 return nullptr;
2801
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002802 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
2803 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
David Majnemerdaa24b92015-09-05 20:44:56 +00002804 auto *MulInstr = dyn_cast<Instruction>(MulVal);
2805 if (!MulInstr)
2806 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002807 assert(MulInstr->getOpcode() == Instruction::Mul);
2808
David Majnemer634ca232014-11-01 23:46:05 +00002809 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
2810 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002811 assert(LHS->getOpcode() == Instruction::ZExt);
2812 assert(RHS->getOpcode() == Instruction::ZExt);
2813 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
2814
2815 // Calculate type and width of the result produced by mul.with.overflow.
2816 Type *TyA = A->getType(), *TyB = B->getType();
2817 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
2818 WidthB = TyB->getPrimitiveSizeInBits();
2819 unsigned MulWidth;
2820 Type *MulType;
2821 if (WidthB > WidthA) {
2822 MulWidth = WidthB;
2823 MulType = TyB;
2824 } else {
2825 MulWidth = WidthA;
2826 MulType = TyA;
2827 }
2828
2829 // In order to replace the original mul with a narrower mul.with.overflow,
2830 // all uses must ignore upper bits of the product. The number of used low
2831 // bits must be not greater than the width of mul.with.overflow.
2832 if (MulVal->hasNUsesOrMore(2))
2833 for (User *U : MulVal->users()) {
2834 if (U == &I)
2835 continue;
2836 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2837 // Check if truncation ignores bits above MulWidth.
2838 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
2839 if (TruncWidth > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002840 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002841 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2842 // Check if AND ignores bits above MulWidth.
2843 if (BO->getOpcode() != Instruction::And)
Craig Topperf40110f2014-04-25 05:29:35 +00002844 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002845 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2846 const APInt &CVal = CI->getValue();
2847 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
Craig Topperf40110f2014-04-25 05:29:35 +00002848 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002849 }
2850 } else {
2851 // Other uses prohibit this transformation.
Craig Topperf40110f2014-04-25 05:29:35 +00002852 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002853 }
2854 }
2855
2856 // Recognize patterns
2857 switch (I.getPredicate()) {
2858 case ICmpInst::ICMP_EQ:
2859 case ICmpInst::ICMP_NE:
2860 // Recognize pattern:
2861 // mulval = mul(zext A, zext B)
2862 // cmp eq/neq mulval, zext trunc mulval
2863 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
2864 if (Zext->hasOneUse()) {
2865 Value *ZextArg = Zext->getOperand(0);
2866 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
2867 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
2868 break; //Recognized
2869 }
2870
2871 // Recognize pattern:
2872 // mulval = mul(zext A, zext B)
2873 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
2874 ConstantInt *CI;
2875 Value *ValToMask;
2876 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
2877 if (ValToMask != MulVal)
Craig Topperf40110f2014-04-25 05:29:35 +00002878 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002879 const APInt &CVal = CI->getValue() + 1;
2880 if (CVal.isPowerOf2()) {
2881 unsigned MaskWidth = CVal.logBase2();
2882 if (MaskWidth == MulWidth)
2883 break; // Recognized
2884 }
2885 }
Craig Topperf40110f2014-04-25 05:29:35 +00002886 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002887
2888 case ICmpInst::ICMP_UGT:
2889 // Recognize pattern:
2890 // mulval = mul(zext A, zext B)
2891 // cmp ugt mulval, max
2892 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2893 APInt MaxVal = APInt::getMaxValue(MulWidth);
2894 MaxVal = MaxVal.zext(CI->getBitWidth());
2895 if (MaxVal.eq(CI->getValue()))
2896 break; // Recognized
2897 }
Craig Topperf40110f2014-04-25 05:29:35 +00002898 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002899
2900 case ICmpInst::ICMP_UGE:
2901 // Recognize pattern:
2902 // mulval = mul(zext A, zext B)
2903 // cmp uge mulval, max+1
2904 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2905 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
2906 if (MaxVal.eq(CI->getValue()))
2907 break; // Recognized
2908 }
Craig Topperf40110f2014-04-25 05:29:35 +00002909 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002910
2911 case ICmpInst::ICMP_ULE:
2912 // Recognize pattern:
2913 // mulval = mul(zext A, zext B)
2914 // cmp ule mulval, max
2915 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
2916 APInt MaxVal = APInt::getMaxValue(MulWidth);
2917 MaxVal = MaxVal.zext(CI->getBitWidth());
2918 if (MaxVal.eq(CI->getValue()))
2919 break; // Recognized
2920 }
Craig Topperf40110f2014-04-25 05:29:35 +00002921 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002922
2923 case ICmpInst::ICMP_ULT:
2924 // Recognize pattern:
2925 // mulval = mul(zext A, zext B)
2926 // cmp ule mulval, max + 1
2927 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002928 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002929 if (MaxVal.eq(CI->getValue()))
2930 break; // Recognized
2931 }
Craig Topperf40110f2014-04-25 05:29:35 +00002932 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002933
2934 default:
Craig Topperf40110f2014-04-25 05:29:35 +00002935 return nullptr;
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002936 }
2937
2938 InstCombiner::BuilderTy *Builder = IC.Builder;
2939 Builder->SetInsertPoint(MulInstr);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002940
2941 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
2942 Value *MulA = A, *MulB = B;
2943 if (WidthA < MulWidth)
2944 MulA = Builder->CreateZExt(A, MulType);
2945 if (WidthB < MulWidth)
2946 MulB = Builder->CreateZExt(B, MulType);
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002947 Value *F = Intrinsic::getDeclaration(I.getModule(),
2948 Intrinsic::umul_with_overflow, MulType);
David Blaikieff6409d2015-05-18 22:13:54 +00002949 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002950 IC.Worklist.Add(MulInstr);
2951
2952 // If there are uses of mul result other than the comparison, we know that
2953 // they are truncation or binary AND. Change them to use result of
Serge Pavlovb5f3ddc2014-04-14 02:20:19 +00002954 // mul.with.overflow and adjust properly mask/size.
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002955 if (MulVal->hasNUsesOrMore(2)) {
2956 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
2957 for (User *U : MulVal->users()) {
2958 if (U == &I || U == OtherVal)
2959 continue;
2960 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
2961 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
Sanjay Patel4b198802016-02-01 22:23:39 +00002962 IC.replaceInstUsesWith(*TI, Mul);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002963 else
2964 TI->setOperand(0, Mul);
2965 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
2966 assert(BO->getOpcode() == Instruction::And);
2967 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
2968 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
2969 APInt ShortMask = CI->getValue().trunc(MulWidth);
2970 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
2971 Instruction *Zext =
2972 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
2973 IC.Worklist.Add(Zext);
Sanjay Patel4b198802016-02-01 22:23:39 +00002974 IC.replaceInstUsesWith(*BO, Zext);
Serge Pavlov4bb54d52014-04-13 18:23:41 +00002975 } else {
2976 llvm_unreachable("Unexpected Binary operation");
2977 }
2978 IC.Worklist.Add(cast<Instruction>(U));
2979 }
2980 }
2981 if (isa<Instruction>(OtherVal))
2982 IC.Worklist.Add(cast<Instruction>(OtherVal));
2983
2984 // The original icmp gets replaced with the overflow value, maybe inverted
2985 // depending on predicate.
2986 bool Inverse = false;
2987 switch (I.getPredicate()) {
2988 case ICmpInst::ICMP_NE:
2989 break;
2990 case ICmpInst::ICMP_EQ:
2991 Inverse = true;
2992 break;
2993 case ICmpInst::ICMP_UGT:
2994 case ICmpInst::ICMP_UGE:
2995 if (I.getOperand(0) == MulVal)
2996 break;
2997 Inverse = true;
2998 break;
2999 case ICmpInst::ICMP_ULT:
3000 case ICmpInst::ICMP_ULE:
3001 if (I.getOperand(1) == MulVal)
3002 break;
3003 Inverse = true;
3004 break;
3005 default:
3006 llvm_unreachable("Unexpected predicate");
3007 }
3008 if (Inverse) {
3009 Value *Res = Builder->CreateExtractValue(Call, 1);
3010 return BinaryOperator::CreateNot(Res);
3011 }
3012
3013 return ExtractValueInst::Create(Call, 1);
3014}
3015
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003016/// When performing a comparison against a constant, it is possible that not all
3017/// the bits in the LHS are demanded. This helper method computes the mask that
3018/// IS demanded.
Owen Andersond490c2d2011-01-11 00:36:45 +00003019static APInt DemandedBitsLHSMask(ICmpInst &I,
3020 unsigned BitWidth, bool isSignCheck) {
3021 if (isSignCheck)
3022 return APInt::getSignBit(BitWidth);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003023
Owen Andersond490c2d2011-01-11 00:36:45 +00003024 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3025 if (!CI) return APInt::getAllOnesValue(BitWidth);
Owen Anderson0022a4b2011-01-11 18:26:37 +00003026 const APInt &RHS = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00003027
Owen Andersond490c2d2011-01-11 00:36:45 +00003028 switch (I.getPredicate()) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003029 // For a UGT comparison, we don't care about any bits that
Owen Andersond490c2d2011-01-11 00:36:45 +00003030 // correspond to the trailing ones of the comparand. The value of these
3031 // bits doesn't impact the outcome of the comparison, because any value
3032 // greater than the RHS must differ in a bit higher than these due to carry.
3033 case ICmpInst::ICMP_UGT: {
3034 unsigned trailingOnes = RHS.countTrailingOnes();
3035 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
3036 return ~lowBitsSet;
3037 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003038
Owen Andersond490c2d2011-01-11 00:36:45 +00003039 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
3040 // Any value less than the RHS must differ in a higher bit because of carries.
3041 case ICmpInst::ICMP_ULT: {
3042 unsigned trailingZeros = RHS.countTrailingZeros();
3043 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
3044 return ~lowBitsSet;
3045 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003046
Owen Andersond490c2d2011-01-11 00:36:45 +00003047 default:
3048 return APInt::getAllOnesValue(BitWidth);
3049 }
Owen Andersond490c2d2011-01-11 00:36:45 +00003050}
Chris Lattner2188e402010-01-04 07:37:31 +00003051
Quentin Colombet5ab55552013-09-09 20:56:48 +00003052/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
3053/// should be swapped.
Alp Tokercb402912014-01-24 17:20:08 +00003054/// The decision is based on how many times these two operands are reused
Quentin Colombet5ab55552013-09-09 20:56:48 +00003055/// as subtract operands and their positions in those instructions.
3056/// The rational is that several architectures use the same instruction for
3057/// both subtract and cmp, thus it is better if the order of those operands
3058/// match.
3059/// \return true if Op0 and Op1 should be swapped.
3060static bool swapMayExposeCSEOpportunities(const Value * Op0,
3061 const Value * Op1) {
3062 // Filter out pointer value as those cannot appears directly in subtract.
3063 // FIXME: we may want to go through inttoptrs or bitcasts.
3064 if (Op0->getType()->isPointerTy())
3065 return false;
3066 // Count every uses of both Op0 and Op1 in a subtract.
3067 // Each time Op0 is the first operand, count -1: swapping is bad, the
3068 // subtract has already the same layout as the compare.
3069 // Each time Op0 is the second operand, count +1: swapping is good, the
Alp Tokercb402912014-01-24 17:20:08 +00003070 // subtract has a different layout as the compare.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003071 // At the end, if the benefit is greater than 0, Op0 should come second to
3072 // expose more CSE opportunities.
3073 int GlobalSwapBenefits = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003074 for (const User *U : Op0->users()) {
3075 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003076 if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
3077 continue;
3078 // If Op0 is the first argument, this is not beneficial to swap the
3079 // arguments.
3080 int LocalSwapBenefits = -1;
3081 unsigned Op1Idx = 1;
3082 if (BinOp->getOperand(Op1Idx) == Op0) {
3083 Op1Idx = 0;
3084 LocalSwapBenefits = 1;
3085 }
3086 if (BinOp->getOperand(Op1Idx) != Op1)
3087 continue;
3088 GlobalSwapBenefits += LocalSwapBenefits;
3089 }
3090 return GlobalSwapBenefits > 0;
3091}
3092
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003093/// \brief Check that one use is in the same block as the definition and all
3094/// other uses are in blocks dominated by a given block
3095///
3096/// \param DI Definition
3097/// \param UI Use
3098/// \param DB Block that must dominate all uses of \p DI outside
3099/// the parent block
3100/// \return true when \p UI is the only use of \p DI in the parent block
3101/// and all other uses of \p DI are in blocks dominated by \p DB.
3102///
3103bool InstCombiner::dominatesAllUses(const Instruction *DI,
3104 const Instruction *UI,
3105 const BasicBlock *DB) const {
3106 assert(DI && UI && "Instruction not defined\n");
3107 // ignore incomplete definitions
3108 if (!DI->getParent())
3109 return false;
3110 // DI and UI must be in the same block
3111 if (DI->getParent() != UI->getParent())
3112 return false;
3113 // Protect from self-referencing blocks
3114 if (DI->getParent() == DB)
3115 return false;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003116 for (const User *U : DI->users()) {
3117 auto *Usr = cast<Instruction>(U);
Justin Bogner99798402016-08-05 01:06:44 +00003118 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003119 return false;
3120 }
3121 return true;
3122}
3123
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003124/// Return true when the instruction sequence within a block is select-cmp-br.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003125static bool isChainSelectCmpBranch(const SelectInst *SI) {
3126 const BasicBlock *BB = SI->getParent();
3127 if (!BB)
3128 return false;
3129 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
3130 if (!BI || BI->getNumSuccessors() != 2)
3131 return false;
3132 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
3133 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
3134 return false;
3135 return true;
3136}
3137
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003138/// \brief True when a select result is replaced by one of its operands
3139/// in select-icmp sequence. This will eventually result in the elimination
3140/// of the select.
3141///
3142/// \param SI Select instruction
3143/// \param Icmp Compare instruction
3144/// \param SIOpd Operand that replaces the select
3145///
3146/// Notes:
3147/// - The replacement is global and requires dominator information
3148/// - The caller is responsible for the actual replacement
3149///
3150/// Example:
3151///
3152/// entry:
3153/// %4 = select i1 %3, %C* %0, %C* null
3154/// %5 = icmp eq %C* %4, null
3155/// br i1 %5, label %9, label %7
3156/// ...
3157/// ; <label>:7 ; preds = %entry
3158/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
3159/// ...
3160///
3161/// can be transformed to
3162///
3163/// %5 = icmp eq %C* %0, null
3164/// %6 = select i1 %3, i1 %5, i1 true
3165/// br i1 %6, label %9, label %7
3166/// ...
3167/// ; <label>:7 ; preds = %entry
3168/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
3169///
3170/// Similar when the first operand of the select is a constant or/and
3171/// the compare is for not equal rather than equal.
3172///
3173/// NOTE: The function is only called when the select and compare constants
3174/// are equal, the optimization can work only for EQ predicates. This is not a
3175/// major restriction since a NE compare should be 'normalized' to an equal
3176/// compare, which usually happens in the combiner and test case
3177/// select-cmp-br.ll
3178/// checks for it.
3179bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
3180 const ICmpInst *Icmp,
3181 const unsigned SIOpd) {
David Majnemer83484fd2014-11-22 06:09:28 +00003182 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003183 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
3184 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
3185 // The check for the unique predecessor is not the best that can be
3186 // done. But it protects efficiently against cases like when SI's
3187 // home block has two successors, Succ and Succ1, and Succ1 predecessor
3188 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
3189 // replaced can be reached on either path. So the uniqueness check
3190 // guarantees that the path all uses of SI (outside SI's parent) are on
3191 // is disjoint from all other paths out of SI. But that information
3192 // is more expensive to compute, and the trade-off here is in favor
3193 // of compile-time.
3194 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
3195 NumSel++;
3196 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
3197 return true;
3198 }
3199 }
3200 return false;
3201}
3202
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003203/// If we have an icmp le or icmp ge instruction with a constant operand, turn
3204/// it into the appropriate icmp lt or icmp gt instruction. This transform
3205/// allows them to be folded in visitICmpInst.
Sanjay Patele9b2c322016-05-17 00:57:57 +00003206static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
3207 ICmpInst::Predicate Pred = I.getPredicate();
3208 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE &&
3209 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE)
3210 return nullptr;
3211
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003212 Value *Op0 = I.getOperand(0);
3213 Value *Op1 = I.getOperand(1);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003214 auto *Op1C = dyn_cast<Constant>(Op1);
3215 if (!Op1C)
3216 return nullptr;
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003217
Sanjay Patele9b2c322016-05-17 00:57:57 +00003218 // Check if the constant operand can be safely incremented/decremented without
3219 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled
3220 // the edge cases for us, so we just assert on them. For vectors, we must
3221 // handle the edge cases.
3222 Type *Op1Type = Op1->getType();
3223 bool IsSigned = I.isSigned();
3224 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE);
Sanjay Patel18254932016-05-17 01:12:31 +00003225 auto *CI = dyn_cast<ConstantInt>(Op1C);
3226 if (CI) {
Sanjay Patele9b2c322016-05-17 00:57:57 +00003227 // A <= MAX -> TRUE ; A >= MIN -> TRUE
3228 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned));
3229 } else if (Op1Type->isVectorTy()) {
Sanjay Patelb79ab272016-05-13 15:10:46 +00003230 // TODO? If the edge cases for vectors were guaranteed to be handled as they
Sanjay Patele9b2c322016-05-17 00:57:57 +00003231 // are for scalar, we could remove the min/max checks. However, to do that,
3232 // we would have to use insertelement/shufflevector to replace edge values.
3233 unsigned NumElts = Op1Type->getVectorNumElements();
3234 for (unsigned i = 0; i != NumElts; ++i) {
3235 Constant *Elt = Op1C->getAggregateElement(i);
Benjamin Kramerca9a0fe2016-05-17 12:08:55 +00003236 if (!Elt)
3237 return nullptr;
3238
Sanjay Patele9b2c322016-05-17 00:57:57 +00003239 if (isa<UndefValue>(Elt))
3240 continue;
3241 // Bail out if we can't determine if this constant is min/max or if we
3242 // know that this constant is min/max.
3243 auto *CI = dyn_cast<ConstantInt>(Elt);
3244 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned)))
3245 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003246 }
Sanjay Patele9b2c322016-05-17 00:57:57 +00003247 } else {
3248 // ConstantExpr?
3249 return nullptr;
Sanjay Patelb79ab272016-05-13 15:10:46 +00003250 }
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003251
Sanjay Patele9b2c322016-05-17 00:57:57 +00003252 // Increment or decrement the constant and set the new comparison predicate:
3253 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT
Sanjay Patel22b01fe2016-05-17 20:20:40 +00003254 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true);
Sanjay Patele9b2c322016-05-17 00:57:57 +00003255 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT;
3256 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred;
3257 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne));
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003258}
3259
Chris Lattner2188e402010-01-04 07:37:31 +00003260Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
3261 bool Changed = false;
Chris Lattner9306ffa2010-02-01 19:54:45 +00003262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Quentin Colombet5ab55552013-09-09 20:56:48 +00003263 unsigned Op0Cplxity = getComplexity(Op0);
3264 unsigned Op1Cplxity = getComplexity(Op1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003265
Chris Lattner2188e402010-01-04 07:37:31 +00003266 /// Orders the operands of the compare so that they are listed from most
3267 /// complex to least complex. This puts constants before unary operators,
3268 /// before binary operators.
Quentin Colombet5ab55552013-09-09 20:56:48 +00003269 if (Op0Cplxity < Op1Cplxity ||
Sanjay Patel4c204232016-06-04 20:39:22 +00003270 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003271 I.swapOperands();
Chris Lattner9306ffa2010-02-01 19:54:45 +00003272 std::swap(Op0, Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003273 Changed = true;
3274 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003275
Jingyue Wu5e34ce32015-06-25 20:14:47 +00003276 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +00003277 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00003278 return replaceInstUsesWith(I, V);
Jim Grosbach129c52a2011-09-30 18:09:53 +00003279
Pete Cooperbc5c5242011-12-01 03:58:40 +00003280 // comparing -val or val with non-zero is the same as just comparing val
Pete Cooperfdddc272011-12-01 19:13:26 +00003281 // ie, abs(val) != 0 -> val != 0
Sanjay Patel4c204232016-06-04 20:39:22 +00003282 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003283 Value *Cond, *SelectTrue, *SelectFalse;
3284 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
Pete Cooperbc5c5242011-12-01 03:58:40 +00003285 m_Value(SelectFalse)))) {
Pete Cooperfdddc272011-12-01 19:13:26 +00003286 if (Value *V = dyn_castNegVal(SelectTrue)) {
3287 if (V == SelectFalse)
3288 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
3289 }
3290 else if (Value *V = dyn_castNegVal(SelectFalse)) {
3291 if (V == SelectTrue)
3292 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
Pete Cooperbc5c5242011-12-01 03:58:40 +00003293 }
3294 }
3295 }
3296
Chris Lattner229907c2011-07-18 04:54:35 +00003297 Type *Ty = Op0->getType();
Chris Lattner2188e402010-01-04 07:37:31 +00003298
3299 // icmp's with boolean values can always be turned into bitwise operations
Sanjay Patela6fbc822016-06-05 17:49:45 +00003300 if (Ty->getScalarType()->isIntegerTy(1)) {
Chris Lattner2188e402010-01-04 07:37:31 +00003301 switch (I.getPredicate()) {
3302 default: llvm_unreachable("Invalid icmp instruction!");
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003303 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
3304 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003305 return BinaryOperator::CreateNot(Xor);
3306 }
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003307 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B
Chris Lattner2188e402010-01-04 07:37:31 +00003308 return BinaryOperator::CreateXor(Op0, Op1);
3309
3310 case ICmpInst::ICMP_UGT:
3311 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003312 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003313 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
3314 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003315 return BinaryOperator::CreateAnd(Not, Op1);
3316 }
3317 case ICmpInst::ICMP_SGT:
3318 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003319 LLVM_FALLTHROUGH;
Chris Lattner2188e402010-01-04 07:37:31 +00003320 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003321 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003322 return BinaryOperator::CreateAnd(Not, Op0);
3323 }
3324 case ICmpInst::ICMP_UGE:
3325 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003326 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003327 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
3328 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003329 return BinaryOperator::CreateOr(Not, Op1);
3330 }
3331 case ICmpInst::ICMP_SGE:
3332 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003333 LLVM_FALLTHROUGH;
Sanjay Patel5f0217f2016-06-05 16:46:18 +00003334 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
3335 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp");
Chris Lattner2188e402010-01-04 07:37:31 +00003336 return BinaryOperator::CreateOr(Not, Op0);
3337 }
3338 }
3339 }
3340
Sanjay Patele9b2c322016-05-17 00:57:57 +00003341 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I))
Sanjay Pateld5b0e542016-04-29 16:22:25 +00003342 return NewICmp;
3343
Chris Lattner2188e402010-01-04 07:37:31 +00003344 unsigned BitWidth = 0;
Chris Lattner5e0c0c72010-12-19 19:37:52 +00003345 if (Ty->isIntOrIntVectorTy())
Chris Lattner2188e402010-01-04 07:37:31 +00003346 BitWidth = Ty->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003347 else // Get pointer size.
3348 BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
Jim Grosbach129c52a2011-09-30 18:09:53 +00003349
Chris Lattner2188e402010-01-04 07:37:31 +00003350 bool isSignBit = false;
3351
3352 // See if we are doing a comparison with a constant.
3353 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00003354 Value *A = nullptr, *B = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003355
Owen Anderson1294ea72010-12-17 18:08:00 +00003356 // Match the following pattern, which is a common idiom when writing
3357 // overflow-safe integer arithmetic function. The source performs an
3358 // addition in wider type, and explicitly checks for overflow using
3359 // comparisons against INT_MIN and INT_MAX. Simplify this by using the
3360 // sadd_with_overflow intrinsic.
Chris Lattneree61c1d2010-12-19 17:52:50 +00003361 //
3362 // TODO: This could probably be generalized to handle other overflow-safe
Jim Grosbach129c52a2011-09-30 18:09:53 +00003363 // operations if we worked out the formulas to compute the appropriate
Owen Anderson1294ea72010-12-17 18:08:00 +00003364 // magic constants.
Jim Grosbach129c52a2011-09-30 18:09:53 +00003365 //
Chris Lattneree61c1d2010-12-19 17:52:50 +00003366 // sum = a + b
3367 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
Owen Anderson1294ea72010-12-17 18:08:00 +00003368 {
Chris Lattneree61c1d2010-12-19 17:52:50 +00003369 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI
Owen Anderson1294ea72010-12-17 18:08:00 +00003370 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
Chris Lattneree61c1d2010-12-19 17:52:50 +00003371 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
Chris Lattnerce2995a2010-12-19 18:38:44 +00003372 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
Chris Lattneree61c1d2010-12-19 17:52:50 +00003373 return Res;
Owen Anderson1294ea72010-12-17 18:08:00 +00003374 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003375
Philip Reamesec8a8b52016-03-09 21:05:07 +00003376 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
3377 if (CI->isZero() && I.getPredicate() == ICmpInst::ICMP_SGT)
3378 if (auto *SI = dyn_cast<SelectInst>(Op0)) {
3379 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
3380 if (SPR.Flavor == SPF_SMIN) {
Philip Reames8f12eba2016-03-09 21:31:47 +00003381 if (isKnownPositive(A, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003382 return new ICmpInst(I.getPredicate(), B, CI);
Philip Reames8f12eba2016-03-09 21:31:47 +00003383 if (isKnownPositive(B, DL))
Philip Reamesec8a8b52016-03-09 21:05:07 +00003384 return new ICmpInst(I.getPredicate(), A, CI);
3385 }
3386 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00003387
Philip Reamesec8a8b52016-03-09 21:05:07 +00003388
David Majnemera0afb552015-01-14 19:26:56 +00003389 // The following transforms are only 'worth it' if the only user of the
3390 // subtraction is the icmp.
3391 if (Op0->hasOneUse()) {
3392 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
3393 if (I.isEquality() && CI->isZero() &&
3394 match(Op0, m_Sub(m_Value(A), m_Value(B))))
3395 return new ICmpInst(I.getPredicate(), A, B);
3396
3397 // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
3398 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
3399 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3400 return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
3401
3402 // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
3403 if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
3404 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3405 return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
3406
3407 // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
3408 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
3409 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3410 return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
3411
3412 // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
3413 if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
3414 match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
3415 return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
Chris Lattner2188e402010-01-04 07:37:31 +00003416 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003417
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003418 if (I.isEquality()) {
3419 ConstantInt *CI2;
3420 if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
3421 match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
David Majnemer59939ac2014-10-19 08:23:08 +00003422 // (icmp eq/ne (ashr/lshr const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003423 if (Instruction *Inst = foldICmpCstShrConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003424 return Inst;
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003425 }
David Majnemer59939ac2014-10-19 08:23:08 +00003426 if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
3427 // (icmp eq/ne (shl const2, A), const1)
Sanjay Patel43395062016-07-21 18:07:40 +00003428 if (Instruction *Inst = foldICmpCstShlConst(I, Op0, A, CI, CI2))
David Majnemer2abb8182014-10-25 07:13:13 +00003429 return Inst;
David Majnemer59939ac2014-10-19 08:23:08 +00003430 }
Suyog Sarda3a8c2c12014-07-22 19:19:36 +00003431 }
3432
Chris Lattner2188e402010-01-04 07:37:31 +00003433 // If this comparison is a normal comparison, it demands all
3434 // bits, if it is a sign bit comparison, it only demands the sign bit.
3435 bool UnusedBit;
3436 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
Balaram Makam569eaec2016-05-04 21:32:14 +00003437
3438 // Canonicalize icmp instructions based on dominating conditions.
3439 BasicBlock *Parent = I.getParent();
3440 BasicBlock *Dom = Parent->getSinglePredecessor();
3441 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr;
3442 ICmpInst::Predicate Pred;
3443 BasicBlock *TrueBB, *FalseBB;
3444 ConstantInt *CI2;
3445 if (BI && match(BI, m_Br(m_ICmp(Pred, m_Specific(Op0), m_ConstantInt(CI2)),
3446 TrueBB, FalseBB)) &&
3447 TrueBB != FalseBB) {
3448 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(I.getPredicate(),
3449 CI->getValue());
3450 ConstantRange DominatingCR =
3451 (Parent == TrueBB)
3452 ? ConstantRange::makeExactICmpRegion(Pred, CI2->getValue())
3453 : ConstantRange::makeExactICmpRegion(
3454 CmpInst::getInversePredicate(Pred), CI2->getValue());
3455 ConstantRange Intersection = DominatingCR.intersectWith(CR);
3456 ConstantRange Difference = DominatingCR.difference(CR);
3457 if (Intersection.isEmptySet())
3458 return replaceInstUsesWith(I, Builder->getFalse());
3459 if (Difference.isEmptySet())
3460 return replaceInstUsesWith(I, Builder->getTrue());
3461 // Canonicalizing a sign bit comparison that gets used in a branch,
3462 // pessimizes codegen by generating branch on zero instruction instead
3463 // of a test and branch. So we avoid canonicalizing in such situations
3464 // because test and branch instruction has better branch displacement
3465 // than compare and branch instruction.
3466 if (!isBranchOnSignBitCheck(I, isSignBit) && !I.isEquality()) {
3467 if (auto *AI = Intersection.getSingleElement())
3468 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Builder->getInt(*AI));
3469 if (auto *AD = Difference.getSingleElement())
3470 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Builder->getInt(*AD));
3471 }
3472 }
Chris Lattner2188e402010-01-04 07:37:31 +00003473 }
3474
3475 // See if we can fold the comparison based on range information we can get
3476 // by checking whether bits are known to be zero or one in the input.
3477 if (BitWidth != 0) {
3478 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
3479 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
3480
3481 if (SimplifyDemandedBits(I.getOperandUse(0),
Owen Andersond490c2d2011-01-11 00:36:45 +00003482 DemandedBitsLHSMask(I, BitWidth, isSignBit),
Chris Lattner2188e402010-01-04 07:37:31 +00003483 Op0KnownZero, Op0KnownOne, 0))
3484 return &I;
3485 if (SimplifyDemandedBits(I.getOperandUse(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003486 APInt::getAllOnesValue(BitWidth), Op1KnownZero,
3487 Op1KnownOne, 0))
Chris Lattner2188e402010-01-04 07:37:31 +00003488 return &I;
3489
3490 // Given the known and unknown bits, compute a range that the LHS could be
3491 // in. Compute the Min, Max and RHS values based on the known bits. For the
3492 // EQ and NE we use unsigned values.
3493 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
3494 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
3495 if (I.isSigned()) {
3496 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3497 Op0Min, Op0Max);
3498 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3499 Op1Min, Op1Max);
3500 } else {
3501 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
3502 Op0Min, Op0Max);
3503 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
3504 Op1Min, Op1Max);
3505 }
3506
3507 // If Min and Max are known to be the same, then SimplifyDemandedBits
3508 // figured out that the LHS is a constant. Just constant fold this now so
3509 // that code below can assume that Min != Max.
3510 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
3511 return new ICmpInst(I.getPredicate(),
Nick Lewycky92db8e82011-03-06 03:36:19 +00003512 ConstantInt::get(Op0->getType(), Op0Min), Op1);
Chris Lattner2188e402010-01-04 07:37:31 +00003513 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
3514 return new ICmpInst(I.getPredicate(), Op0,
Nick Lewycky92db8e82011-03-06 03:36:19 +00003515 ConstantInt::get(Op1->getType(), Op1Min));
Chris Lattner2188e402010-01-04 07:37:31 +00003516
3517 // Based on the range information we know about the LHS, see if we can
Nick Lewycky6b4454192011-02-28 06:20:05 +00003518 // simplify this comparison. For example, (x&4) < 8 is always true.
Chris Lattner2188e402010-01-04 07:37:31 +00003519 switch (I.getPredicate()) {
3520 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattnerf7e89612010-11-21 06:44:42 +00003521 case ICmpInst::ICMP_EQ: {
Chris Lattner2188e402010-01-04 07:37:31 +00003522 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003523 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003524
Chris Lattnerf7e89612010-11-21 06:44:42 +00003525 // If all bits are known zero except for one, then we know at most one
3526 // bit is set. If the comparison is against zero, then this is a check
3527 // to see if *that* bit is set.
3528 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003529 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003530 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003531 Value *LHS = nullptr;
3532 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003533 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3534 LHSC->getValue() != Op0KnownZeroInverted)
3535 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003536
Chris Lattnerf7e89612010-11-21 06:44:42 +00003537 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattnere5afa152010-11-23 02:42:04 +00003538 // then turn "((1 << x)&8) == 0" into "x != 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003539 // or turn "((1 << x)&7) == 0" into "x > 2".
Craig Topperf40110f2014-04-25 05:29:35 +00003540 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003541 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003542 APInt ValToCheck = Op0KnownZeroInverted;
3543 if (ValToCheck.isPowerOf2()) {
3544 unsigned CmpVal = ValToCheck.countTrailingZeros();
3545 return new ICmpInst(ICmpInst::ICMP_NE, X,
3546 ConstantInt::get(X->getType(), CmpVal));
3547 } else if ((++ValToCheck).isPowerOf2()) {
3548 unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
3549 return new ICmpInst(ICmpInst::ICMP_UGT, X,
3550 ConstantInt::get(X->getType(), CmpVal));
3551 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003552 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003553
Chris Lattnerf7e89612010-11-21 06:44:42 +00003554 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattnere5afa152010-11-23 02:42:04 +00003555 // then turn "((8 >>u x)&1) == 0" into "x != 3".
Chris Lattner98457102011-02-10 05:23:05 +00003556 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003557 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003558 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003559 return new ICmpInst(ICmpInst::ICMP_NE, X,
Chris Lattner98457102011-02-10 05:23:05 +00003560 ConstantInt::get(X->getType(),
3561 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003562 }
Chris Lattner2188e402010-01-04 07:37:31 +00003563 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003564 }
3565 case ICmpInst::ICMP_NE: {
Chris Lattner2188e402010-01-04 07:37:31 +00003566 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Sanjay Patel4b198802016-02-01 22:23:39 +00003567 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Jim Grosbach129c52a2011-09-30 18:09:53 +00003568
Chris Lattnerf7e89612010-11-21 06:44:42 +00003569 // If all bits are known zero except for one, then we know at most one
3570 // bit is set. If the comparison is against zero, then this is a check
3571 // to see if *that* bit is set.
3572 APInt Op0KnownZeroInverted = ~Op0KnownZero;
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003573 if (~Op1KnownZero == 0) {
Chris Lattnerf7e89612010-11-21 06:44:42 +00003574 // If the LHS is an AND with the same constant, look through it.
Craig Topperf40110f2014-04-25 05:29:35 +00003575 Value *LHS = nullptr;
3576 ConstantInt *LHSC = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003577 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
3578 LHSC->getValue() != Op0KnownZeroInverted)
3579 LHS = Op0;
Jim Grosbach129c52a2011-09-30 18:09:53 +00003580
Chris Lattnerf7e89612010-11-21 06:44:42 +00003581 // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
Chris Lattnere5afa152010-11-23 02:42:04 +00003582 // then turn "((1 << x)&8) != 0" into "x == 3".
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003583 // or turn "((1 << x)&7) != 0" into "x < 3".
Craig Topperf40110f2014-04-25 05:29:35 +00003584 Value *X = nullptr;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003585 if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
Dinesh Dwivedice5d35a2014-06-02 07:57:24 +00003586 APInt ValToCheck = Op0KnownZeroInverted;
3587 if (ValToCheck.isPowerOf2()) {
3588 unsigned CmpVal = ValToCheck.countTrailingZeros();
3589 return new ICmpInst(ICmpInst::ICMP_EQ, X,
3590 ConstantInt::get(X->getType(), CmpVal));
3591 } else if ((++ValToCheck).isPowerOf2()) {
3592 unsigned CmpVal = ValToCheck.countTrailingZeros();
3593 return new ICmpInst(ICmpInst::ICMP_ULT, X,
3594 ConstantInt::get(X->getType(), CmpVal));
3595 }
Chris Lattnerf7e89612010-11-21 06:44:42 +00003596 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003597
Chris Lattnerf7e89612010-11-21 06:44:42 +00003598 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
Chris Lattnere5afa152010-11-23 02:42:04 +00003599 // then turn "((8 >>u x)&1) != 0" into "x == 3".
Chris Lattner98457102011-02-10 05:23:05 +00003600 const APInt *CI;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003601 if (Op0KnownZeroInverted == 1 &&
Chris Lattner98457102011-02-10 05:23:05 +00003602 match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
Chris Lattnere5afa152010-11-23 02:42:04 +00003603 return new ICmpInst(ICmpInst::ICMP_EQ, X,
Chris Lattner98457102011-02-10 05:23:05 +00003604 ConstantInt::get(X->getType(),
3605 CI->countTrailingZeros()));
Chris Lattnerf7e89612010-11-21 06:44:42 +00003606 }
Chris Lattner2188e402010-01-04 07:37:31 +00003607 break;
Chris Lattnerf7e89612010-11-21 06:44:42 +00003608 }
Chris Lattner2188e402010-01-04 07:37:31 +00003609 case ICmpInst::ICMP_ULT:
3610 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003611 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003612 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003613 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003614 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
3615 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3616 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3617 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
3618 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003619 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003620
3621 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
3622 if (CI->isMinValue(true))
3623 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
3624 Constant::getAllOnesValue(Op0->getType()));
3625 }
3626 break;
3627 case ICmpInst::ICMP_UGT:
3628 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003629 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003630 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003631 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003632
3633 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
3634 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3635 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3636 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
3637 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003638 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003639
3640 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
3641 if (CI->isMaxValue(true))
3642 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
3643 Constant::getNullValue(Op0->getType()));
3644 }
3645 break;
3646 case ICmpInst::ICMP_SLT:
3647 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003648 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003649 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Sanjay Patel4b198802016-02-01 22:23:39 +00003650 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003651 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
3652 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3653 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3654 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
3655 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003656 Builder->getInt(CI->getValue()-1));
Chris Lattner2188e402010-01-04 07:37:31 +00003657 }
3658 break;
3659 case ICmpInst::ICMP_SGT:
3660 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003661 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003662 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003663 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003664
3665 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
3666 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
3667 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3668 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
3669 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Jakub Staszakbddea112013-06-06 20:18:46 +00003670 Builder->getInt(CI->getValue()+1));
Chris Lattner2188e402010-01-04 07:37:31 +00003671 }
3672 break;
3673 case ICmpInst::ICMP_SGE:
3674 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
3675 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003676 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003677 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003678 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003679 break;
3680 case ICmpInst::ICMP_SLE:
3681 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
3682 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003683 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003684 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003685 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003686 break;
3687 case ICmpInst::ICMP_UGE:
3688 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
3689 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003690 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003691 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003692 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003693 break;
3694 case ICmpInst::ICMP_ULE:
3695 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
3696 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003697 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003698 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Sanjay Patel4b198802016-02-01 22:23:39 +00003699 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Chris Lattner2188e402010-01-04 07:37:31 +00003700 break;
3701 }
3702
3703 // Turn a signed comparison into an unsigned one if both operands
3704 // are known to have the same sign.
3705 if (I.isSigned() &&
3706 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
3707 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
3708 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
3709 }
3710
3711 // Test if the ICmpInst instruction is used exclusively by a select as
3712 // part of a minimum or maximum operation. If so, refrain from doing
3713 // any other folding. This helps out other analyses which understand
3714 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
3715 // and CodeGen. And in this case, at least one of the comparison
3716 // operands has at least one user besides the compare (the select),
3717 // which would often largely negate the benefit of folding anyway.
3718 if (I.hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +00003719 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
Chris Lattner2188e402010-01-04 07:37:31 +00003720 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
3721 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +00003722 return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00003723
3724 // See if we are doing a comparison between a constant and an instruction that
3725 // can be folded into the comparison.
Sanjay Patel1271bf92016-07-23 13:06:49 +00003726
Sanjay Patel1e5b2d12016-08-16 16:08:11 +00003727 if (Instruction *Res = foldICmpWithConstant(I))
3728 return Res;
Chris Lattner2188e402010-01-04 07:37:31 +00003729
Sanjay Patelab50a932016-08-02 22:38:33 +00003730 if (Instruction *Res = foldICmpEqualityWithConstant(I))
3731 return Res;
3732
Sanjay Patel1271bf92016-07-23 13:06:49 +00003733 if (Instruction *Res = foldICmpIntrinsicWithConstant(I))
3734 return Res;
3735
Chris Lattner2188e402010-01-04 07:37:31 +00003736 // Handle icmp with constant (but not simple integer constant) RHS
3737 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3738 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3739 switch (LHSI->getOpcode()) {
3740 case Instruction::GetElementPtr:
3741 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3742 if (RHSC->isNullValue() &&
3743 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3744 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3745 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3746 break;
3747 case Instruction::PHI:
3748 // Only fold icmp into the PHI if the phi and icmp are in the same
3749 // block. If in the same block, we're encouraging jump threading. If
3750 // not, we are just pessimizing the code by making an i1 phi.
3751 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00003752 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003753 return NV;
3754 break;
3755 case Instruction::Select: {
3756 // If either operand of the select is a constant, we can fold the
3757 // comparison into the select arms, which will cause one to be
3758 // constant folded and the select turned into a bitwise or.
Craig Topperf40110f2014-04-25 05:29:35 +00003759 Value *Op1 = nullptr, *Op2 = nullptr;
Hans Wennborg083ca9b2015-10-06 23:24:35 +00003760 ConstantInt *CI = nullptr;
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003761 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003762 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003763 CI = dyn_cast<ConstantInt>(Op1);
3764 }
3765 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003766 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003767 CI = dyn_cast<ConstantInt>(Op2);
3768 }
Chris Lattner2188e402010-01-04 07:37:31 +00003769
3770 // We only want to perform this transformation if it will not lead to
3771 // additional code. This is true if either both sides of the select
3772 // fold to a constant (in which case the icmp is replaced with a select
3773 // which will usually simplify) or this is the only user of the
3774 // select (in which case we are trading a select+icmp for a simpler
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +00003775 // select+icmp) or all uses of the select can be replaced based on
3776 // dominance information ("Global cases").
3777 bool Transform = false;
3778 if (Op1 && Op2)
3779 Transform = true;
3780 else if (Op1 || Op2) {
3781 // Local case
3782 if (LHSI->hasOneUse())
3783 Transform = true;
3784 // Global cases
3785 else if (CI && !CI->isZero())
3786 // When Op1 is constant try replacing select with second operand.
3787 // Otherwise Op2 is constant and try replacing select with first
3788 // operand.
3789 Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
3790 Op1 ? 2 : 1);
3791 }
3792 if (Transform) {
Chris Lattner2188e402010-01-04 07:37:31 +00003793 if (!Op1)
3794 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
3795 RHSC, I.getName());
3796 if (!Op2)
3797 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
3798 RHSC, I.getName());
3799 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3800 }
3801 break;
3802 }
Chris Lattner2188e402010-01-04 07:37:31 +00003803 case Instruction::IntToPtr:
3804 // icmp pred inttoptr(X), null -> icmp pred X, 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003805 if (RHSC->isNullValue() &&
3806 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
Chris Lattner2188e402010-01-04 07:37:31 +00003807 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
3808 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3809 break;
3810
3811 case Instruction::Load:
3812 // Try to optimize things like "A[i] > 4" to index computations.
3813 if (GetElementPtrInst *GEP =
3814 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3815 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3816 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3817 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00003818 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Chris Lattner2188e402010-01-04 07:37:31 +00003819 return Res;
3820 }
3821 break;
3822 }
3823 }
3824
3825 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
3826 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Sanjay Patel43395062016-07-21 18:07:40 +00003827 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner2188e402010-01-04 07:37:31 +00003828 return NI;
3829 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003830 if (Instruction *NI = foldGEPICmp(GEP, Op0,
Chris Lattner2188e402010-01-04 07:37:31 +00003831 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
3832 return NI;
3833
Hans Wennborgf1f36512015-10-07 00:20:07 +00003834 // Try to optimize equality comparisons against alloca-based pointers.
3835 if (Op0->getType()->isPointerTy() && I.isEquality()) {
3836 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
3837 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003838 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003839 return New;
3840 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL)))
Sanjay Patel43395062016-07-21 18:07:40 +00003841 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0))
Hans Wennborgf1f36512015-10-07 00:20:07 +00003842 return New;
3843 }
3844
Chris Lattner2188e402010-01-04 07:37:31 +00003845 // Test to see if the operands of the icmp are casted versions of other
3846 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
3847 // now.
3848 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
Jim Grosbach129c52a2011-09-30 18:09:53 +00003849 if (Op0->getType()->isPointerTy() &&
3850 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner2188e402010-01-04 07:37:31 +00003851 // We keep moving the cast from the left operand over to the right
3852 // operand, where it can often be eliminated completely.
3853 Op0 = CI->getOperand(0);
3854
3855 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3856 // so eliminate it as well.
3857 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
3858 Op1 = CI2->getOperand(0);
3859
3860 // If Op1 is a constant, we can fold the cast into the constant.
3861 if (Op0->getType() != Op1->getType()) {
3862 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3863 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
3864 } else {
3865 // Otherwise, cast the RHS right before the icmp
3866 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
3867 }
3868 }
3869 return new ICmpInst(I.getPredicate(), Op0, Op1);
3870 }
3871 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00003872
Chris Lattner2188e402010-01-04 07:37:31 +00003873 if (isa<CastInst>(Op0)) {
3874 // Handle the special case of: icmp (cast bool to X), <cst>
3875 // This comes up when you have code like
3876 // int X = A < B;
3877 // if (X) ...
3878 // For generality, we handle any zero-extension of any operand comparison
3879 // with a constant or another cast from the same type.
3880 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Sanjay Patel43395062016-07-21 18:07:40 +00003881 if (Instruction *R = foldICmpWithCastAndCast(I))
Chris Lattner2188e402010-01-04 07:37:31 +00003882 return R;
3883 }
Chris Lattner2188e402010-01-04 07:37:31 +00003884
Duncan Sandse5220012011-02-17 07:46:37 +00003885 // Special logic for binary operators.
3886 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
3887 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
3888 if (BO0 || BO1) {
3889 CmpInst::Predicate Pred = I.getPredicate();
3890 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
3891 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3892 NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
3893 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
3894 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
3895 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3896 NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
3897 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
3898 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
3899
3900 // Analyze the case when either Op0 or Op1 is an add instruction.
3901 // 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 +00003902 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +00003903 if (BO0 && BO0->getOpcode() == Instruction::Add) {
3904 A = BO0->getOperand(0);
3905 B = BO0->getOperand(1);
3906 }
3907 if (BO1 && BO1->getOpcode() == Instruction::Add) {
3908 C = BO1->getOperand(0);
3909 D = BO1->getOperand(1);
3910 }
Duncan Sandse5220012011-02-17 07:46:37 +00003911
David Majnemer549f4f22014-11-01 09:09:51 +00003912 // icmp (X+cst) < 0 --> X < -cst
3913 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
3914 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
3915 if (!RHSC->isMinValue(/*isSigned=*/true))
3916 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
3917
Duncan Sandse5220012011-02-17 07:46:37 +00003918 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3919 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
3920 return new ICmpInst(Pred, A == Op1 ? B : A,
3921 Constant::getNullValue(Op1->getType()));
3922
3923 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3924 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
3925 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
3926 C == Op0 ? D : C);
3927
Duncan Sands84653b32011-02-18 16:25:37 +00003928 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00003929 if (A && C && (A == C || A == D || B == C || B == D) &&
3930 NoOp0WrapProblem && NoOp1WrapProblem &&
3931 // Try not to increase register pressure.
3932 BO0->hasOneUse() && BO1->hasOneUse()) {
3933 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003934 Value *Y, *Z;
3935 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003936 // C + B == C + D -> B == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003937 Y = B;
3938 Z = D;
3939 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003940 // D + B == C + D -> B == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003941 Y = B;
3942 Z = C;
3943 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003944 // A + C == C + D -> A == D
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003945 Y = A;
3946 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00003947 } else {
3948 assert(B == D);
3949 // A + D == C + D -> A == C
Duncan Sands1d3acdd2012-11-16 18:55:49 +00003950 Y = A;
3951 Z = C;
3952 }
Duncan Sandse5220012011-02-17 07:46:37 +00003953 return new ICmpInst(Pred, Y, Z);
3954 }
3955
David Majnemerb81cd632013-04-11 20:05:46 +00003956 // icmp slt (X + -1), Y -> icmp sle X, Y
3957 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
3958 match(B, m_AllOnes()))
3959 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
3960
3961 // icmp sge (X + -1), Y -> icmp sgt X, Y
3962 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
3963 match(B, m_AllOnes()))
3964 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
3965
3966 // icmp sle (X + 1), Y -> icmp slt X, Y
3967 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
3968 match(B, m_One()))
3969 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
3970
3971 // icmp sgt (X + 1), Y -> icmp sge X, Y
3972 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
3973 match(B, m_One()))
3974 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
3975
Michael Liaoc65d3862015-10-19 22:08:14 +00003976 // icmp sgt X, (Y + -1) -> icmp sge X, Y
3977 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
3978 match(D, m_AllOnes()))
3979 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
3980
3981 // icmp sle X, (Y + -1) -> icmp slt X, Y
3982 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
3983 match(D, m_AllOnes()))
3984 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
3985
3986 // icmp sge X, (Y + 1) -> icmp sgt X, Y
3987 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE &&
3988 match(D, m_One()))
3989 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
3990
3991 // icmp slt X, (Y + 1) -> icmp sle X, Y
3992 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT &&
3993 match(D, m_One()))
3994 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
3995
David Majnemerb81cd632013-04-11 20:05:46 +00003996 // if C1 has greater magnitude than C2:
3997 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
3998 // s.t. C3 = C1 - C2
3999 //
4000 // if C2 has greater magnitude than C1:
4001 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
4002 // s.t. C3 = C2 - C1
4003 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
4004 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
4005 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
4006 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
4007 const APInt &AP1 = C1->getValue();
4008 const APInt &AP2 = C2->getValue();
4009 if (AP1.isNegative() == AP2.isNegative()) {
4010 APInt AP1Abs = C1->getValue().abs();
4011 APInt AP2Abs = C2->getValue().abs();
4012 if (AP1Abs.uge(AP2Abs)) {
4013 ConstantInt *C3 = Builder->getInt(AP1 - AP2);
4014 Value *NewAdd = Builder->CreateNSWAdd(A, C3);
4015 return new ICmpInst(Pred, NewAdd, C);
4016 } else {
4017 ConstantInt *C3 = Builder->getInt(AP2 - AP1);
4018 Value *NewAdd = Builder->CreateNSWAdd(C, C3);
4019 return new ICmpInst(Pred, A, NewAdd);
4020 }
4021 }
4022 }
4023
4024
Duncan Sandse5220012011-02-17 07:46:37 +00004025 // Analyze the case when either Op0 or Op1 is a sub instruction.
4026 // 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 +00004027 A = nullptr;
4028 B = nullptr;
4029 C = nullptr;
4030 D = nullptr;
4031 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
4032 A = BO0->getOperand(0);
4033 B = BO0->getOperand(1);
4034 }
4035 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
4036 C = BO1->getOperand(0);
4037 D = BO1->getOperand(1);
4038 }
Duncan Sandse5220012011-02-17 07:46:37 +00004039
Duncan Sands84653b32011-02-18 16:25:37 +00004040 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
4041 if (A == Op1 && NoOp0WrapProblem)
4042 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
4043
4044 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
4045 if (C == Op0 && NoOp1WrapProblem)
4046 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
4047
4048 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
Duncan Sandse5220012011-02-17 07:46:37 +00004049 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
4050 // Try not to increase register pressure.
4051 BO0->hasOneUse() && BO1->hasOneUse())
4052 return new ICmpInst(Pred, A, C);
4053
Duncan Sands84653b32011-02-18 16:25:37 +00004054 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
4055 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
4056 // Try not to increase register pressure.
4057 BO0->hasOneUse() && BO1->hasOneUse())
4058 return new ICmpInst(Pred, D, B);
4059
David Majnemer186c9422014-05-15 00:02:20 +00004060 // icmp (0-X) < cst --> x > -cst
4061 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
4062 Value *X;
4063 if (match(BO0, m_Neg(m_Value(X))))
4064 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
4065 if (!RHSC->isMinValue(/*isSigned=*/true))
4066 return new ICmpInst(I.getSwappedPredicate(), X,
4067 ConstantExpr::getNeg(RHSC));
4068 }
4069
Craig Topperf40110f2014-04-25 05:29:35 +00004070 BinaryOperator *SRem = nullptr;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004071 // icmp (srem X, Y), Y
Nick Lewycky25cc3382011-03-05 04:28:48 +00004072 if (BO0 && BO0->getOpcode() == Instruction::SRem &&
4073 Op1 == BO0->getOperand(1))
4074 SRem = BO0;
Nick Lewyckyafc80982011-03-08 06:29:47 +00004075 // icmp Y, (srem X, Y)
Nick Lewycky25cc3382011-03-05 04:28:48 +00004076 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
4077 Op0 == BO1->getOperand(1))
4078 SRem = BO1;
4079 if (SRem) {
4080 // We don't check hasOneUse to avoid increasing register pressure because
4081 // the value we use is the same value this instruction was already using.
4082 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
4083 default: break;
4084 case ICmpInst::ICMP_EQ:
Sanjay Patel4b198802016-02-01 22:23:39 +00004085 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004086 case ICmpInst::ICMP_NE:
Sanjay Patel4b198802016-02-01 22:23:39 +00004087 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
Nick Lewycky25cc3382011-03-05 04:28:48 +00004088 case ICmpInst::ICMP_SGT:
4089 case ICmpInst::ICMP_SGE:
4090 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4091 Constant::getAllOnesValue(SRem->getType()));
4092 case ICmpInst::ICMP_SLT:
4093 case ICmpInst::ICMP_SLE:
4094 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4095 Constant::getNullValue(SRem->getType()));
4096 }
4097 }
4098
Duncan Sandse5220012011-02-17 07:46:37 +00004099 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
4100 BO0->hasOneUse() && BO1->hasOneUse() &&
4101 BO0->getOperand(1) == BO1->getOperand(1)) {
4102 switch (BO0->getOpcode()) {
4103 default: break;
4104 case Instruction::Add:
4105 case Instruction::Sub:
4106 case Instruction::Xor:
4107 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4108 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4109 BO1->getOperand(0));
4110 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
4111 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4112 if (CI->getValue().isSignBit()) {
4113 ICmpInst::Predicate Pred = I.isSigned()
4114 ? I.getUnsignedPredicate()
4115 : I.getSignedPredicate();
4116 return new ICmpInst(Pred, BO0->getOperand(0),
4117 BO1->getOperand(0));
Chris Lattner2188e402010-01-04 07:37:31 +00004118 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004119
David Majnemerf8853ae2016-02-01 17:37:56 +00004120 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) {
Duncan Sandse5220012011-02-17 07:46:37 +00004121 ICmpInst::Predicate Pred = I.isSigned()
4122 ? I.getUnsignedPredicate()
4123 : I.getSignedPredicate();
4124 Pred = I.getSwappedPredicate(Pred);
4125 return new ICmpInst(Pred, BO0->getOperand(0),
4126 BO1->getOperand(0));
4127 }
Chris Lattner2188e402010-01-04 07:37:31 +00004128 }
Duncan Sandse5220012011-02-17 07:46:37 +00004129 break;
4130 case Instruction::Mul:
4131 if (!I.isEquality())
4132 break;
4133
4134 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
4135 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
4136 // Mask = -1 >> count-trailing-zeros(Cst).
4137 if (!CI->isZero() && !CI->isOne()) {
4138 const APInt &AP = CI->getValue();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004139 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Duncan Sandse5220012011-02-17 07:46:37 +00004140 APInt::getLowBitsSet(AP.getBitWidth(),
4141 AP.getBitWidth() -
4142 AP.countTrailingZeros()));
4143 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
4144 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
4145 return new ICmpInst(I.getPredicate(), And1, And2);
4146 }
4147 }
4148 break;
Nick Lewycky9719a712011-03-05 05:19:11 +00004149 case Instruction::UDiv:
4150 case Instruction::LShr:
4151 if (I.isSigned())
4152 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00004153 LLVM_FALLTHROUGH;
Nick Lewycky9719a712011-03-05 05:19:11 +00004154 case Instruction::SDiv:
4155 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00004156 if (!BO0->isExact() || !BO1->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00004157 break;
4158 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4159 BO1->getOperand(0));
4160 case Instruction::Shl: {
4161 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4162 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4163 if (!NUW && !NSW)
4164 break;
4165 if (!NSW && I.isSigned())
4166 break;
4167 return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
4168 BO1->getOperand(0));
4169 }
Chris Lattner2188e402010-01-04 07:37:31 +00004170 }
4171 }
Sanjoy Dasc86c1622015-08-21 22:22:37 +00004172
4173 if (BO0) {
4174 // Transform A & (L - 1) `ult` L --> L != 0
4175 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4176 auto BitwiseAnd =
4177 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value()));
4178
4179 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) {
4180 auto *Zero = Constant::getNullValue(BO0->getType());
4181 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4182 }
4183 }
Chris Lattner2188e402010-01-04 07:37:31 +00004184 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004185
Chris Lattner2188e402010-01-04 07:37:31 +00004186 { Value *A, *B;
David Majnemer1a08acc2013-04-12 17:25:07 +00004187 // Transform (A & ~B) == 0 --> (A & B) != 0
4188 // and (A & ~B) != 0 --> (A & B) == 0
4189 // if A is a power of 2.
4190 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
Chandler Carruth66b31302015-01-04 12:03:27 +00004191 match(Op1, m_Zero()) &&
Justin Bogner99798402016-08-05 01:06:44 +00004192 isKnownToBeAPowerOfTwo(A, DL, false, 0, &AC, &I, &DT) && I.isEquality())
David Majnemer1a08acc2013-04-12 17:25:07 +00004193 return new ICmpInst(I.getInversePredicate(),
4194 Builder->CreateAnd(A, B),
4195 Op1);
4196
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004197 // ~x < ~y --> y < x
4198 // ~x < cst --> ~cst < x
4199 if (match(Op0, m_Not(m_Value(A)))) {
4200 if (match(Op1, m_Not(m_Value(B))))
4201 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner497459d2011-01-15 05:42:47 +00004202 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
Chris Lattnerf3c4eef2011-01-15 05:41:33 +00004203 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
4204 }
Chris Lattner5e0c0c72010-12-19 19:37:52 +00004205
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004206 Instruction *AddI = nullptr;
4207 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
4208 m_Instruction(AddI))) &&
4209 isa<IntegerType>(A->getType())) {
4210 Value *Result;
4211 Constant *Overflow;
4212 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
4213 Overflow)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00004214 replaceInstUsesWith(*AddI, Result);
4215 return replaceInstUsesWith(I, Overflow);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00004216 }
4217 }
Serge Pavlov4bb54d52014-04-13 18:23:41 +00004218
4219 // (zext a) * (zext b) --> llvm.umul.with.overflow.
4220 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4221 if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
4222 return R;
4223 }
4224 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
4225 if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
4226 return R;
4227 }
Chris Lattner2188e402010-01-04 07:37:31 +00004228 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004229
Chris Lattner2188e402010-01-04 07:37:31 +00004230 if (I.isEquality()) {
4231 Value *A, *B, *C, *D;
Duncan Sands84653b32011-02-18 16:25:37 +00004232
Chris Lattner2188e402010-01-04 07:37:31 +00004233 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4234 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4235 Value *OtherVal = A == Op1 ? B : A;
4236 return new ICmpInst(I.getPredicate(), OtherVal,
4237 Constant::getNullValue(A->getType()));
4238 }
4239
4240 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4241 // A^c1 == C^c2 --> A == C^(c1^c2)
4242 ConstantInt *C1, *C2;
4243 if (match(B, m_ConstantInt(C1)) &&
4244 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Jakub Staszakbddea112013-06-06 20:18:46 +00004245 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004246 Value *Xor = Builder->CreateXor(C, NC);
Chris Lattner2188e402010-01-04 07:37:31 +00004247 return new ICmpInst(I.getPredicate(), A, Xor);
4248 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004249
Chris Lattner2188e402010-01-04 07:37:31 +00004250 // A^B == A^D -> B == D
4251 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4252 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4253 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4254 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4255 }
4256 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004257
Chris Lattner2188e402010-01-04 07:37:31 +00004258 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4259 (A == Op0 || B == Op0)) {
4260 // A == (A^B) -> B == 0
4261 Value *OtherVal = A == Op0 ? B : A;
4262 return new ICmpInst(I.getPredicate(), OtherVal,
4263 Constant::getNullValue(A->getType()));
4264 }
4265
Chris Lattner2188e402010-01-04 07:37:31 +00004266 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
Jim Grosbach129c52a2011-09-30 18:09:53 +00004267 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
Chris Lattner31b106d2011-04-26 20:02:45 +00004268 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
Craig Topperf40110f2014-04-25 05:29:35 +00004269 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004270
Chris Lattner2188e402010-01-04 07:37:31 +00004271 if (A == C) {
4272 X = B; Y = D; Z = A;
4273 } else if (A == D) {
4274 X = B; Y = C; Z = A;
4275 } else if (B == C) {
4276 X = A; Y = D; Z = B;
4277 } else if (B == D) {
4278 X = A; Y = C; Z = B;
4279 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004280
Chris Lattner2188e402010-01-04 07:37:31 +00004281 if (X) { // Build (X^Y) & Z
Benjamin Kramer547b6c52011-09-27 20:39:19 +00004282 Op1 = Builder->CreateXor(X, Y);
4283 Op1 = Builder->CreateAnd(Op1, Z);
Chris Lattner2188e402010-01-04 07:37:31 +00004284 I.setOperand(0, Op1);
4285 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4286 return &I;
4287 }
4288 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004289
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004290 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
Benjamin Kramer21501452012-06-11 08:01:25 +00004291 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B)
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004292 ConstantInt *Cst1;
Benjamin Kramer21501452012-06-11 08:01:25 +00004293 if ((Op0->hasOneUse() &&
4294 match(Op0, m_ZExt(m_Value(A))) &&
4295 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
4296 (Op1->hasOneUse() &&
4297 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
4298 match(Op1, m_ZExt(m_Value(A))))) {
Benjamin Kramer8b8a7692012-06-10 20:35:00 +00004299 APInt Pow2 = Cst1->getValue() + 1;
4300 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
4301 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
4302 return new ICmpInst(I.getPredicate(), A,
4303 Builder->CreateTrunc(B, A->getType()));
4304 }
4305
Benjamin Kramer03f3e242013-11-16 16:00:48 +00004306 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4307 // For lshr and ashr pairs.
4308 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4309 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
4310 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
4311 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
4312 unsigned TypeBits = Cst1->getBitWidth();
4313 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4314 if (ShAmt < TypeBits && ShAmt != 0) {
4315 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
4316 ? ICmpInst::ICMP_UGE
4317 : ICmpInst::ICMP_ULT;
4318 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4319 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4320 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
4321 }
4322 }
4323
Benjamin Kramer7fa8c432015-03-26 17:12:06 +00004324 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4325 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4326 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4327 unsigned TypeBits = Cst1->getBitWidth();
4328 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4329 if (ShAmt < TypeBits && ShAmt != 0) {
4330 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
4331 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4332 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
4333 I.getName() + ".mask");
4334 return new ICmpInst(I.getPredicate(), And,
4335 Constant::getNullValue(Cst1->getType()));
4336 }
4337 }
4338
Chris Lattner1b06c712011-04-26 20:18:20 +00004339 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4340 // "icmp (and X, mask), cst"
4341 uint64_t ShAmt = 0;
Chris Lattner1b06c712011-04-26 20:18:20 +00004342 if (Op0->hasOneUse() &&
4343 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
4344 m_ConstantInt(ShAmt))))) &&
4345 match(Op1, m_ConstantInt(Cst1)) &&
4346 // Only do this when A has multiple uses. This is most important to do
4347 // when it exposes other optimizations.
4348 !A->hasOneUse()) {
4349 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004350
Chris Lattner1b06c712011-04-26 20:18:20 +00004351 if (ShAmt < ASize) {
4352 APInt MaskV =
4353 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4354 MaskV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004355
Chris Lattner1b06c712011-04-26 20:18:20 +00004356 APInt CmpV = Cst1->getValue().zext(ASize);
4357 CmpV <<= ShAmt;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004358
Chris Lattner1b06c712011-04-26 20:18:20 +00004359 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
4360 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
4361 }
4362 }
Chris Lattner2188e402010-01-04 07:37:31 +00004363 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004364
David Majnemerc1eca5a2014-11-06 23:23:30 +00004365 // The 'cmpxchg' instruction returns an aggregate containing the old value and
4366 // an i1 which indicates whether or not we successfully did the swap.
4367 //
4368 // Replace comparisons between the old value and the expected value with the
4369 // indicator that 'cmpxchg' returns.
4370 //
4371 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
4372 // spuriously fail. In those cases, the old value may equal the expected
4373 // value but it is possible for the swap to not occur.
4374 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4375 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4376 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4377 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4378 !ACXI->isWeak())
4379 return ExtractValueInst::Create(ACXI, 1);
4380
Chris Lattner2188e402010-01-04 07:37:31 +00004381 {
4382 Value *X; ConstantInt *Cst;
4383 // icmp X+Cst, X
4384 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004385 return foldICmpAddOpConst(I, X, Cst, I.getPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004386
4387 // icmp X, X+Cst
4388 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Sanjay Patel43395062016-07-21 18:07:40 +00004389 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate());
Chris Lattner2188e402010-01-04 07:37:31 +00004390 }
Craig Topperf40110f2014-04-25 05:29:35 +00004391 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004392}
4393
Sanjay Patel5f0217f2016-06-05 16:46:18 +00004394/// Fold fcmp ([us]itofp x, cst) if possible.
Sanjay Patel43395062016-07-21 18:07:40 +00004395Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
Chris Lattner2188e402010-01-04 07:37:31 +00004396 Constant *RHSC) {
Craig Topperf40110f2014-04-25 05:29:35 +00004397 if (!isa<ConstantFP>(RHSC)) return nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004398 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004399
Chris Lattner2188e402010-01-04 07:37:31 +00004400 // Get the width of the mantissa. We don't want to hack on conversions that
4401 // might lose information from the integer, e.g. "i64 -> float"
4402 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Craig Topperf40110f2014-04-25 05:29:35 +00004403 if (MantissaWidth == -1) return nullptr; // Unknown.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004404
Matt Arsenault55e73122015-01-06 15:50:59 +00004405 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4406
Chris Lattner2188e402010-01-04 07:37:31 +00004407 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004408
Matt Arsenault55e73122015-01-06 15:50:59 +00004409 if (I.isEquality()) {
4410 FCmpInst::Predicate P = I.getPredicate();
4411 bool IsExact = false;
4412 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
4413 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
4414
4415 // If the floating point constant isn't an integer value, we know if we will
4416 // ever compare equal / not equal to it.
4417 if (!IsExact) {
4418 // TODO: Can never be -0.0 and other non-representable values
4419 APFloat RHSRoundInt(RHS);
4420 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
4421 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
4422 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
Sanjay Patel4b198802016-02-01 22:23:39 +00004423 return replaceInstUsesWith(I, Builder->getFalse());
Matt Arsenault55e73122015-01-06 15:50:59 +00004424
4425 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
Sanjay Patel4b198802016-02-01 22:23:39 +00004426 return replaceInstUsesWith(I, Builder->getTrue());
Matt Arsenault55e73122015-01-06 15:50:59 +00004427 }
4428 }
4429
4430 // TODO: If the constant is exactly representable, is it always OK to do
4431 // equality compares as integer?
4432 }
4433
Arch D. Robison8ed08542015-09-15 17:51:59 +00004434 // Check to see that the input is converted from an integer type that is small
4435 // enough that preserves all bits. TODO: check here for "known" sign bits.
4436 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4437 unsigned InputSize = IntTy->getScalarSizeInBits();
Matt Arsenault55e73122015-01-06 15:50:59 +00004438
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004439 // Following test does NOT adjust InputSize downwards for signed inputs,
4440 // because the most negative value still requires all the mantissa bits
Arch D. Robison8ed08542015-09-15 17:51:59 +00004441 // to distinguish it from one less than that value.
4442 if ((int)InputSize > MantissaWidth) {
4443 // Conversion would lose accuracy. Check if loss can impact comparison.
4444 int Exp = ilogb(RHS);
4445 if (Exp == APFloat::IEK_Inf) {
4446 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004447 if (MaxExponent < (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004448 // Conversion could create infinity.
4449 return nullptr;
4450 } else {
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004451 // Note that if RHS is zero or NaN, then Exp is negative
Arch D. Robison8ed08542015-09-15 17:51:59 +00004452 // and first condition is trivially false.
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00004453 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
Arch D. Robison8ed08542015-09-15 17:51:59 +00004454 // Conversion could affect comparison.
4455 return nullptr;
4456 }
4457 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004458
Chris Lattner2188e402010-01-04 07:37:31 +00004459 // Otherwise, we can potentially simplify the comparison. We know that it
4460 // will always come through as an integer value and we know the constant is
4461 // not a NAN (it would have been previously simplified).
4462 assert(!RHS.isNaN() && "NaN comparison not already folded!");
Jim Grosbach129c52a2011-09-30 18:09:53 +00004463
Chris Lattner2188e402010-01-04 07:37:31 +00004464 ICmpInst::Predicate Pred;
4465 switch (I.getPredicate()) {
4466 default: llvm_unreachable("Unexpected predicate!");
4467 case FCmpInst::FCMP_UEQ:
4468 case FCmpInst::FCMP_OEQ:
4469 Pred = ICmpInst::ICMP_EQ;
4470 break;
4471 case FCmpInst::FCMP_UGT:
4472 case FCmpInst::FCMP_OGT:
4473 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
4474 break;
4475 case FCmpInst::FCMP_UGE:
4476 case FCmpInst::FCMP_OGE:
4477 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
4478 break;
4479 case FCmpInst::FCMP_ULT:
4480 case FCmpInst::FCMP_OLT:
4481 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
4482 break;
4483 case FCmpInst::FCMP_ULE:
4484 case FCmpInst::FCMP_OLE:
4485 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
4486 break;
4487 case FCmpInst::FCMP_UNE:
4488 case FCmpInst::FCMP_ONE:
4489 Pred = ICmpInst::ICMP_NE;
4490 break;
4491 case FCmpInst::FCMP_ORD:
Sanjay Patel4b198802016-02-01 22:23:39 +00004492 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004493 case FCmpInst::FCMP_UNO:
Sanjay Patel4b198802016-02-01 22:23:39 +00004494 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004495 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004496
Chris Lattner2188e402010-01-04 07:37:31 +00004497 // Now we know that the APFloat is a normal number, zero or inf.
Jim Grosbach129c52a2011-09-30 18:09:53 +00004498
Chris Lattner2188e402010-01-04 07:37:31 +00004499 // See if the FP constant is too large for the integer. For example,
4500 // comparing an i8 to 300.0.
4501 unsigned IntWidth = IntTy->getScalarSizeInBits();
Jim Grosbach129c52a2011-09-30 18:09:53 +00004502
Chris Lattner2188e402010-01-04 07:37:31 +00004503 if (!LHSUnsigned) {
4504 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4505 // and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004506 APFloat SMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004507 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4508 APFloat::rmNearestTiesToEven);
4509 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4510 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4511 Pred == ICmpInst::ICMP_SLE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004512 return replaceInstUsesWith(I, Builder->getTrue());
4513 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004514 }
4515 } else {
4516 // If the RHS value is > UnsignedMax, fold the comparison. This handles
4517 // +INF and large values.
Michael Gottesman79b09672013-06-27 21:58:19 +00004518 APFloat UMax(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004519 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
4520 APFloat::rmNearestTiesToEven);
4521 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
4522 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
4523 Pred == ICmpInst::ICMP_ULE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004524 return replaceInstUsesWith(I, Builder->getTrue());
4525 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004526 }
4527 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004528
Chris Lattner2188e402010-01-04 07:37:31 +00004529 if (!LHSUnsigned) {
4530 // See if the RHS value is < SignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004531 APFloat SMin(RHS.getSemantics());
Chris Lattner2188e402010-01-04 07:37:31 +00004532 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4533 APFloat::rmNearestTiesToEven);
4534 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4535 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4536 Pred == ICmpInst::ICMP_SGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004537 return replaceInstUsesWith(I, Builder->getTrue());
4538 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004539 }
Devang Patel698452b2012-02-13 23:05:18 +00004540 } else {
4541 // See if the RHS value is < UnsignedMin.
Michael Gottesman79b09672013-06-27 21:58:19 +00004542 APFloat SMin(RHS.getSemantics());
Devang Patel698452b2012-02-13 23:05:18 +00004543 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
4544 APFloat::rmNearestTiesToEven);
4545 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
4546 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
4547 Pred == ICmpInst::ICMP_UGE)
Sanjay Patel4b198802016-02-01 22:23:39 +00004548 return replaceInstUsesWith(I, Builder->getTrue());
4549 return replaceInstUsesWith(I, Builder->getFalse());
Devang Patel698452b2012-02-13 23:05:18 +00004550 }
Chris Lattner2188e402010-01-04 07:37:31 +00004551 }
4552
4553 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
4554 // [0, UMAX], but it may still be fractional. See if it is fractional by
4555 // casting the FP value to the integer value and back, checking for equality.
4556 // Don't do this for zero, because -0.0 is not fractional.
4557 Constant *RHSInt = LHSUnsigned
4558 ? ConstantExpr::getFPToUI(RHSC, IntTy)
4559 : ConstantExpr::getFPToSI(RHSC, IntTy);
4560 if (!RHS.isZero()) {
4561 bool Equal = LHSUnsigned
4562 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
4563 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
4564 if (!Equal) {
4565 // If we had a comparison against a fractional value, we have to adjust
4566 // the compare predicate and sometimes the value. RHSC is rounded towards
4567 // zero at this point.
4568 switch (Pred) {
4569 default: llvm_unreachable("Unexpected integer comparison!");
4570 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Sanjay Patel4b198802016-02-01 22:23:39 +00004571 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004572 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Sanjay Patel4b198802016-02-01 22:23:39 +00004573 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004574 case ICmpInst::ICMP_ULE:
4575 // (float)int <= 4.4 --> int <= 4
4576 // (float)int <= -4.4 --> false
4577 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004578 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004579 break;
4580 case ICmpInst::ICMP_SLE:
4581 // (float)int <= 4.4 --> int <= 4
4582 // (float)int <= -4.4 --> int < -4
4583 if (RHS.isNegative())
4584 Pred = ICmpInst::ICMP_SLT;
4585 break;
4586 case ICmpInst::ICMP_ULT:
4587 // (float)int < -4.4 --> false
4588 // (float)int < 4.4 --> int <= 4
4589 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004590 return replaceInstUsesWith(I, Builder->getFalse());
Chris Lattner2188e402010-01-04 07:37:31 +00004591 Pred = ICmpInst::ICMP_ULE;
4592 break;
4593 case ICmpInst::ICMP_SLT:
4594 // (float)int < -4.4 --> int < -4
4595 // (float)int < 4.4 --> int <= 4
4596 if (!RHS.isNegative())
4597 Pred = ICmpInst::ICMP_SLE;
4598 break;
4599 case ICmpInst::ICMP_UGT:
4600 // (float)int > 4.4 --> int > 4
4601 // (float)int > -4.4 --> true
4602 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004603 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004604 break;
4605 case ICmpInst::ICMP_SGT:
4606 // (float)int > 4.4 --> int > 4
4607 // (float)int > -4.4 --> int >= -4
4608 if (RHS.isNegative())
4609 Pred = ICmpInst::ICMP_SGE;
4610 break;
4611 case ICmpInst::ICMP_UGE:
4612 // (float)int >= -4.4 --> true
4613 // (float)int >= 4.4 --> int > 4
Bob Wilson61f3ad52012-08-07 22:35:16 +00004614 if (RHS.isNegative())
Sanjay Patel4b198802016-02-01 22:23:39 +00004615 return replaceInstUsesWith(I, Builder->getTrue());
Chris Lattner2188e402010-01-04 07:37:31 +00004616 Pred = ICmpInst::ICMP_UGT;
4617 break;
4618 case ICmpInst::ICMP_SGE:
4619 // (float)int >= -4.4 --> int >= -4
4620 // (float)int >= 4.4 --> int > 4
4621 if (!RHS.isNegative())
4622 Pred = ICmpInst::ICMP_SGT;
4623 break;
4624 }
4625 }
4626 }
4627
4628 // Lower this FP comparison into an appropriate integer version of the
4629 // comparison.
4630 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4631}
4632
4633Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4634 bool Changed = false;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004635
Chris Lattner2188e402010-01-04 07:37:31 +00004636 /// Orders the operands of the compare so that they are listed from most
4637 /// complex to least complex. This puts constants before unary operators,
4638 /// before binary operators.
4639 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
4640 I.swapOperands();
4641 Changed = true;
4642 }
4643
4644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Jim Grosbach129c52a2011-09-30 18:09:53 +00004645
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004646 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1,
Justin Bogner99798402016-08-05 01:06:44 +00004647 I.getFastMathFlags(), DL, &TLI, &DT, &AC, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00004648 return replaceInstUsesWith(I, V);
Chris Lattner2188e402010-01-04 07:37:31 +00004649
4650 // Simplify 'fcmp pred X, X'
4651 if (Op0 == Op1) {
4652 switch (I.getPredicate()) {
4653 default: llvm_unreachable("Unknown predicate!");
4654 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4655 case FCmpInst::FCMP_ULT: // True if unordered or less than
4656 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4657 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4658 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4659 I.setPredicate(FCmpInst::FCMP_UNO);
4660 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4661 return &I;
Jim Grosbach129c52a2011-09-30 18:09:53 +00004662
Chris Lattner2188e402010-01-04 07:37:31 +00004663 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4664 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4665 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4666 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4667 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4668 I.setPredicate(FCmpInst::FCMP_ORD);
4669 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4670 return &I;
4671 }
4672 }
Jim Grosbach129c52a2011-09-30 18:09:53 +00004673
James Molloy2b21a7c2015-05-20 18:41:25 +00004674 // Test if the FCmpInst instruction is used exclusively by a select as
4675 // part of a minimum or maximum operation. If so, refrain from doing
4676 // any other folding. This helps out other analyses which understand
4677 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
4678 // and CodeGen. And in this case, at least one of the comparison
4679 // operands has at least one user besides the compare (the select),
4680 // which would often largely negate the benefit of folding anyway.
4681 if (I.hasOneUse())
4682 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
4683 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
4684 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
4685 return nullptr;
4686
Chris Lattner2188e402010-01-04 07:37:31 +00004687 // Handle fcmp with constant RHS
4688 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4689 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4690 switch (LHSI->getOpcode()) {
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004691 case Instruction::FPExt: {
4692 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
4693 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
4694 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
4695 if (!RHSF)
4696 break;
4697
4698 const fltSemantics *Sem;
4699 // FIXME: This shouldn't be here.
Dan Gohman518cda42011-12-17 00:04:22 +00004700 if (LHSExt->getSrcTy()->isHalfTy())
4701 Sem = &APFloat::IEEEhalf;
4702 else if (LHSExt->getSrcTy()->isFloatTy())
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004703 Sem = &APFloat::IEEEsingle;
4704 else if (LHSExt->getSrcTy()->isDoubleTy())
4705 Sem = &APFloat::IEEEdouble;
4706 else if (LHSExt->getSrcTy()->isFP128Ty())
4707 Sem = &APFloat::IEEEquad;
4708 else if (LHSExt->getSrcTy()->isX86_FP80Ty())
4709 Sem = &APFloat::x87DoubleExtended;
Ulrich Weigand6a9bb512012-10-30 12:33:18 +00004710 else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
4711 Sem = &APFloat::PPCDoubleDouble;
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004712 else
4713 break;
4714
4715 bool Lossy;
4716 APFloat F = RHSF->getValueAPF();
4717 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
4718
Jim Grosbach24ff8342011-09-30 18:45:50 +00004719 // Avoid lossy conversions and denormals. Zero is a special case
4720 // that's OK to convert.
Jim Grosbach011dafb2011-09-30 19:58:46 +00004721 APFloat Fabs = F;
4722 Fabs.clearSign();
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004723 if (!Lossy &&
Jim Grosbach011dafb2011-09-30 19:58:46 +00004724 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
4725 APFloat::cmpLessThan) || Fabs.isZero()))
Jim Grosbach24ff8342011-09-30 18:45:50 +00004726
Benjamin Kramercbb18e92011-03-31 10:12:07 +00004727 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4728 ConstantFP::get(RHSC->getContext(), F));
4729 break;
4730 }
Chris Lattner2188e402010-01-04 07:37:31 +00004731 case Instruction::PHI:
4732 // Only fold fcmp into the PHI if the phi and fcmp are in the same
4733 // block. If in the same block, we're encouraging jump threading. If
4734 // not, we are just pessimizing the code by making an i1 phi.
4735 if (LHSI->getParent() == I.getParent())
Chris Lattnerea7131a2011-01-16 05:14:26 +00004736 if (Instruction *NV = FoldOpIntoPhi(I))
Chris Lattner2188e402010-01-04 07:37:31 +00004737 return NV;
4738 break;
4739 case Instruction::SIToFP:
4740 case Instruction::UIToFP:
Sanjay Patel43395062016-07-21 18:07:40 +00004741 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
Chris Lattner2188e402010-01-04 07:37:31 +00004742 return NV;
4743 break;
Benjamin Kramera8c5d082011-03-31 10:12:15 +00004744 case Instruction::FSub: {
4745 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
4746 Value *Op;
4747 if (match(LHSI, m_FNeg(m_Value(Op))))
4748 return new FCmpInst(I.getSwappedPredicate(), Op,
4749 ConstantExpr::getFNeg(RHSC));
4750 break;
4751 }
Dan Gohman94732022010-02-24 06:46:09 +00004752 case Instruction::Load:
4753 if (GetElementPtrInst *GEP =
4754 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
4755 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
4756 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
4757 !cast<LoadInst>(LHSI)->isVolatile())
Sanjay Patel43395062016-07-21 18:07:40 +00004758 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
Dan Gohman94732022010-02-24 06:46:09 +00004759 return Res;
4760 }
4761 break;
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004762 case Instruction::Call: {
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004763 if (!RHSC->isNullValue())
4764 break;
4765
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004766 CallInst *CI = cast<CallInst>(LHSI);
Justin Bogner99798402016-08-05 01:06:44 +00004767 Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI);
David Majnemer2e02ba72016-04-15 17:21:03 +00004768 if (IID != Intrinsic::fabs)
Matt Arsenaultb935d9d2015-01-08 20:09:34 +00004769 break;
4770
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004771 // Various optimization for fabs compared with zero.
David Majnemer2e02ba72016-04-15 17:21:03 +00004772 switch (I.getPredicate()) {
4773 default:
4774 break;
4775 // fabs(x) < 0 --> false
4776 case FCmpInst::FCMP_OLT:
4777 llvm_unreachable("handled by SimplifyFCmpInst");
4778 // fabs(x) > 0 --> x != 0
4779 case FCmpInst::FCMP_OGT:
4780 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
4781 // fabs(x) <= 0 --> x == 0
4782 case FCmpInst::FCMP_OLE:
4783 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
4784 // fabs(x) >= 0 --> !isnan(x)
4785 case FCmpInst::FCMP_OGE:
4786 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
4787 // fabs(x) == 0 --> x == 0
4788 // fabs(x) != 0 --> x != 0
4789 case FCmpInst::FCMP_OEQ:
4790 case FCmpInst::FCMP_UEQ:
4791 case FCmpInst::FCMP_ONE:
4792 case FCmpInst::FCMP_UNE:
4793 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
Benjamin Kramer8c2a7332012-08-18 20:06:47 +00004794 }
4795 }
Chris Lattner2188e402010-01-04 07:37:31 +00004796 }
Chris Lattner2188e402010-01-04 07:37:31 +00004797 }
4798
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004799 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
Benjamin Kramerd159d942011-03-31 10:12:22 +00004800 Value *X, *Y;
4801 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
Benjamin Kramerbe209ab2011-03-31 10:46:03 +00004802 return new FCmpInst(I.getSwappedPredicate(), X, Y);
Benjamin Kramerd159d942011-03-31 10:12:22 +00004803
Benjamin Kramer2ccfbc82011-03-31 10:11:58 +00004804 // fcmp (fpext x), (fpext y) -> fcmp x, y
4805 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
4806 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
4807 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
4808 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
4809 RHSExt->getOperand(0));
4810
Craig Topperf40110f2014-04-25 05:29:35 +00004811 return Changed ? &I : nullptr;
Chris Lattner2188e402010-01-04 07:37:31 +00004812}