1202375Srdivacky//===- InstCombineCompares.cpp --------------------------------------------===//
2202375Srdivacky//
3202375Srdivacky//                     The LLVM Compiler Infrastructure
4202375Srdivacky//
5202375Srdivacky// This file is distributed under the University of Illinois Open Source
6202375Srdivacky// License. See LICENSE.TXT for details.
7202375Srdivacky//
8202375Srdivacky//===----------------------------------------------------------------------===//
9202375Srdivacky//
10202375Srdivacky// This file implements the visitICmp and visitFCmp functions.
11202375Srdivacky//
12202375Srdivacky//===----------------------------------------------------------------------===//
13202375Srdivacky
14202375Srdivacky#include "InstCombine.h"
15226890Sdim#include "llvm/Analysis/ConstantFolding.h"
16202375Srdivacky#include "llvm/Analysis/InstructionSimplify.h"
17202375Srdivacky#include "llvm/Analysis/MemoryBuiltins.h"
18252723Sdim#include "llvm/IR/DataLayout.h"
19252723Sdim#include "llvm/IR/IntrinsicInst.h"
20202375Srdivacky#include "llvm/Support/ConstantRange.h"
21202375Srdivacky#include "llvm/Support/GetElementPtrTypeIterator.h"
22202375Srdivacky#include "llvm/Support/PatternMatch.h"
23252723Sdim#include "llvm/Target/TargetLibraryInfo.h"
24202375Srdivackyusing namespace llvm;
25202375Srdivackyusing namespace PatternMatch;
26202375Srdivacky
27218893Sdimstatic ConstantInt *getOne(Constant *C) {
28218893Sdim  return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
29218893Sdim}
30218893Sdim
31202375Srdivacky/// AddOne - Add one to a ConstantInt
32202375Srdivackystatic Constant *AddOne(Constant *C) {
33202375Srdivacky  return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
34202375Srdivacky}
35202375Srdivacky/// SubOne - Subtract one from a ConstantInt
36218893Sdimstatic Constant *SubOne(Constant *C) {
37218893Sdim  return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
38202375Srdivacky}
39202375Srdivacky
40202375Srdivackystatic ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
41202375Srdivacky  return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
42202375Srdivacky}
43202375Srdivacky
44202375Srdivackystatic bool HasAddOverflow(ConstantInt *Result,
45202375Srdivacky                           ConstantInt *In1, ConstantInt *In2,
46202375Srdivacky                           bool IsSigned) {
47224145Sdim  if (!IsSigned)
48202375Srdivacky    return Result->getValue().ult(In1->getValue());
49224145Sdim
50224145Sdim  if (In2->isNegative())
51224145Sdim    return Result->getValue().sgt(In1->getValue());
52224145Sdim  return Result->getValue().slt(In1->getValue());
53202375Srdivacky}
54202375Srdivacky
55202375Srdivacky/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
56202375Srdivacky/// overflowed for this type.
57202375Srdivackystatic bool AddWithOverflow(Constant *&Result, Constant *In1,
58202375Srdivacky                            Constant *In2, bool IsSigned = false) {
59202375Srdivacky  Result = ConstantExpr::getAdd(In1, In2);
60202375Srdivacky
61226890Sdim  if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
62202375Srdivacky    for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
63202375Srdivacky      Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
64202375Srdivacky      if (HasAddOverflow(ExtractElement(Result, Idx),
65202375Srdivacky                         ExtractElement(In1, Idx),
66202375Srdivacky                         ExtractElement(In2, Idx),
67202375Srdivacky                         IsSigned))
68202375Srdivacky        return true;
69202375Srdivacky    }
70202375Srdivacky    return false;
71202375Srdivacky  }
72202375Srdivacky
73202375Srdivacky  return HasAddOverflow(cast<ConstantInt>(Result),
74202375Srdivacky                        cast<ConstantInt>(In1), cast<ConstantInt>(In2),
75202375Srdivacky                        IsSigned);
76202375Srdivacky}
77202375Srdivacky
78202375Srdivackystatic bool HasSubOverflow(ConstantInt *Result,
79202375Srdivacky                           ConstantInt *In1, ConstantInt *In2,
80202375Srdivacky                           bool IsSigned) {
81224145Sdim  if (!IsSigned)
82202375Srdivacky    return Result->getValue().ugt(In1->getValue());
83226890Sdim
84224145Sdim  if (In2->isNegative())
85224145Sdim    return Result->getValue().slt(In1->getValue());
86224145Sdim
87224145Sdim  return Result->getValue().sgt(In1->getValue());
88202375Srdivacky}
89202375Srdivacky
90202375Srdivacky/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
91202375Srdivacky/// overflowed for this type.
92202375Srdivackystatic bool SubWithOverflow(Constant *&Result, Constant *In1,
93202375Srdivacky                            Constant *In2, bool IsSigned = false) {
94202375Srdivacky  Result = ConstantExpr::getSub(In1, In2);
95202375Srdivacky
96226890Sdim  if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
97202375Srdivacky    for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
98202375Srdivacky      Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
99202375Srdivacky      if (HasSubOverflow(ExtractElement(Result, Idx),
100202375Srdivacky                         ExtractElement(In1, Idx),
101202375Srdivacky                         ExtractElement(In2, Idx),
102202375Srdivacky                         IsSigned))
103202375Srdivacky        return true;
104202375Srdivacky    }
105202375Srdivacky    return false;
106202375Srdivacky  }
107202375Srdivacky
108202375Srdivacky  return HasSubOverflow(cast<ConstantInt>(Result),
109202375Srdivacky                        cast<ConstantInt>(In1), cast<ConstantInt>(In2),
110202375Srdivacky                        IsSigned);
111202375Srdivacky}
112202375Srdivacky
113202375Srdivacky/// isSignBitCheck - Given an exploded icmp instruction, return true if the
114202375Srdivacky/// comparison only checks the sign bit.  If it only checks the sign bit, set
115202375Srdivacky/// TrueIfSigned if the result of the comparison is true when the input value is
116202375Srdivacky/// signed.
117202375Srdivackystatic bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
118202375Srdivacky                           bool &TrueIfSigned) {
119202375Srdivacky  switch (pred) {
120202375Srdivacky  case ICmpInst::ICMP_SLT:   // True if LHS s< 0
121202375Srdivacky    TrueIfSigned = true;
122202375Srdivacky    return RHS->isZero();
123202375Srdivacky  case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
124202375Srdivacky    TrueIfSigned = true;
125202375Srdivacky    return RHS->isAllOnesValue();
126202375Srdivacky  case ICmpInst::ICMP_SGT:   // True if LHS s> -1
127202375Srdivacky    TrueIfSigned = false;
128202375Srdivacky    return RHS->isAllOnesValue();
129202375Srdivacky  case ICmpInst::ICMP_UGT:
130202375Srdivacky    // True if LHS u> RHS and RHS == high-bit-mask - 1
131202375Srdivacky    TrueIfSigned = true;
132224145Sdim    return RHS->isMaxValue(true);
133226890Sdim  case ICmpInst::ICMP_UGE:
134202375Srdivacky    // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
135202375Srdivacky    TrueIfSigned = true;
136202375Srdivacky    return RHS->getValue().isSignBit();
137202375Srdivacky  default:
138202375Srdivacky    return false;
139202375Srdivacky  }
140202375Srdivacky}
141202375Srdivacky
142252723Sdim/// Returns true if the exploded icmp can be expressed as a signed comparison
143252723Sdim/// to zero and updates the predicate accordingly.
144252723Sdim/// The signedness of the comparison is preserved.
145252723Sdimstatic bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
146252723Sdim  if (!ICmpInst::isSigned(pred))
147252723Sdim    return false;
148252723Sdim
149252723Sdim  if (RHS->isZero())
150252723Sdim    return ICmpInst::isRelational(pred);
151252723Sdim
152252723Sdim  if (RHS->isOne()) {
153252723Sdim    if (pred == ICmpInst::ICMP_SLT) {
154252723Sdim      pred = ICmpInst::ICMP_SLE;
155252723Sdim      return true;
156252723Sdim    }
157252723Sdim  } else if (RHS->isAllOnesValue()) {
158252723Sdim    if (pred == ICmpInst::ICMP_SGT) {
159252723Sdim      pred = ICmpInst::ICMP_SGE;
160252723Sdim      return true;
161252723Sdim    }
162252723Sdim  }
163252723Sdim
164252723Sdim  return false;
165252723Sdim}
166252723Sdim
167202375Srdivacky// isHighOnes - Return true if the constant is of the form 1+0+.
168202375Srdivacky// This is the same as lowones(~X).
169202375Srdivackystatic bool isHighOnes(const ConstantInt *CI) {
170202375Srdivacky  return (~CI->getValue() + 1).isPowerOf2();
171202375Srdivacky}
172202375Srdivacky
173226890Sdim/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
174202375Srdivacky/// set of known zero and one bits, compute the maximum and minimum values that
175202375Srdivacky/// could have the specified known zero and known one bits, returning them in
176202375Srdivacky/// min/max.
177202375Srdivackystatic void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
178202375Srdivacky                                                   const APInt& KnownOne,
179202375Srdivacky                                                   APInt& Min, APInt& Max) {
180202375Srdivacky  assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
181202375Srdivacky         KnownZero.getBitWidth() == Min.getBitWidth() &&
182202375Srdivacky         KnownZero.getBitWidth() == Max.getBitWidth() &&
183202375Srdivacky         "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
184202375Srdivacky  APInt UnknownBits = ~(KnownZero|KnownOne);
185202375Srdivacky
186202375Srdivacky  // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
187202375Srdivacky  // bit if it is unknown.
188202375Srdivacky  Min = KnownOne;
189202375Srdivacky  Max = KnownOne|UnknownBits;
190226890Sdim
191202375Srdivacky  if (UnknownBits.isNegative()) { // Sign bit is unknown
192218893Sdim    Min.setBit(Min.getBitWidth()-1);
193218893Sdim    Max.clearBit(Max.getBitWidth()-1);
194202375Srdivacky  }
195202375Srdivacky}
196202375Srdivacky
197202375Srdivacky// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
198202375Srdivacky// a set of known zero and one bits, compute the maximum and minimum values that
199202375Srdivacky// could have the specified known zero and known one bits, returning them in
200202375Srdivacky// min/max.
201202375Srdivackystatic void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
202202375Srdivacky                                                     const APInt &KnownOne,
203202375Srdivacky                                                     APInt &Min, APInt &Max) {
204202375Srdivacky  assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
205202375Srdivacky         KnownZero.getBitWidth() == Min.getBitWidth() &&
206202375Srdivacky         KnownZero.getBitWidth() == Max.getBitWidth() &&
207202375Srdivacky         "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
208202375Srdivacky  APInt UnknownBits = ~(KnownZero|KnownOne);
209226890Sdim
210202375Srdivacky  // The minimum value is when the unknown bits are all zeros.
211202375Srdivacky  Min = KnownOne;
212202375Srdivacky  // The maximum value is when the unknown bits are all ones.
213202375Srdivacky  Max = KnownOne|UnknownBits;
214202375Srdivacky}
215202375Srdivacky
216202375Srdivacky
217202375Srdivacky
218202375Srdivacky/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
219202375Srdivacky///   cmp pred (load (gep GV, ...)), cmpcst
220202375Srdivacky/// where GV is a global variable with a constant initializer.  Try to simplify
221202375Srdivacky/// this into some simple computation that does not need the load.  For example
222202375Srdivacky/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
223202375Srdivacky///
224202375Srdivacky/// If AndCst is non-null, then the loaded value is masked with that constant
225202375Srdivacky/// before doing the comparison.  This handles cases like "A[i]&4 == 0".
226202375SrdivackyInstruction *InstCombiner::
227202375SrdivackyFoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
228202375Srdivacky                             CmpInst &ICI, ConstantInt *AndCst) {
229202375Srdivacky  // We need TD information to know the pointer size unless this is inbounds.
230263509Sdim  if (!GEP->isInBounds() && TD == 0)
231263509Sdim    return 0;
232226890Sdim
233235633Sdim  Constant *Init = GV->getInitializer();
234235633Sdim  if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
235235633Sdim    return 0;
236252723Sdim
237235633Sdim  uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
238235633Sdim  if (ArrayElementCount > 1024) return 0;  // Don't blow up on huge arrays.
239226890Sdim
240202375Srdivacky  // There are many forms of this optimization we can handle, for now, just do
241202375Srdivacky  // the simple index into a single-dimensional array.
242202375Srdivacky  //
243202375Srdivacky  // Require: GEP GV, 0, i {{, constant indices}}
244202375Srdivacky  if (GEP->getNumOperands() < 3 ||
245202375Srdivacky      !isa<ConstantInt>(GEP->getOperand(1)) ||
246202375Srdivacky      !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
247202375Srdivacky      isa<Constant>(GEP->getOperand(2)))
248202375Srdivacky    return 0;
249202375Srdivacky
250202375Srdivacky  // Check that indices after the variable are constants and in-range for the
251202375Srdivacky  // type they index.  Collect the indices.  This is typically for arrays of
252202375Srdivacky  // structs.
253202375Srdivacky  SmallVector<unsigned, 4> LaterIndices;
254226890Sdim
255235633Sdim  Type *EltTy = Init->getType()->getArrayElementType();
256202375Srdivacky  for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
257202375Srdivacky    ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
258202375Srdivacky    if (Idx == 0) return 0;  // Variable index.
259226890Sdim
260202375Srdivacky    uint64_t IdxVal = Idx->getZExtValue();
261202375Srdivacky    if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
262226890Sdim
263226890Sdim    if (StructType *STy = dyn_cast<StructType>(EltTy))
264202375Srdivacky      EltTy = STy->getElementType(IdxVal);
265226890Sdim    else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
266202375Srdivacky      if (IdxVal >= ATy->getNumElements()) return 0;
267202375Srdivacky      EltTy = ATy->getElementType();
268202375Srdivacky    } else {
269202375Srdivacky      return 0; // Unknown type.
270202375Srdivacky    }
271226890Sdim
272202375Srdivacky    LaterIndices.push_back(IdxVal);
273202375Srdivacky  }
274226890Sdim
275202375Srdivacky  enum { Overdefined = -3, Undefined = -2 };
276202375Srdivacky
277202375Srdivacky  // Variables for our state machines.
278226890Sdim
279202375Srdivacky  // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
280202375Srdivacky  // "i == 47 | i == 87", where 47 is the first index the condition is true for,
281202375Srdivacky  // and 87 is the second (and last) index.  FirstTrueElement is -2 when
282202375Srdivacky  // undefined, otherwise set to the first true element.  SecondTrueElement is
283202375Srdivacky  // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
284202375Srdivacky  int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
285202375Srdivacky
286202375Srdivacky  // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
287202375Srdivacky  // form "i != 47 & i != 87".  Same state transitions as for true elements.
288202375Srdivacky  int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
289226890Sdim
290202375Srdivacky  /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
291202375Srdivacky  /// define a state machine that triggers for ranges of values that the index
292202375Srdivacky  /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
293202375Srdivacky  /// This is -2 when undefined, -3 when overdefined, and otherwise the last
294202375Srdivacky  /// index in the range (inclusive).  We use -2 for undefined here because we
295202375Srdivacky  /// use relative comparisons and don't want 0-1 to match -1.
296202375Srdivacky  int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
297226890Sdim
298202375Srdivacky  // MagicBitvector - This is a magic bitvector where we set a bit if the
299202375Srdivacky  // comparison is true for element 'i'.  If there are 64 elements or less in
300202375Srdivacky  // the array, this will fully represent all the comparison results.
301202375Srdivacky  uint64_t MagicBitvector = 0;
302226890Sdim
303226890Sdim
304202375Srdivacky  // Scan the array and see if one of our patterns matches.
305202375Srdivacky  Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
306235633Sdim  for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
307235633Sdim    Constant *Elt = Init->getAggregateElement(i);
308235633Sdim    if (Elt == 0) return 0;
309226890Sdim
310202375Srdivacky    // If this is indexing an array of structures, get the structure element.
311202375Srdivacky    if (!LaterIndices.empty())
312224145Sdim      Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
313226890Sdim
314202375Srdivacky    // If the element is masked, handle it.
315202375Srdivacky    if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
316226890Sdim
317202375Srdivacky    // Find out if the comparison would be true or false for the i'th element.
318202375Srdivacky    Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
319235633Sdim                                                  CompareRHS, TD, TLI);
320202375Srdivacky    // If the result is undef for this element, ignore it.
321202375Srdivacky    if (isa<UndefValue>(C)) {
322202375Srdivacky      // Extend range state machines to cover this element in case there is an
323202375Srdivacky      // undef in the middle of the range.
324202375Srdivacky      if (TrueRangeEnd == (int)i-1)
325202375Srdivacky        TrueRangeEnd = i;
326202375Srdivacky      if (FalseRangeEnd == (int)i-1)
327202375Srdivacky        FalseRangeEnd = i;
328202375Srdivacky      continue;
329202375Srdivacky    }
330226890Sdim
331202375Srdivacky    // If we can't compute the result for any of the elements, we have to give
332202375Srdivacky    // up evaluating the entire conditional.
333202375Srdivacky    if (!isa<ConstantInt>(C)) return 0;
334226890Sdim
335202375Srdivacky    // Otherwise, we know if the comparison is true or false for this element,
336202375Srdivacky    // update our state machines.
337202375Srdivacky    bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
338226890Sdim
339202375Srdivacky    // State machine for single/double/range index comparison.
340202375Srdivacky    if (IsTrueForElt) {
341202375Srdivacky      // Update the TrueElement state machine.
342202375Srdivacky      if (FirstTrueElement == Undefined)
343202375Srdivacky        FirstTrueElement = TrueRangeEnd = i;  // First true element.
344202375Srdivacky      else {
345202375Srdivacky        // Update double-compare state machine.
346202375Srdivacky        if (SecondTrueElement == Undefined)
347202375Srdivacky          SecondTrueElement = i;
348202375Srdivacky        else
349202375Srdivacky          SecondTrueElement = Overdefined;
350226890Sdim
351202375Srdivacky        // Update range state machine.
352202375Srdivacky        if (TrueRangeEnd == (int)i-1)
353202375Srdivacky          TrueRangeEnd = i;
354202375Srdivacky        else
355202375Srdivacky          TrueRangeEnd = Overdefined;
356202375Srdivacky      }
357202375Srdivacky    } else {
358202375Srdivacky      // Update the FalseElement state machine.
359202375Srdivacky      if (FirstFalseElement == Undefined)
360202375Srdivacky        FirstFalseElement = FalseRangeEnd = i; // First false element.
361202375Srdivacky      else {
362202375Srdivacky        // Update double-compare state machine.
363202375Srdivacky        if (SecondFalseElement == Undefined)
364202375Srdivacky          SecondFalseElement = i;
365202375Srdivacky        else
366202375Srdivacky          SecondFalseElement = Overdefined;
367226890Sdim
368202375Srdivacky        // Update range state machine.
369202375Srdivacky        if (FalseRangeEnd == (int)i-1)
370202375Srdivacky          FalseRangeEnd = i;
371202375Srdivacky        else
372202375Srdivacky          FalseRangeEnd = Overdefined;
373202375Srdivacky      }
374202375Srdivacky    }
375226890Sdim
376226890Sdim
377202375Srdivacky    // If this element is in range, update our magic bitvector.
378202375Srdivacky    if (i < 64 && IsTrueForElt)
379202375Srdivacky      MagicBitvector |= 1ULL << i;
380226890Sdim
381202375Srdivacky    // If all of our states become overdefined, bail out early.  Since the
382202375Srdivacky    // predicate is expensive, only check it every 8 elements.  This is only
383202375Srdivacky    // really useful for really huge arrays.
384202375Srdivacky    if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
385202375Srdivacky        SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
386202375Srdivacky        FalseRangeEnd == Overdefined)
387202375Srdivacky      return 0;
388202375Srdivacky  }
389202375Srdivacky
390202375Srdivacky  // Now that we've scanned the entire array, emit our new comparison(s).  We
391202375Srdivacky  // order the state machines in complexity of the generated code.
392202375Srdivacky  Value *Idx = GEP->getOperand(2);
393202375Srdivacky
394202375Srdivacky  // If the index is larger than the pointer size of the target, truncate the
395202375Srdivacky  // index down like the GEP would do implicitly.  We don't have to do this for
396202375Srdivacky  // an inbounds GEP because the index can't be out of range.
397263509Sdim  if (!GEP->isInBounds()) {
398263509Sdim    Type *IntPtrTy = TD->getIntPtrType(GEP->getType());
399263509Sdim    unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
400263509Sdim    if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
401263509Sdim      Idx = Builder->CreateTrunc(Idx, IntPtrTy);
402263509Sdim  }
403226890Sdim
404202375Srdivacky  // If the comparison is only true for one or two elements, emit direct
405202375Srdivacky  // comparisons.
406202375Srdivacky  if (SecondTrueElement != Overdefined) {
407202375Srdivacky    // None true -> false.
408202375Srdivacky    if (FirstTrueElement == Undefined)
409263509Sdim      return ReplaceInstUsesWith(ICI, Builder->getFalse());
410226890Sdim
411202375Srdivacky    Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
412226890Sdim
413202375Srdivacky    // True for one element -> 'i == 47'.
414202375Srdivacky    if (SecondTrueElement == Undefined)
415202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
416226890Sdim
417202375Srdivacky    // True for two elements -> 'i == 47 | i == 72'.
418202375Srdivacky    Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
419202375Srdivacky    Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
420202375Srdivacky    Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
421202375Srdivacky    return BinaryOperator::CreateOr(C1, C2);
422202375Srdivacky  }
423202375Srdivacky
424202375Srdivacky  // If the comparison is only false for one or two elements, emit direct
425202375Srdivacky  // comparisons.
426202375Srdivacky  if (SecondFalseElement != Overdefined) {
427202375Srdivacky    // None false -> true.
428202375Srdivacky    if (FirstFalseElement == Undefined)
429263509Sdim      return ReplaceInstUsesWith(ICI, Builder->getTrue());
430226890Sdim
431202375Srdivacky    Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
432202375Srdivacky
433202375Srdivacky    // False for one element -> 'i != 47'.
434202375Srdivacky    if (SecondFalseElement == Undefined)
435202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
436226890Sdim
437202375Srdivacky    // False for two elements -> 'i != 47 & i != 72'.
438202375Srdivacky    Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
439202375Srdivacky    Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
440202375Srdivacky    Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
441202375Srdivacky    return BinaryOperator::CreateAnd(C1, C2);
442202375Srdivacky  }
443226890Sdim
444202375Srdivacky  // If the comparison can be replaced with a range comparison for the elements
445202375Srdivacky  // where it is true, emit the range check.
446202375Srdivacky  if (TrueRangeEnd != Overdefined) {
447202375Srdivacky    assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
448226890Sdim
449202375Srdivacky    // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
450202375Srdivacky    if (FirstTrueElement) {
451202375Srdivacky      Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
452202375Srdivacky      Idx = Builder->CreateAdd(Idx, Offs);
453202375Srdivacky    }
454226890Sdim
455202375Srdivacky    Value *End = ConstantInt::get(Idx->getType(),
456202375Srdivacky                                  TrueRangeEnd-FirstTrueElement+1);
457202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
458202375Srdivacky  }
459226890Sdim
460202375Srdivacky  // False range check.
461202375Srdivacky  if (FalseRangeEnd != Overdefined) {
462202375Srdivacky    assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
463202375Srdivacky    // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
464202375Srdivacky    if (FirstFalseElement) {
465202375Srdivacky      Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
466202375Srdivacky      Idx = Builder->CreateAdd(Idx, Offs);
467202375Srdivacky    }
468226890Sdim
469202375Srdivacky    Value *End = ConstantInt::get(Idx->getType(),
470202375Srdivacky                                  FalseRangeEnd-FirstFalseElement);
471202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
472202375Srdivacky  }
473226890Sdim
474226890Sdim
475252723Sdim  // If a magic bitvector captures the entire comparison state
476202375Srdivacky  // of this load, replace it with computation that does:
477202375Srdivacky  //   ((magic_cst >> i) & 1) != 0
478252723Sdim  {
479252723Sdim    Type *Ty = 0;
480252723Sdim
481252723Sdim    // Look for an appropriate type:
482252723Sdim    // - The type of Idx if the magic fits
483252723Sdim    // - The smallest fitting legal type if we have a DataLayout
484252723Sdim    // - Default to i32
485252723Sdim    if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
486252723Sdim      Ty = Idx->getType();
487252723Sdim    else if (TD)
488252723Sdim      Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
489252723Sdim    else if (ArrayElementCount <= 32)
490202375Srdivacky      Ty = Type::getInt32Ty(Init->getContext());
491252723Sdim
492252723Sdim    if (Ty != 0) {
493252723Sdim      Value *V = Builder->CreateIntCast(Idx, Ty, false);
494252723Sdim      V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
495252723Sdim      V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
496252723Sdim      return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
497252723Sdim    }
498202375Srdivacky  }
499226890Sdim
500202375Srdivacky  return 0;
501202375Srdivacky}
502202375Srdivacky
503202375Srdivacky
504202375Srdivacky/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
505202375Srdivacky/// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
506202375Srdivacky/// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
507202375Srdivacky/// be complex, and scales are involved.  The above expression would also be
508202375Srdivacky/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
509202375Srdivacky/// This later form is less amenable to optimization though, and we are allowed
510202375Srdivacky/// to generate the first by knowing that pointer arithmetic doesn't overflow.
511202375Srdivacky///
512202375Srdivacky/// If we can't emit an optimized form for this expression, this returns null.
513226890Sdim///
514223017Sdimstatic Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
515245431Sdim  DataLayout &TD = *IC.getDataLayout();
516202375Srdivacky  gep_type_iterator GTI = gep_type_begin(GEP);
517226890Sdim
518202375Srdivacky  // Check to see if this gep only has a single variable index.  If so, and if
519202375Srdivacky  // any constant indices are a multiple of its scale, then we can compute this
520202375Srdivacky  // in terms of the scale of the variable index.  For example, if the GEP
521202375Srdivacky  // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
522202375Srdivacky  // because the expression will cross zero at the same point.
523202375Srdivacky  unsigned i, e = GEP->getNumOperands();
524202375Srdivacky  int64_t Offset = 0;
525202375Srdivacky  for (i = 1; i != e; ++i, ++GTI) {
526202375Srdivacky    if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
527202375Srdivacky      // Compute the aggregate offset of constant indices.
528202375Srdivacky      if (CI->isZero()) continue;
529226890Sdim
530202375Srdivacky      // Handle a struct index, which adds its field offset to the pointer.
531226890Sdim      if (StructType *STy = dyn_cast<StructType>(*GTI)) {
532202375Srdivacky        Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
533202375Srdivacky      } else {
534202375Srdivacky        uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
535202375Srdivacky        Offset += Size*CI->getSExtValue();
536202375Srdivacky      }
537202375Srdivacky    } else {
538202375Srdivacky      // Found our variable index.
539202375Srdivacky      break;
540202375Srdivacky    }
541202375Srdivacky  }
542226890Sdim
543202375Srdivacky  // If there are no variable indices, we must have a constant offset, just
544202375Srdivacky  // evaluate it the general way.
545202375Srdivacky  if (i == e) return 0;
546226890Sdim
547202375Srdivacky  Value *VariableIdx = GEP->getOperand(i);
548202375Srdivacky  // Determine the scale factor of the variable element.  For example, this is
549202375Srdivacky  // 4 if the variable index is into an array of i32.
550202375Srdivacky  uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
551226890Sdim
552202375Srdivacky  // Verify that there are no other variable indices.  If so, emit the hard way.
553202375Srdivacky  for (++i, ++GTI; i != e; ++i, ++GTI) {
554202375Srdivacky    ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
555202375Srdivacky    if (!CI) return 0;
556226890Sdim
557202375Srdivacky    // Compute the aggregate offset of constant indices.
558202375Srdivacky    if (CI->isZero()) continue;
559226890Sdim
560202375Srdivacky    // Handle a struct index, which adds its field offset to the pointer.
561226890Sdim    if (StructType *STy = dyn_cast<StructType>(*GTI)) {
562202375Srdivacky      Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
563202375Srdivacky    } else {
564202375Srdivacky      uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
565202375Srdivacky      Offset += Size*CI->getSExtValue();
566202375Srdivacky    }
567202375Srdivacky  }
568226890Sdim
569263509Sdim
570263509Sdim
571202375Srdivacky  // Okay, we know we have a single variable index, which must be a
572202375Srdivacky  // pointer/array/vector index.  If there is no offset, life is simple, return
573202375Srdivacky  // the index.
574263509Sdim  Type *IntPtrTy = TD.getIntPtrType(GEP->getOperand(0)->getType());
575263509Sdim  unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
576202375Srdivacky  if (Offset == 0) {
577202375Srdivacky    // Cast to intptrty in case a truncation occurs.  If an extension is needed,
578202375Srdivacky    // we don't need to bother extending: the extension won't affect where the
579202375Srdivacky    // computation crosses zero.
580223017Sdim    if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
581223017Sdim      VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
582223017Sdim    }
583202375Srdivacky    return VariableIdx;
584202375Srdivacky  }
585226890Sdim
586202375Srdivacky  // Otherwise, there is an index.  The computation we will do will be modulo
587202375Srdivacky  // the pointer size, so get it.
588202375Srdivacky  uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
589226890Sdim
590202375Srdivacky  Offset &= PtrSizeMask;
591202375Srdivacky  VariableScale &= PtrSizeMask;
592226890Sdim
593202375Srdivacky  // To do this transformation, any constant index must be a multiple of the
594202375Srdivacky  // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
595202375Srdivacky  // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
596202375Srdivacky  // multiple of the variable scale.
597202375Srdivacky  int64_t NewOffs = Offset / (int64_t)VariableScale;
598202375Srdivacky  if (Offset != NewOffs*(int64_t)VariableScale)
599202375Srdivacky    return 0;
600226890Sdim
601202375Srdivacky  // Okay, we can do this evaluation.  Start by converting the index to intptr.
602202375Srdivacky  if (VariableIdx->getType() != IntPtrTy)
603223017Sdim    VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
604223017Sdim                                            true /*Signed*/);
605202375Srdivacky  Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
606223017Sdim  return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
607202375Srdivacky}
608202375Srdivacky
609202375Srdivacky/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
610202375Srdivacky/// else.  At this point we know that the GEP is on the LHS of the comparison.
611202375SrdivackyInstruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
612202375Srdivacky                                       ICmpInst::Predicate Cond,
613202375Srdivacky                                       Instruction &I) {
614235633Sdim  // Don't transform signed compares of GEPs into index compares. Even if the
615235633Sdim  // GEP is inbounds, the final add of the base pointer can have signed overflow
616235633Sdim  // and would change the result of the icmp.
617235633Sdim  // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
618235633Sdim  // the maximum signed value for the pointer type.
619235633Sdim  if (ICmpInst::isSigned(Cond))
620235633Sdim    return 0;
621235633Sdim
622202375Srdivacky  // Look through bitcasts.
623202375Srdivacky  if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
624202375Srdivacky    RHS = BCI->getOperand(0);
625202375Srdivacky
626202375Srdivacky  Value *PtrBase = GEPLHS->getOperand(0);
627202375Srdivacky  if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
628202375Srdivacky    // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
629202375Srdivacky    // This transformation (ignoring the base and scales) is valid because we
630202375Srdivacky    // know pointers can't overflow since the gep is inbounds.  See if we can
631202375Srdivacky    // output an optimized form.
632223017Sdim    Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
633226890Sdim
634202375Srdivacky    // If not, synthesize the offset the hard way.
635202375Srdivacky    if (Offset == 0)
636202375Srdivacky      Offset = EmitGEPOffset(GEPLHS);
637202375Srdivacky    return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
638202375Srdivacky                        Constant::getNullValue(Offset->getType()));
639202375Srdivacky  } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
640202375Srdivacky    // If the base pointers are different, but the indices are the same, just
641202375Srdivacky    // compare the base pointer.
642202375Srdivacky    if (PtrBase != GEPRHS->getOperand(0)) {
643202375Srdivacky      bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
644202375Srdivacky      IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
645202375Srdivacky                        GEPRHS->getOperand(0)->getType();
646202375Srdivacky      if (IndicesTheSame)
647202375Srdivacky        for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
648202375Srdivacky          if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
649202375Srdivacky            IndicesTheSame = false;
650202375Srdivacky            break;
651202375Srdivacky          }
652202375Srdivacky
653202375Srdivacky      // If all indices are the same, just compare the base pointers.
654202375Srdivacky      if (IndicesTheSame)
655263509Sdim        return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
656202375Srdivacky
657235633Sdim      // If we're comparing GEPs with two base pointers that only differ in type
658235633Sdim      // and both GEPs have only constant indices or just one use, then fold
659235633Sdim      // the compare with the adjusted indices.
660235633Sdim      if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
661235633Sdim          (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
662235633Sdim          (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
663235633Sdim          PtrBase->stripPointerCasts() ==
664235633Sdim            GEPRHS->getOperand(0)->stripPointerCasts()) {
665235633Sdim        Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
666235633Sdim                                         EmitGEPOffset(GEPLHS),
667235633Sdim                                         EmitGEPOffset(GEPRHS));
668235633Sdim        return ReplaceInstUsesWith(I, Cmp);
669235633Sdim      }
670235633Sdim
671202375Srdivacky      // Otherwise, the base pointers are different and the indices are
672202375Srdivacky      // different, bail out.
673202375Srdivacky      return 0;
674202375Srdivacky    }
675202375Srdivacky
676202375Srdivacky    // If one of the GEPs has all zero indices, recurse.
677202375Srdivacky    bool AllZeros = true;
678202375Srdivacky    for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
679202375Srdivacky      if (!isa<Constant>(GEPLHS->getOperand(i)) ||
680202375Srdivacky          !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
681202375Srdivacky        AllZeros = false;
682202375Srdivacky        break;
683202375Srdivacky      }
684202375Srdivacky    if (AllZeros)
685202375Srdivacky      return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
686263509Sdim                         ICmpInst::getSwappedPredicate(Cond), I);
687202375Srdivacky
688202375Srdivacky    // If the other GEP has all zero indices, recurse.
689202375Srdivacky    AllZeros = true;
690202375Srdivacky    for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
691202375Srdivacky      if (!isa<Constant>(GEPRHS->getOperand(i)) ||
692202375Srdivacky          !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
693202375Srdivacky        AllZeros = false;
694202375Srdivacky        break;
695202375Srdivacky      }
696202375Srdivacky    if (AllZeros)
697202375Srdivacky      return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
698202375Srdivacky
699223017Sdim    bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
700202375Srdivacky    if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
701202375Srdivacky      // If the GEPs only differ by one index, compare it.
702202375Srdivacky      unsigned NumDifferences = 0;  // Keep track of # differences.
703202375Srdivacky      unsigned DiffOperand = 0;     // The operand that differs.
704202375Srdivacky      for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
705202375Srdivacky        if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
706202375Srdivacky          if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
707202375Srdivacky                   GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
708202375Srdivacky            // Irreconcilable differences.
709202375Srdivacky            NumDifferences = 2;
710202375Srdivacky            break;
711202375Srdivacky          } else {
712202375Srdivacky            if (NumDifferences++) break;
713202375Srdivacky            DiffOperand = i;
714202375Srdivacky          }
715202375Srdivacky        }
716202375Srdivacky
717202375Srdivacky      if (NumDifferences == 0)   // SAME GEP?
718202375Srdivacky        return ReplaceInstUsesWith(I, // No comparison is needed here.
719263509Sdim                             Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
720202375Srdivacky
721223017Sdim      else if (NumDifferences == 1 && GEPsInBounds) {
722202375Srdivacky        Value *LHSV = GEPLHS->getOperand(DiffOperand);
723202375Srdivacky        Value *RHSV = GEPRHS->getOperand(DiffOperand);
724202375Srdivacky        // Make sure we do a signed comparison here.
725202375Srdivacky        return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
726202375Srdivacky      }
727202375Srdivacky    }
728202375Srdivacky
729202375Srdivacky    // Only lower this if the icmp is the only user of the GEP or if we expect
730202375Srdivacky    // the result to fold to a constant!
731202375Srdivacky    if (TD &&
732223017Sdim        GEPsInBounds &&
733202375Srdivacky        (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
734202375Srdivacky        (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
735202375Srdivacky      // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
736202375Srdivacky      Value *L = EmitGEPOffset(GEPLHS);
737202375Srdivacky      Value *R = EmitGEPOffset(GEPRHS);
738202375Srdivacky      return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
739202375Srdivacky    }
740202375Srdivacky  }
741202375Srdivacky  return 0;
742202375Srdivacky}
743202375Srdivacky
744202375Srdivacky/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
745263509SdimInstruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
746202375Srdivacky                                            Value *X, ConstantInt *CI,
747263509Sdim                                            ICmpInst::Predicate Pred) {
748202375Srdivacky  // If we have X+0, exit early (simplifying logic below) and let it get folded
749202375Srdivacky  // elsewhere.   icmp X+0, X  -> icmp X, X
750202375Srdivacky  if (CI->isZero()) {
751202375Srdivacky    bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
752202375Srdivacky    return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
753202375Srdivacky  }
754226890Sdim
755202375Srdivacky  // (X+4) == X -> false.
756202375Srdivacky  if (Pred == ICmpInst::ICMP_EQ)
757263509Sdim    return ReplaceInstUsesWith(ICI, Builder->getFalse());
758202375Srdivacky
759202375Srdivacky  // (X+4) != X -> true.
760202375Srdivacky  if (Pred == ICmpInst::ICMP_NE)
761263509Sdim    return ReplaceInstUsesWith(ICI, Builder->getTrue());
762202375Srdivacky
763202375Srdivacky  // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
764221345Sdim  // so the values can never be equal.  Similarly for all other "or equals"
765202375Srdivacky  // operators.
766226890Sdim
767202375Srdivacky  // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
768202375Srdivacky  // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
769202375Srdivacky  // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
770202375Srdivacky  if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
771226890Sdim    Value *R =
772202375Srdivacky      ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
773202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
774202375Srdivacky  }
775226890Sdim
776202375Srdivacky  // (X+1) >u X        --> X <u (0-1)        --> X != 255
777202375Srdivacky  // (X+2) >u X        --> X <u (0-2)        --> X <u 254
778202375Srdivacky  // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
779218893Sdim  if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
780202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
781226890Sdim
782202375Srdivacky  unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
783202375Srdivacky  ConstantInt *SMax = ConstantInt::get(X->getContext(),
784202375Srdivacky                                       APInt::getSignedMaxValue(BitWidth));
785202375Srdivacky
786202375Srdivacky  // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
787202375Srdivacky  // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
788202375Srdivacky  // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
789202375Srdivacky  // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
790202375Srdivacky  // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
791202375Srdivacky  // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
792218893Sdim  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
793202375Srdivacky    return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
794226890Sdim
795202375Srdivacky  // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
796202375Srdivacky  // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
797202375Srdivacky  // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
798202375Srdivacky  // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
799202375Srdivacky  // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
800202375Srdivacky  // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
801226890Sdim
802202375Srdivacky  assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
803263509Sdim  Constant *C = Builder->getInt(CI->getValue()-1);
804202375Srdivacky  return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
805202375Srdivacky}
806202375Srdivacky
807202375Srdivacky/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
808202375Srdivacky/// and CmpRHS are both known to be integer constants.
809202375SrdivackyInstruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
810202375Srdivacky                                          ConstantInt *DivRHS) {
811202375Srdivacky  ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
812202375Srdivacky  const APInt &CmpRHSV = CmpRHS->getValue();
813226890Sdim
814226890Sdim  // FIXME: If the operand types don't match the type of the divide
815202375Srdivacky  // then don't attempt this transform. The code below doesn't have the
816202375Srdivacky  // logic to deal with a signed divide and an unsigned compare (and
817226890Sdim  // vice versa). This is because (x /s C1) <s C2  produces different
818202375Srdivacky  // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
819226890Sdim  // (x /u C1) <u C2.  Simply casting the operands and result won't
820226890Sdim  // work. :(  The if statement below tests that condition and bails
821218893Sdim  // if it finds it.
822202375Srdivacky  bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
823202375Srdivacky  if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
824202375Srdivacky    return 0;
825202375Srdivacky  if (DivRHS->isZero())
826202375Srdivacky    return 0; // The ProdOV computation fails on divide by zero.
827202375Srdivacky  if (DivIsSigned && DivRHS->isAllOnesValue())
828202375Srdivacky    return 0; // The overflow computation also screws up here
829218893Sdim  if (DivRHS->isOne()) {
830218893Sdim    // This eliminates some funny cases with INT_MIN.
831218893Sdim    ICI.setOperand(0, DivI->getOperand(0));   // X/1 == X.
832218893Sdim    return &ICI;
833218893Sdim  }
834202375Srdivacky
835202375Srdivacky  // Compute Prod = CI * DivRHS. We are essentially solving an equation
836226890Sdim  // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
837226890Sdim  // C2 (CI). By solving for X we can turn this into a range check
838226890Sdim  // instead of computing a divide.
839202375Srdivacky  Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
840202375Srdivacky
841202375Srdivacky  // Determine if the product overflows by seeing if the product is
842202375Srdivacky  // not equal to the divide. Make sure we do the same kind of divide
843226890Sdim  // as in the LHS instruction that we're folding.
844202375Srdivacky  bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
845202375Srdivacky                 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
846202375Srdivacky
847202375Srdivacky  // Get the ICmp opcode
848202375Srdivacky  ICmpInst::Predicate Pred = ICI.getPredicate();
849202375Srdivacky
850218893Sdim  /// If the division is known to be exact, then there is no remainder from the
851218893Sdim  /// divide, so the covered range size is unit, otherwise it is the divisor.
852218893Sdim  ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
853226890Sdim
854202375Srdivacky  // Figure out the interval that is being checked.  For example, a comparison
855226890Sdim  // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
856202375Srdivacky  // Compute this interval based on the constants involved and the signedness of
857202375Srdivacky  // the compare/divide.  This computes a half-open interval, keeping track of
858202375Srdivacky  // whether either value in the interval overflows.  After analysis each
859202375Srdivacky  // overflow variable is set to 0 if it's corresponding bound variable is valid
860202375Srdivacky  // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
861202375Srdivacky  int LoOverflow = 0, HiOverflow = 0;
862202375Srdivacky  Constant *LoBound = 0, *HiBound = 0;
863218893Sdim
864202375Srdivacky  if (!DivIsSigned) {  // udiv
865202375Srdivacky    // e.g. X/5 op 3  --> [15, 20)
866202375Srdivacky    LoBound = Prod;
867202375Srdivacky    HiOverflow = LoOverflow = ProdOV;
868218893Sdim    if (!HiOverflow) {
869218893Sdim      // If this is not an exact divide, then many values in the range collapse
870218893Sdim      // to the same result value.
871218893Sdim      HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
872218893Sdim    }
873226890Sdim
874202375Srdivacky  } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
875202375Srdivacky    if (CmpRHSV == 0) {       // (X / pos) op 0
876202375Srdivacky      // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
877218893Sdim      LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
878218893Sdim      HiBound = RangeSize;
879202375Srdivacky    } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
880202375Srdivacky      LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
881202375Srdivacky      HiOverflow = LoOverflow = ProdOV;
882202375Srdivacky      if (!HiOverflow)
883218893Sdim        HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
884202375Srdivacky    } else {                       // (X / pos) op neg
885202375Srdivacky      // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
886202375Srdivacky      HiBound = AddOne(Prod);
887202375Srdivacky      LoOverflow = HiOverflow = ProdOV ? -1 : 0;
888202375Srdivacky      if (!LoOverflow) {
889218893Sdim        ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
890202375Srdivacky        LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
891218893Sdim      }
892202375Srdivacky    }
893224145Sdim  } else if (DivRHS->isNegative()) { // Divisor is < 0.
894218893Sdim    if (DivI->isExact())
895218893Sdim      RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
896202375Srdivacky    if (CmpRHSV == 0) {       // (X / neg) op 0
897202375Srdivacky      // e.g. X/-5 op 0  --> [-4, 5)
898218893Sdim      LoBound = AddOne(RangeSize);
899218893Sdim      HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
900202375Srdivacky      if (HiBound == DivRHS) {     // -INTMIN = INTMIN
901202375Srdivacky        HiOverflow = 1;            // [INTMIN+1, overflow)
902202375Srdivacky        HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
903202375Srdivacky      }
904202375Srdivacky    } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
905202375Srdivacky      // e.g. X/-5 op 3  --> [-19, -14)
906202375Srdivacky      HiBound = AddOne(Prod);
907202375Srdivacky      HiOverflow = LoOverflow = ProdOV ? -1 : 0;
908202375Srdivacky      if (!LoOverflow)
909218893Sdim        LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
910202375Srdivacky    } else {                       // (X / neg) op neg
911202375Srdivacky      LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
912202375Srdivacky      LoOverflow = HiOverflow = ProdOV;
913202375Srdivacky      if (!HiOverflow)
914218893Sdim        HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
915202375Srdivacky    }
916226890Sdim
917202375Srdivacky    // Dividing by a negative swaps the condition.  LT <-> GT
918202375Srdivacky    Pred = ICmpInst::getSwappedPredicate(Pred);
919202375Srdivacky  }
920202375Srdivacky
921202375Srdivacky  Value *X = DivI->getOperand(0);
922202375Srdivacky  switch (Pred) {
923202375Srdivacky  default: llvm_unreachable("Unhandled icmp opcode!");
924202375Srdivacky  case ICmpInst::ICMP_EQ:
925202375Srdivacky    if (LoOverflow && HiOverflow)
926263509Sdim      return ReplaceInstUsesWith(ICI, Builder->getFalse());
927204792Srdivacky    if (HiOverflow)
928202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
929202375Srdivacky                          ICmpInst::ICMP_UGE, X, LoBound);
930204792Srdivacky    if (LoOverflow)
931202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
932202375Srdivacky                          ICmpInst::ICMP_ULT, X, HiBound);
933218893Sdim    return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
934218893Sdim                                                    DivIsSigned, true));
935202375Srdivacky  case ICmpInst::ICMP_NE:
936202375Srdivacky    if (LoOverflow && HiOverflow)
937263509Sdim      return ReplaceInstUsesWith(ICI, Builder->getTrue());
938204792Srdivacky    if (HiOverflow)
939202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
940202375Srdivacky                          ICmpInst::ICMP_ULT, X, LoBound);
941204792Srdivacky    if (LoOverflow)
942202375Srdivacky      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
943202375Srdivacky                          ICmpInst::ICMP_UGE, X, HiBound);
944204792Srdivacky    return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
945204792Srdivacky                                                    DivIsSigned, false));
946202375Srdivacky  case ICmpInst::ICMP_ULT:
947202375Srdivacky  case ICmpInst::ICMP_SLT:
948202375Srdivacky    if (LoOverflow == +1)   // Low bound is greater than input range.
949263509Sdim      return ReplaceInstUsesWith(ICI, Builder->getTrue());
950202375Srdivacky    if (LoOverflow == -1)   // Low bound is less than input range.
951263509Sdim      return ReplaceInstUsesWith(ICI, Builder->getFalse());
952202375Srdivacky    return new ICmpInst(Pred, X, LoBound);
953202375Srdivacky  case ICmpInst::ICMP_UGT:
954202375Srdivacky  case ICmpInst::ICMP_SGT:
955202375Srdivacky    if (HiOverflow == +1)       // High bound greater than input range.
956263509Sdim      return ReplaceInstUsesWith(ICI, Builder->getFalse());
957218893Sdim    if (HiOverflow == -1)       // High bound less than input range.
958263509Sdim      return ReplaceInstUsesWith(ICI, Builder->getTrue());
959202375Srdivacky    if (Pred == ICmpInst::ICMP_UGT)
960202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
961218893Sdim    return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
962202375Srdivacky  }
963202375Srdivacky}
964202375Srdivacky
965218893Sdim/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
966218893SdimInstruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
967218893Sdim                                          ConstantInt *ShAmt) {
968218893Sdim  const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
969226890Sdim
970218893Sdim  // Check that the shift amount is in range.  If not, don't perform
971218893Sdim  // undefined shifts.  When the shift is visited it will be
972218893Sdim  // simplified.
973218893Sdim  uint32_t TypeBits = CmpRHSV.getBitWidth();
974218893Sdim  uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
975218893Sdim  if (ShAmtVal >= TypeBits || ShAmtVal == 0)
976218893Sdim    return 0;
977226890Sdim
978218893Sdim  if (!ICI.isEquality()) {
979218893Sdim    // If we have an unsigned comparison and an ashr, we can't simplify this.
980218893Sdim    // Similarly for signed comparisons with lshr.
981218893Sdim    if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
982218893Sdim      return 0;
983226890Sdim
984223017Sdim    // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
985223017Sdim    // by a power of 2.  Since we already have logic to simplify these,
986223017Sdim    // transform to div and then simplify the resultant comparison.
987218893Sdim    if (Shr->getOpcode() == Instruction::AShr &&
988223017Sdim        (!Shr->isExact() || ShAmtVal == TypeBits - 1))
989218893Sdim      return 0;
990226890Sdim
991218893Sdim    // Revisit the shift (to delete it).
992218893Sdim    Worklist.Add(Shr);
993226890Sdim
994218893Sdim    Constant *DivCst =
995218893Sdim      ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
996226890Sdim
997218893Sdim    Value *Tmp =
998218893Sdim      Shr->getOpcode() == Instruction::AShr ?
999218893Sdim      Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
1000218893Sdim      Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
1001226890Sdim
1002218893Sdim    ICI.setOperand(0, Tmp);
1003226890Sdim
1004218893Sdim    // If the builder folded the binop, just return it.
1005218893Sdim    BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
1006218893Sdim    if (TheDiv == 0)
1007218893Sdim      return &ICI;
1008226890Sdim
1009218893Sdim    // Otherwise, fold this div/compare.
1010218893Sdim    assert(TheDiv->getOpcode() == Instruction::SDiv ||
1011218893Sdim           TheDiv->getOpcode() == Instruction::UDiv);
1012226890Sdim
1013218893Sdim    Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1014218893Sdim    assert(Res && "This div/cst should have folded!");
1015218893Sdim    return Res;
1016218893Sdim  }
1017226890Sdim
1018226890Sdim
1019218893Sdim  // If we are comparing against bits always shifted out, the
1020218893Sdim  // comparison cannot succeed.
1021218893Sdim  APInt Comp = CmpRHSV << ShAmtVal;
1022263509Sdim  ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
1023218893Sdim  if (Shr->getOpcode() == Instruction::LShr)
1024218893Sdim    Comp = Comp.lshr(ShAmtVal);
1025218893Sdim  else
1026218893Sdim    Comp = Comp.ashr(ShAmtVal);
1027226890Sdim
1028218893Sdim  if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1029218893Sdim    bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1030263509Sdim    Constant *Cst = Builder->getInt1(IsICMP_NE);
1031218893Sdim    return ReplaceInstUsesWith(ICI, Cst);
1032218893Sdim  }
1033226890Sdim
1034218893Sdim  // Otherwise, check to see if the bits shifted out are known to be zero.
1035218893Sdim  // If so, we can compare against the unshifted value:
1036218893Sdim  //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
1037218893Sdim  if (Shr->hasOneUse() && Shr->isExact())
1038218893Sdim    return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
1039226890Sdim
1040218893Sdim  if (Shr->hasOneUse()) {
1041218893Sdim    // Otherwise strength reduce the shift into an and.
1042218893Sdim    APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1043263509Sdim    Constant *Mask = Builder->getInt(Val);
1044226890Sdim
1045218893Sdim    Value *And = Builder->CreateAnd(Shr->getOperand(0),
1046218893Sdim                                    Mask, Shr->getName()+".mask");
1047218893Sdim    return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1048218893Sdim  }
1049218893Sdim  return 0;
1050218893Sdim}
1051202375Srdivacky
1052218893Sdim
1053202375Srdivacky/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1054202375Srdivacky///
1055202375SrdivackyInstruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1056202375Srdivacky                                                          Instruction *LHSI,
1057202375Srdivacky                                                          ConstantInt *RHS) {
1058202375Srdivacky  const APInt &RHSV = RHS->getValue();
1059226890Sdim
1060202375Srdivacky  switch (LHSI->getOpcode()) {
1061202375Srdivacky  case Instruction::Trunc:
1062202375Srdivacky    if (ICI.isEquality() && LHSI->hasOneUse()) {
1063202375Srdivacky      // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1064202375Srdivacky      // of the high bits truncated out of x are known.
1065202375Srdivacky      unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1066202375Srdivacky             SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1067202375Srdivacky      APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1068235633Sdim      ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
1069226890Sdim
1070202375Srdivacky      // If all the high bits are known, we can do this xform.
1071202375Srdivacky      if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1072202375Srdivacky        // Pull in the high bits from known-ones set.
1073218893Sdim        APInt NewRHS = RHS->getValue().zext(SrcBits);
1074245431Sdim        NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
1075202375Srdivacky        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1076263509Sdim                            Builder->getInt(NewRHS));
1077202375Srdivacky      }
1078202375Srdivacky    }
1079202375Srdivacky    break;
1080226890Sdim
1081202375Srdivacky  case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
1082202375Srdivacky    if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1083202375Srdivacky      // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1084202375Srdivacky      // fold the xor.
1085202375Srdivacky      if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1086202375Srdivacky          (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1087202375Srdivacky        Value *CompareVal = LHSI->getOperand(0);
1088226890Sdim
1089202375Srdivacky        // If the sign bit of the XorCST is not set, there is no change to
1090202375Srdivacky        // the operation, just stop using the Xor.
1091224145Sdim        if (!XorCST->isNegative()) {
1092202375Srdivacky          ICI.setOperand(0, CompareVal);
1093202375Srdivacky          Worklist.Add(LHSI);
1094202375Srdivacky          return &ICI;
1095202375Srdivacky        }
1096226890Sdim
1097202375Srdivacky        // Was the old condition true if the operand is positive?
1098202375Srdivacky        bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1099226890Sdim
1100202375Srdivacky        // If so, the new one isn't.
1101202375Srdivacky        isTrueIfPositive ^= true;
1102226890Sdim
1103202375Srdivacky        if (isTrueIfPositive)
1104202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1105202375Srdivacky                              SubOne(RHS));
1106202375Srdivacky        else
1107202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1108202375Srdivacky                              AddOne(RHS));
1109202375Srdivacky      }
1110202375Srdivacky
1111202375Srdivacky      if (LHSI->hasOneUse()) {
1112202375Srdivacky        // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1113202375Srdivacky        if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
1114202375Srdivacky          const APInt &SignBit = XorCST->getValue();
1115202375Srdivacky          ICmpInst::Predicate Pred = ICI.isSigned()
1116202375Srdivacky                                         ? ICI.getUnsignedPredicate()
1117202375Srdivacky                                         : ICI.getSignedPredicate();
1118202375Srdivacky          return new ICmpInst(Pred, LHSI->getOperand(0),
1119263509Sdim                              Builder->getInt(RHSV ^ SignBit));
1120202375Srdivacky        }
1121202375Srdivacky
1122202375Srdivacky        // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1123224145Sdim        if (!ICI.isEquality() && XorCST->isMaxValue(true)) {
1124202375Srdivacky          const APInt &NotSignBit = XorCST->getValue();
1125202375Srdivacky          ICmpInst::Predicate Pred = ICI.isSigned()
1126202375Srdivacky                                         ? ICI.getUnsignedPredicate()
1127202375Srdivacky                                         : ICI.getSignedPredicate();
1128202375Srdivacky          Pred = ICI.getSwappedPredicate(Pred);
1129202375Srdivacky          return new ICmpInst(Pred, LHSI->getOperand(0),
1130263509Sdim                              Builder->getInt(RHSV ^ NotSignBit));
1131202375Srdivacky        }
1132202375Srdivacky      }
1133263509Sdim
1134263509Sdim      // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1135263509Sdim      //   iff -C is a power of 2
1136263509Sdim      if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
1137263509Sdim          XorCST->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1138263509Sdim        return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCST);
1139263509Sdim
1140263509Sdim      // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1141263509Sdim      //   iff -C is a power of 2
1142263509Sdim      if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
1143263509Sdim          XorCST->getValue() == -RHSV && RHSV.isPowerOf2())
1144263509Sdim        return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCST);
1145202375Srdivacky    }
1146202375Srdivacky    break;
1147202375Srdivacky  case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
1148202375Srdivacky    if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1149202375Srdivacky        LHSI->getOperand(0)->hasOneUse()) {
1150202375Srdivacky      ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1151226890Sdim
1152202375Srdivacky      // If the LHS is an AND of a truncating cast, we can widen the
1153202375Srdivacky      // and/compare to be the input width without changing the value
1154202375Srdivacky      // produced, eliminating a cast.
1155202375Srdivacky      if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1156202375Srdivacky        // We can do this transformation if either the AND constant does not
1157226890Sdim        // have its sign bit set or if it is an equality comparison.
1158202375Srdivacky        // Extending a relational comparison when we're checking the sign
1159202375Srdivacky        // bit would not work.
1160224145Sdim        if (ICI.isEquality() ||
1161224145Sdim            (!AndCST->isNegative() && RHSV.isNonNegative())) {
1162224145Sdim          Value *NewAnd =
1163202375Srdivacky            Builder->CreateAnd(Cast->getOperand(0),
1164224145Sdim                               ConstantExpr::getZExt(AndCST, Cast->getSrcTy()));
1165224145Sdim          NewAnd->takeName(LHSI);
1166202375Srdivacky          return new ICmpInst(ICI.getPredicate(), NewAnd,
1167224145Sdim                              ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1168202375Srdivacky        }
1169202375Srdivacky      }
1170224145Sdim
1171224145Sdim      // If the LHS is an AND of a zext, and we have an equality compare, we can
1172224145Sdim      // shrink the and/compare to the smaller type, eliminating the cast.
1173224145Sdim      if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1174226890Sdim        IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1175224145Sdim        // Make sure we don't compare the upper bits, SimplifyDemandedBits
1176224145Sdim        // should fold the icmp to true/false in that case.
1177224145Sdim        if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1178224145Sdim          Value *NewAnd =
1179224145Sdim            Builder->CreateAnd(Cast->getOperand(0),
1180224145Sdim                               ConstantExpr::getTrunc(AndCST, Ty));
1181224145Sdim          NewAnd->takeName(LHSI);
1182224145Sdim          return new ICmpInst(ICI.getPredicate(), NewAnd,
1183224145Sdim                              ConstantExpr::getTrunc(RHS, Ty));
1184224145Sdim        }
1185224145Sdim      }
1186224145Sdim
1187202375Srdivacky      // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1188202375Srdivacky      // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1189202375Srdivacky      // happens a LOT in code produced by the C front-end, for bitfield
1190202375Srdivacky      // access.
1191202375Srdivacky      BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1192202375Srdivacky      if (Shift && !Shift->isShift())
1193202375Srdivacky        Shift = 0;
1194226890Sdim
1195202375Srdivacky      ConstantInt *ShAmt;
1196202375Srdivacky      ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1197226890Sdim      Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
1198226890Sdim      Type *AndTy = AndCST->getType();          // Type of the and.
1199226890Sdim
1200202375Srdivacky      // We can fold this as long as we can't shift unknown bits
1201263509Sdim      // into the mask. This can happen with signed shift
1202263509Sdim      // rights, as they sign-extend. With logical shifts,
1203263509Sdim      // we must still make sure the comparison is not signed
1204263509Sdim      // because we are effectively changing the
1205263509Sdim      // position of the sign bit (PR17827).
1206263509Sdim      // TODO: We can relax these constraints a bit more.
1207202375Srdivacky      if (ShAmt) {
1208263509Sdim        bool CanFold = false;
1209263509Sdim        unsigned ShiftOpcode = Shift->getOpcode();
1210263509Sdim        if (ShiftOpcode == Instruction::AShr) {
1211202375Srdivacky          // To test for the bad case of the signed shr, see if any
1212202375Srdivacky          // of the bits shifted in could be tested after the mask.
1213202375Srdivacky          uint32_t TyBits = Ty->getPrimitiveSizeInBits();
1214202375Srdivacky          int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
1215226890Sdim
1216202375Srdivacky          uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
1217226890Sdim          if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
1218202375Srdivacky               AndCST->getValue()) == 0)
1219202375Srdivacky            CanFold = true;
1220263509Sdim        } else if (ShiftOpcode == Instruction::Shl ||
1221263509Sdim                   ShiftOpcode == Instruction::LShr) {
1222263509Sdim          CanFold = !ICI.isSigned();
1223202375Srdivacky        }
1224226890Sdim
1225202375Srdivacky        if (CanFold) {
1226202375Srdivacky          Constant *NewCst;
1227202375Srdivacky          if (Shift->getOpcode() == Instruction::Shl)
1228202375Srdivacky            NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1229202375Srdivacky          else
1230202375Srdivacky            NewCst = ConstantExpr::getShl(RHS, ShAmt);
1231226890Sdim
1232202375Srdivacky          // Check to see if we are shifting out any of the bits being
1233202375Srdivacky          // compared.
1234202375Srdivacky          if (ConstantExpr::get(Shift->getOpcode(),
1235202375Srdivacky                                       NewCst, ShAmt) != RHS) {
1236202375Srdivacky            // If we shifted bits out, the fold is not going to work out.
1237202375Srdivacky            // As a special case, check to see if this means that the
1238202375Srdivacky            // result is always true or false now.
1239202375Srdivacky            if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1240263509Sdim              return ReplaceInstUsesWith(ICI, Builder->getFalse());
1241202375Srdivacky            if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1242263509Sdim              return ReplaceInstUsesWith(ICI, Builder->getTrue());
1243202375Srdivacky          } else {
1244202375Srdivacky            ICI.setOperand(1, NewCst);
1245202375Srdivacky            Constant *NewAndCST;
1246202375Srdivacky            if (Shift->getOpcode() == Instruction::Shl)
1247202375Srdivacky              NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
1248202375Srdivacky            else
1249202375Srdivacky              NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1250202375Srdivacky            LHSI->setOperand(1, NewAndCST);
1251202375Srdivacky            LHSI->setOperand(0, Shift->getOperand(0));
1252202375Srdivacky            Worklist.Add(Shift); // Shift is dead.
1253202375Srdivacky            return &ICI;
1254202375Srdivacky          }
1255202375Srdivacky        }
1256202375Srdivacky      }
1257226890Sdim
1258202375Srdivacky      // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
1259202375Srdivacky      // preferable because it allows the C<<Y expression to be hoisted out
1260202375Srdivacky      // of a loop if Y is invariant and X is not.
1261202375Srdivacky      if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1262202375Srdivacky          ICI.isEquality() && !Shift->isArithmeticShift() &&
1263202375Srdivacky          !isa<Constant>(Shift->getOperand(0))) {
1264202375Srdivacky        // Compute C << Y.
1265202375Srdivacky        Value *NS;
1266202375Srdivacky        if (Shift->getOpcode() == Instruction::LShr) {
1267226890Sdim          NS = Builder->CreateShl(AndCST, Shift->getOperand(1));
1268202375Srdivacky        } else {
1269202375Srdivacky          // Insert a logical shift.
1270226890Sdim          NS = Builder->CreateLShr(AndCST, Shift->getOperand(1));
1271202375Srdivacky        }
1272226890Sdim
1273202375Srdivacky        // Compute X & (C << Y).
1274226890Sdim        Value *NewAnd =
1275202375Srdivacky          Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1276226890Sdim
1277202375Srdivacky        ICI.setOperand(0, NewAnd);
1278202375Srdivacky        return &ICI;
1279202375Srdivacky      }
1280252723Sdim
1281252723Sdim      // Replace ((X & AndCST) > RHSV) with ((X & AndCST) != 0), if any
1282252723Sdim      // bit set in (X & AndCST) will produce a result greater than RHSV.
1283252723Sdim      if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1284252723Sdim        unsigned NTZ = AndCST->getValue().countTrailingZeros();
1285252723Sdim        if ((NTZ < AndCST->getBitWidth()) &&
1286252723Sdim            APInt::getOneBitSet(AndCST->getBitWidth(), NTZ).ugt(RHSV))
1287252723Sdim          return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1288252723Sdim                              Constant::getNullValue(RHS->getType()));
1289252723Sdim      }
1290202375Srdivacky    }
1291226890Sdim
1292202375Srdivacky    // Try to optimize things like "A[i]&42 == 0" to index computations.
1293202375Srdivacky    if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1294202375Srdivacky      if (GetElementPtrInst *GEP =
1295202375Srdivacky          dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1296202375Srdivacky        if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1297202375Srdivacky          if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1298202375Srdivacky              !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1299202375Srdivacky            ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1300202375Srdivacky            if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1301202375Srdivacky              return Res;
1302202375Srdivacky          }
1303202375Srdivacky    }
1304263509Sdim
1305263509Sdim    // X & -C == -C -> X >  u ~C
1306263509Sdim    // X & -C != -C -> X <= u ~C
1307263509Sdim    //   iff C is a power of 2
1308263509Sdim    if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1309263509Sdim      return new ICmpInst(
1310263509Sdim          ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1311263509Sdim                                                  : ICmpInst::ICMP_ULE,
1312263509Sdim          LHSI->getOperand(0), SubOne(RHS));
1313202375Srdivacky    break;
1314202375Srdivacky
1315202375Srdivacky  case Instruction::Or: {
1316202375Srdivacky    if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1317202375Srdivacky      break;
1318202375Srdivacky    Value *P, *Q;
1319202375Srdivacky    if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1320202375Srdivacky      // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1321202375Srdivacky      // -> and (icmp eq P, null), (icmp eq Q, null).
1322202375Srdivacky      Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1323202375Srdivacky                                        Constant::getNullValue(P->getType()));
1324202375Srdivacky      Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1325202375Srdivacky                                        Constant::getNullValue(Q->getType()));
1326202375Srdivacky      Instruction *Op;
1327202375Srdivacky      if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1328202375Srdivacky        Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1329202375Srdivacky      else
1330202375Srdivacky        Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1331202375Srdivacky      return Op;
1332202375Srdivacky    }
1333202375Srdivacky    break;
1334202375Srdivacky  }
1335226890Sdim
1336252723Sdim  case Instruction::Mul: {       // (icmp pred (mul X, Val), CI)
1337252723Sdim    ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1338252723Sdim    if (!Val) break;
1339252723Sdim
1340252723Sdim    // If this is a signed comparison to 0 and the mul is sign preserving,
1341252723Sdim    // use the mul LHS operand instead.
1342252723Sdim    ICmpInst::Predicate pred = ICI.getPredicate();
1343252723Sdim    if (isSignTest(pred, RHS) && !Val->isZero() &&
1344252723Sdim        cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1345252723Sdim      return new ICmpInst(Val->isNegative() ?
1346252723Sdim                          ICmpInst::getSwappedPredicate(pred) : pred,
1347252723Sdim                          LHSI->getOperand(0),
1348252723Sdim                          Constant::getNullValue(RHS->getType()));
1349252723Sdim
1350252723Sdim    break;
1351252723Sdim  }
1352252723Sdim
1353202375Srdivacky  case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
1354263509Sdim    uint32_t TypeBits = RHSV.getBitWidth();
1355202375Srdivacky    ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1356263509Sdim    if (!ShAmt) {
1357263509Sdim      Value *X;
1358263509Sdim      // (1 << X) pred P2 -> X pred Log2(P2)
1359263509Sdim      if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1360263509Sdim        bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1361263509Sdim        ICmpInst::Predicate Pred = ICI.getPredicate();
1362263509Sdim        if (ICI.isUnsigned()) {
1363263509Sdim          if (!RHSVIsPowerOf2) {
1364263509Sdim            // (1 << X) <  30 -> X <= 4
1365263509Sdim            // (1 << X) <= 30 -> X <= 4
1366263509Sdim            // (1 << X) >= 30 -> X >  4
1367263509Sdim            // (1 << X) >  30 -> X >  4
1368263509Sdim            if (Pred == ICmpInst::ICMP_ULT)
1369263509Sdim              Pred = ICmpInst::ICMP_ULE;
1370263509Sdim            else if (Pred == ICmpInst::ICMP_UGE)
1371263509Sdim              Pred = ICmpInst::ICMP_UGT;
1372263509Sdim          }
1373263509Sdim          unsigned RHSLog2 = RHSV.logBase2();
1374226890Sdim
1375263509Sdim          // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1376263509Sdim          // (1 << X) >  2147483648 -> X >  31 -> false
1377263509Sdim          // (1 << X) <= 2147483648 -> X <= 31 -> true
1378263509Sdim          // (1 << X) <  2147483648 -> X <  31 -> X != 31
1379263509Sdim          if (RHSLog2 == TypeBits-1) {
1380263509Sdim            if (Pred == ICmpInst::ICMP_UGE)
1381263509Sdim              Pred = ICmpInst::ICMP_EQ;
1382263509Sdim            else if (Pred == ICmpInst::ICMP_UGT)
1383263509Sdim              return ReplaceInstUsesWith(ICI, Builder->getFalse());
1384263509Sdim            else if (Pred == ICmpInst::ICMP_ULE)
1385263509Sdim              return ReplaceInstUsesWith(ICI, Builder->getTrue());
1386263509Sdim            else if (Pred == ICmpInst::ICMP_ULT)
1387263509Sdim              Pred = ICmpInst::ICMP_NE;
1388263509Sdim          }
1389226890Sdim
1390263509Sdim          return new ICmpInst(Pred, X,
1391263509Sdim                              ConstantInt::get(RHS->getType(), RHSLog2));
1392263509Sdim        } else if (ICI.isSigned()) {
1393263509Sdim          if (RHSV.isAllOnesValue()) {
1394263509Sdim            // (1 << X) <= -1 -> X == 31
1395263509Sdim            if (Pred == ICmpInst::ICMP_SLE)
1396263509Sdim              return new ICmpInst(ICmpInst::ICMP_EQ, X,
1397263509Sdim                                  ConstantInt::get(RHS->getType(), TypeBits-1));
1398263509Sdim
1399263509Sdim            // (1 << X) >  -1 -> X != 31
1400263509Sdim            if (Pred == ICmpInst::ICMP_SGT)
1401263509Sdim              return new ICmpInst(ICmpInst::ICMP_NE, X,
1402263509Sdim                                  ConstantInt::get(RHS->getType(), TypeBits-1));
1403263509Sdim          } else if (!RHSV) {
1404263509Sdim            // (1 << X) <  0 -> X == 31
1405263509Sdim            // (1 << X) <= 0 -> X == 31
1406263509Sdim            if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1407263509Sdim              return new ICmpInst(ICmpInst::ICMP_EQ, X,
1408263509Sdim                                  ConstantInt::get(RHS->getType(), TypeBits-1));
1409263509Sdim
1410263509Sdim            // (1 << X) >= 0 -> X != 31
1411263509Sdim            // (1 << X) >  0 -> X != 31
1412263509Sdim            if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1413263509Sdim              return new ICmpInst(ICmpInst::ICMP_NE, X,
1414263509Sdim                                  ConstantInt::get(RHS->getType(), TypeBits-1));
1415263509Sdim          }
1416263509Sdim        } else if (ICI.isEquality()) {
1417263509Sdim          if (RHSVIsPowerOf2)
1418263509Sdim            return new ICmpInst(
1419263509Sdim                Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1420263509Sdim
1421263509Sdim          return ReplaceInstUsesWith(
1422263509Sdim              ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
1423263509Sdim                                             : Builder->getTrue());
1424263509Sdim        }
1425263509Sdim      }
1426263509Sdim      break;
1427263509Sdim    }
1428263509Sdim
1429202375Srdivacky    // Check that the shift amount is in range.  If not, don't perform
1430202375Srdivacky    // undefined shifts.  When the shift is visited it will be
1431202375Srdivacky    // simplified.
1432202375Srdivacky    if (ShAmt->uge(TypeBits))
1433202375Srdivacky      break;
1434226890Sdim
1435202375Srdivacky    if (ICI.isEquality()) {
1436202375Srdivacky      // If we are comparing against bits always shifted out, the
1437202375Srdivacky      // comparison cannot succeed.
1438202375Srdivacky      Constant *Comp =
1439202375Srdivacky        ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1440202375Srdivacky                                                                 ShAmt);
1441202375Srdivacky      if (Comp != RHS) {// Comparing against a bit that we know is zero.
1442202375Srdivacky        bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1443263509Sdim        Constant *Cst = Builder->getInt1(IsICMP_NE);
1444202375Srdivacky        return ReplaceInstUsesWith(ICI, Cst);
1445202375Srdivacky      }
1446226890Sdim
1447218893Sdim      // If the shift is NUW, then it is just shifting out zeros, no need for an
1448218893Sdim      // AND.
1449218893Sdim      if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1450218893Sdim        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1451218893Sdim                            ConstantExpr::getLShr(RHS, ShAmt));
1452226890Sdim
1453252723Sdim      // If the shift is NSW and we compare to 0, then it is just shifting out
1454252723Sdim      // sign bits, no need for an AND either.
1455252723Sdim      if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1456252723Sdim        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1457252723Sdim                            ConstantExpr::getLShr(RHS, ShAmt));
1458252723Sdim
1459202375Srdivacky      if (LHSI->hasOneUse()) {
1460202375Srdivacky        // Otherwise strength reduce the shift into an and.
1461202375Srdivacky        uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1462263509Sdim        Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1463263509Sdim                                                          TypeBits - ShAmtVal));
1464226890Sdim
1465202375Srdivacky        Value *And =
1466202375Srdivacky          Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1467202375Srdivacky        return new ICmpInst(ICI.getPredicate(), And,
1468218893Sdim                            ConstantExpr::getLShr(RHS, ShAmt));
1469202375Srdivacky      }
1470202375Srdivacky    }
1471226890Sdim
1472252723Sdim    // If this is a signed comparison to 0 and the shift is sign preserving,
1473252723Sdim    // use the shift LHS operand instead.
1474252723Sdim    ICmpInst::Predicate pred = ICI.getPredicate();
1475252723Sdim    if (isSignTest(pred, RHS) &&
1476252723Sdim        cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1477252723Sdim      return new ICmpInst(pred,
1478252723Sdim                          LHSI->getOperand(0),
1479252723Sdim                          Constant::getNullValue(RHS->getType()));
1480252723Sdim
1481202375Srdivacky    // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1482202375Srdivacky    bool TrueIfSigned = false;
1483202375Srdivacky    if (LHSI->hasOneUse() &&
1484202375Srdivacky        isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1485202375Srdivacky      // (X << 31) <s 0  --> (X&1) != 0
1486218893Sdim      Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1487226890Sdim                                        APInt::getOneBitSet(TypeBits,
1488218893Sdim                                            TypeBits-ShAmt->getZExtValue()-1));
1489202375Srdivacky      Value *And =
1490202375Srdivacky        Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1491202375Srdivacky      return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1492202375Srdivacky                          And, Constant::getNullValue(And->getType()));
1493202375Srdivacky    }
1494252723Sdim
1495252723Sdim    // Transform (icmp pred iM (shl iM %v, N), CI)
1496252723Sdim    // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1497252723Sdim    // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
1498252723Sdim    // This enables to get rid of the shift in favor of a trunc which can be
1499252723Sdim    // free on the target. It has the additional benefit of comparing to a
1500252723Sdim    // smaller constant, which will be target friendly.
1501252723Sdim    unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
1502252723Sdim    if (LHSI->hasOneUse() &&
1503252723Sdim        Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
1504252723Sdim      Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1505252723Sdim      Constant *NCI = ConstantExpr::getTrunc(
1506252723Sdim                        ConstantExpr::getAShr(RHS,
1507252723Sdim                          ConstantInt::get(RHS->getType(), Amt)),
1508252723Sdim                        NTy);
1509252723Sdim      return new ICmpInst(ICI.getPredicate(),
1510252723Sdim                          Builder->CreateTrunc(LHSI->getOperand(0), NTy),
1511252723Sdim                          NCI);
1512252723Sdim    }
1513252723Sdim
1514202375Srdivacky    break;
1515202375Srdivacky  }
1516226890Sdim
1517202375Srdivacky  case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
1518221345Sdim  case Instruction::AShr: {
1519221345Sdim    // Handle equality comparisons of shift-by-constant.
1520221345Sdim    BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1521221345Sdim    if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1522221345Sdim      if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
1523218893Sdim        return Res;
1524221345Sdim    }
1525221345Sdim
1526221345Sdim    // Handle exact shr's.
1527221345Sdim    if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1528221345Sdim      if (RHSV.isMinValue())
1529221345Sdim        return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1530221345Sdim    }
1531202375Srdivacky    break;
1532221345Sdim  }
1533226890Sdim
1534202375Srdivacky  case Instruction::SDiv:
1535202375Srdivacky  case Instruction::UDiv:
1536202375Srdivacky    // Fold: icmp pred ([us]div X, C1), C2 -> range test
1537226890Sdim    // Fold this div into the comparison, producing a range check.
1538226890Sdim    // Determine, based on the divide type, what the range is being
1539226890Sdim    // checked.  If there is an overflow on the low or high side, remember
1540202375Srdivacky    // it, otherwise compute the range [low, hi) bounding the new value.
1541202375Srdivacky    // See: InsertRangeTest above for the kinds of replacements possible.
1542202375Srdivacky    if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1543202375Srdivacky      if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1544202375Srdivacky                                          DivRHS))
1545202375Srdivacky        return R;
1546202375Srdivacky    break;
1547202375Srdivacky
1548263509Sdim  case Instruction::Sub: {
1549263509Sdim    ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1550263509Sdim    if (!LHSC) break;
1551263509Sdim    const APInt &LHSV = LHSC->getValue();
1552263509Sdim
1553263509Sdim    // C1-X <u C2 -> (X|(C2-1)) == C1
1554263509Sdim    //   iff C1 & (C2-1) == C2-1
1555263509Sdim    //       C2 is a power of 2
1556263509Sdim    if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1557263509Sdim        RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1558263509Sdim      return new ICmpInst(ICmpInst::ICMP_EQ,
1559263509Sdim                          Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1560263509Sdim                          LHSC);
1561263509Sdim
1562263509Sdim    // C1-X >u C2 -> (X|C2) != C1
1563263509Sdim    //   iff C1 & C2 == C2
1564263509Sdim    //       C2+1 is a power of 2
1565263509Sdim    if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1566263509Sdim        (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1567263509Sdim      return new ICmpInst(ICmpInst::ICMP_NE,
1568263509Sdim                          Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1569263509Sdim    break;
1570263509Sdim  }
1571263509Sdim
1572202375Srdivacky  case Instruction::Add:
1573202375Srdivacky    // Fold: icmp pred (add X, C1), C2
1574202375Srdivacky    if (!ICI.isEquality()) {
1575202375Srdivacky      ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1576202375Srdivacky      if (!LHSC) break;
1577202375Srdivacky      const APInt &LHSV = LHSC->getValue();
1578202375Srdivacky
1579202375Srdivacky      ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1580202375Srdivacky                            .subtract(LHSV);
1581202375Srdivacky
1582202375Srdivacky      if (ICI.isSigned()) {
1583202375Srdivacky        if (CR.getLower().isSignBit()) {
1584202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1585263509Sdim                              Builder->getInt(CR.getUpper()));
1586202375Srdivacky        } else if (CR.getUpper().isSignBit()) {
1587202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1588263509Sdim                              Builder->getInt(CR.getLower()));
1589202375Srdivacky        }
1590202375Srdivacky      } else {
1591202375Srdivacky        if (CR.getLower().isMinValue()) {
1592202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1593263509Sdim                              Builder->getInt(CR.getUpper()));
1594202375Srdivacky        } else if (CR.getUpper().isMinValue()) {
1595202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1596263509Sdim                              Builder->getInt(CR.getLower()));
1597202375Srdivacky        }
1598202375Srdivacky      }
1599263509Sdim
1600263509Sdim      // X-C1 <u C2 -> (X & -C2) == C1
1601263509Sdim      //   iff C1 & (C2-1) == 0
1602263509Sdim      //       C2 is a power of 2
1603263509Sdim      if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1604263509Sdim          RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
1605263509Sdim        return new ICmpInst(ICmpInst::ICMP_EQ,
1606263509Sdim                            Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1607263509Sdim                            ConstantExpr::getNeg(LHSC));
1608263509Sdim
1609263509Sdim      // X-C1 >u C2 -> (X & ~C2) != C1
1610263509Sdim      //   iff C1 & C2 == 0
1611263509Sdim      //       C2+1 is a power of 2
1612263509Sdim      if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1613263509Sdim          (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1614263509Sdim        return new ICmpInst(ICmpInst::ICMP_NE,
1615263509Sdim                            Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1616263509Sdim                            ConstantExpr::getNeg(LHSC));
1617202375Srdivacky    }
1618202375Srdivacky    break;
1619202375Srdivacky  }
1620226890Sdim
1621202375Srdivacky  // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1622202375Srdivacky  if (ICI.isEquality()) {
1623202375Srdivacky    bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1624226890Sdim
1625226890Sdim    // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
1626202375Srdivacky    // the second operand is a constant, simplify a bit.
1627202375Srdivacky    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1628202375Srdivacky      switch (BO->getOpcode()) {
1629202375Srdivacky      case Instruction::SRem:
1630202375Srdivacky        // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1631202375Srdivacky        if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1632202375Srdivacky          const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1633207618Srdivacky          if (V.sgt(1) && V.isPowerOf2()) {
1634202375Srdivacky            Value *NewRem =
1635202375Srdivacky              Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1636202375Srdivacky                                  BO->getName());
1637202375Srdivacky            return new ICmpInst(ICI.getPredicate(), NewRem,
1638202375Srdivacky                                Constant::getNullValue(BO->getType()));
1639202375Srdivacky          }
1640202375Srdivacky        }
1641202375Srdivacky        break;
1642202375Srdivacky      case Instruction::Add:
1643202375Srdivacky        // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1644202375Srdivacky        if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1645202375Srdivacky          if (BO->hasOneUse())
1646202375Srdivacky            return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1647202375Srdivacky                                ConstantExpr::getSub(RHS, BOp1C));
1648202375Srdivacky        } else if (RHSV == 0) {
1649202375Srdivacky          // Replace ((add A, B) != 0) with (A != -B) if A or B is
1650202375Srdivacky          // efficiently invertible, or if the add has just this one use.
1651202375Srdivacky          Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1652226890Sdim
1653202375Srdivacky          if (Value *NegVal = dyn_castNegVal(BOp1))
1654202375Srdivacky            return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1655221345Sdim          if (Value *NegVal = dyn_castNegVal(BOp0))
1656202375Srdivacky            return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1657221345Sdim          if (BO->hasOneUse()) {
1658202375Srdivacky            Value *Neg = Builder->CreateNeg(BOp1);
1659202375Srdivacky            Neg->takeName(BO);
1660202375Srdivacky            return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1661202375Srdivacky          }
1662202375Srdivacky        }
1663202375Srdivacky        break;
1664202375Srdivacky      case Instruction::Xor:
1665202375Srdivacky        // For the xor case, we can xor two constants together, eliminating
1666202375Srdivacky        // the explicit xor.
1667224145Sdim        if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1668224145Sdim          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1669202375Srdivacky                              ConstantExpr::getXor(RHS, BOC));
1670224145Sdim        } else if (RHSV == 0) {
1671224145Sdim          // Replace ((xor A, B) != 0) with (A != B)
1672224145Sdim          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1673224145Sdim                              BO->getOperand(1));
1674224145Sdim        }
1675224145Sdim        break;
1676202375Srdivacky      case Instruction::Sub:
1677224145Sdim        // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1678224145Sdim        if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1679224145Sdim          if (BO->hasOneUse())
1680224145Sdim            return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1681224145Sdim                                ConstantExpr::getSub(BOp0C, RHS));
1682224145Sdim        } else if (RHSV == 0) {
1683224145Sdim          // Replace ((sub A, B) != 0) with (A != B)
1684202375Srdivacky          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1685202375Srdivacky                              BO->getOperand(1));
1686224145Sdim        }
1687202375Srdivacky        break;
1688202375Srdivacky      case Instruction::Or:
1689202375Srdivacky        // If bits are being or'd in that are not present in the constant we
1690202375Srdivacky        // are comparing against, then the comparison could never succeed!
1691212904Sdim        if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1692202375Srdivacky          Constant *NotCI = ConstantExpr::getNot(RHS);
1693202375Srdivacky          if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1694263509Sdim            return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1695202375Srdivacky        }
1696202375Srdivacky        break;
1697226890Sdim
1698202375Srdivacky      case Instruction::And:
1699202375Srdivacky        if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1700202375Srdivacky          // If bits are being compared against that are and'd out, then the
1701202375Srdivacky          // comparison can never succeed!
1702202375Srdivacky          if ((RHSV & ~BOC->getValue()) != 0)
1703263509Sdim            return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1704226890Sdim
1705202375Srdivacky          // If we have ((X & C) == C), turn it into ((X & C) != 0).
1706202375Srdivacky          if (RHS == BOC && RHSV.isPowerOf2())
1707202375Srdivacky            return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1708202375Srdivacky                                ICmpInst::ICMP_NE, LHSI,
1709202375Srdivacky                                Constant::getNullValue(RHS->getType()));
1710224145Sdim
1711224145Sdim          // Don't perform the following transforms if the AND has multiple uses
1712224145Sdim          if (!BO->hasOneUse())
1713224145Sdim            break;
1714224145Sdim
1715202375Srdivacky          // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1716202375Srdivacky          if (BOC->getValue().isSignBit()) {
1717202375Srdivacky            Value *X = BO->getOperand(0);
1718202375Srdivacky            Constant *Zero = Constant::getNullValue(X->getType());
1719226890Sdim            ICmpInst::Predicate pred = isICMP_NE ?
1720202375Srdivacky              ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1721202375Srdivacky            return new ICmpInst(pred, X, Zero);
1722202375Srdivacky          }
1723226890Sdim
1724202375Srdivacky          // ((X & ~7) == 0) --> X < 8
1725202375Srdivacky          if (RHSV == 0 && isHighOnes(BOC)) {
1726202375Srdivacky            Value *X = BO->getOperand(0);
1727202375Srdivacky            Constant *NegX = ConstantExpr::getNeg(BOC);
1728226890Sdim            ICmpInst::Predicate pred = isICMP_NE ?
1729202375Srdivacky              ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1730202375Srdivacky            return new ICmpInst(pred, X, NegX);
1731202375Srdivacky          }
1732202375Srdivacky        }
1733252723Sdim        break;
1734252723Sdim      case Instruction::Mul:
1735252723Sdim        if (RHSV == 0 && BO->hasNoSignedWrap()) {
1736252723Sdim          if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1737252723Sdim            // The trivial case (mul X, 0) is handled by InstSimplify
1738252723Sdim            // General case : (mul X, C) != 0 iff X != 0
1739252723Sdim            //                (mul X, C) == 0 iff X == 0
1740252723Sdim            if (!BOC->isZero())
1741252723Sdim              return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1742252723Sdim                                  Constant::getNullValue(RHS->getType()));
1743252723Sdim          }
1744252723Sdim        }
1745252723Sdim        break;
1746202375Srdivacky      default: break;
1747202375Srdivacky      }
1748202375Srdivacky    } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1749202375Srdivacky      // Handle icmp {eq|ne} <intrinsic>, intcst.
1750202375Srdivacky      switch (II->getIntrinsicID()) {
1751202375Srdivacky      case Intrinsic::bswap:
1752202375Srdivacky        Worklist.Add(II);
1753210299Sed        ICI.setOperand(0, II->getArgOperand(0));
1754263509Sdim        ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
1755202375Srdivacky        return &ICI;
1756202375Srdivacky      case Intrinsic::ctlz:
1757202375Srdivacky      case Intrinsic::cttz:
1758202375Srdivacky        // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
1759202375Srdivacky        if (RHSV == RHS->getType()->getBitWidth()) {
1760202375Srdivacky          Worklist.Add(II);
1761210299Sed          ICI.setOperand(0, II->getArgOperand(0));
1762202375Srdivacky          ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1763202375Srdivacky          return &ICI;
1764202375Srdivacky        }
1765202375Srdivacky        break;
1766202375Srdivacky      case Intrinsic::ctpop:
1767202375Srdivacky        // popcount(A) == 0  ->  A == 0 and likewise for !=
1768202375Srdivacky        if (RHS->isZero()) {
1769202375Srdivacky          Worklist.Add(II);
1770210299Sed          ICI.setOperand(0, II->getArgOperand(0));
1771202375Srdivacky          ICI.setOperand(1, RHS);
1772202375Srdivacky          return &ICI;
1773202375Srdivacky        }
1774202375Srdivacky        break;
1775202375Srdivacky      default:
1776210299Sed        break;
1777202375Srdivacky      }
1778202375Srdivacky    }
1779202375Srdivacky  }
1780202375Srdivacky  return 0;
1781202375Srdivacky}
1782202375Srdivacky
1783202375Srdivacky/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1784202375Srdivacky/// We only handle extending casts so far.
1785202375Srdivacky///
1786202375SrdivackyInstruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1787202375Srdivacky  const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1788202375Srdivacky  Value *LHSCIOp        = LHSCI->getOperand(0);
1789226890Sdim  Type *SrcTy     = LHSCIOp->getType();
1790226890Sdim  Type *DestTy    = LHSCI->getType();
1791202375Srdivacky  Value *RHSCIOp;
1792202375Srdivacky
1793226890Sdim  // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1794202375Srdivacky  // integer type is the same size as the pointer type.
1795202375Srdivacky  if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
1796263509Sdim      TD->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
1797202375Srdivacky    Value *RHSOp = 0;
1798202375Srdivacky    if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1799202375Srdivacky      RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1800202375Srdivacky    } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1801202375Srdivacky      RHSOp = RHSC->getOperand(0);
1802202375Srdivacky      // If the pointer types don't match, insert a bitcast.
1803202375Srdivacky      if (LHSCIOp->getType() != RHSOp->getType())
1804202375Srdivacky        RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1805202375Srdivacky    }
1806202375Srdivacky
1807202375Srdivacky    if (RHSOp)
1808202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1809202375Srdivacky  }
1810226890Sdim
1811202375Srdivacky  // The code below only handles extension cast instructions, so far.
1812202375Srdivacky  // Enforce this.
1813202375Srdivacky  if (LHSCI->getOpcode() != Instruction::ZExt &&
1814202375Srdivacky      LHSCI->getOpcode() != Instruction::SExt)
1815202375Srdivacky    return 0;
1816202375Srdivacky
1817202375Srdivacky  bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1818202375Srdivacky  bool isSignedCmp = ICI.isSigned();
1819202375Srdivacky
1820202375Srdivacky  if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1821202375Srdivacky    // Not an extension from the same type?
1822202375Srdivacky    RHSCIOp = CI->getOperand(0);
1823226890Sdim    if (RHSCIOp->getType() != LHSCIOp->getType())
1824202375Srdivacky      return 0;
1825226890Sdim
1826202375Srdivacky    // If the signedness of the two casts doesn't agree (i.e. one is a sext
1827202375Srdivacky    // and the other is a zext), then we can't handle this.
1828202375Srdivacky    if (CI->getOpcode() != LHSCI->getOpcode())
1829202375Srdivacky      return 0;
1830202375Srdivacky
1831202375Srdivacky    // Deal with equality cases early.
1832202375Srdivacky    if (ICI.isEquality())
1833202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1834202375Srdivacky
1835202375Srdivacky    // A signed comparison of sign extended values simplifies into a
1836202375Srdivacky    // signed comparison.
1837202375Srdivacky    if (isSignedCmp && isSignedExt)
1838202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1839202375Srdivacky
1840202375Srdivacky    // The other three cases all fold into an unsigned comparison.
1841202375Srdivacky    return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1842202375Srdivacky  }
1843202375Srdivacky
1844202375Srdivacky  // If we aren't dealing with a constant on the RHS, exit early
1845202375Srdivacky  ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1846202375Srdivacky  if (!CI)
1847202375Srdivacky    return 0;
1848202375Srdivacky
1849202375Srdivacky  // Compute the constant that would happen if we truncated to SrcTy then
1850202375Srdivacky  // reextended to DestTy.
1851202375Srdivacky  Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1852202375Srdivacky  Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1853202375Srdivacky                                                Res1, DestTy);
1854202375Srdivacky
1855202375Srdivacky  // If the re-extended constant didn't change...
1856202375Srdivacky  if (Res2 == CI) {
1857202375Srdivacky    // Deal with equality cases early.
1858202375Srdivacky    if (ICI.isEquality())
1859202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1860202375Srdivacky
1861202375Srdivacky    // A signed comparison of sign extended values simplifies into a
1862202375Srdivacky    // signed comparison.
1863202375Srdivacky    if (isSignedExt && isSignedCmp)
1864202375Srdivacky      return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1865202375Srdivacky
1866202375Srdivacky    // The other three cases all fold into an unsigned comparison.
1867202375Srdivacky    return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1868202375Srdivacky  }
1869202375Srdivacky
1870226890Sdim  // The re-extended constant changed so the constant cannot be represented
1871202375Srdivacky  // in the shorter type. Consequently, we cannot emit a simple comparison.
1872218893Sdim  // All the cases that fold to true or false will have already been handled
1873218893Sdim  // by SimplifyICmpInst, so only deal with the tricky case.
1874202375Srdivacky
1875218893Sdim  if (isSignedCmp || !isSignedExt)
1876218893Sdim    return 0;
1877202375Srdivacky
1878202375Srdivacky  // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1879202375Srdivacky  // should have been folded away previously and not enter in here.
1880202375Srdivacky
1881218893Sdim  // We're performing an unsigned comp with a sign extended value.
1882218893Sdim  // This is true if the input is >= 0. [aka >s -1]
1883218893Sdim  Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1884218893Sdim  Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1885218893Sdim
1886202375Srdivacky  // Finally, return the value computed.
1887218893Sdim  if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1888202375Srdivacky    return ReplaceInstUsesWith(ICI, Result);
1889202375Srdivacky
1890218893Sdim  assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
1891202375Srdivacky  return BinaryOperator::CreateNot(Result);
1892202375Srdivacky}
1893202375Srdivacky
1894218893Sdim/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1895218893Sdim///   I = icmp ugt (add (add A, B), CI2), CI1
1896218893Sdim/// If this is of the form:
1897218893Sdim///   sum = a + b
1898218893Sdim///   if (sum+128 >u 255)
1899218893Sdim/// Then replace it with llvm.sadd.with.overflow.i8.
1900218893Sdim///
1901218893Sdimstatic Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1902218893Sdim                                          ConstantInt *CI2, ConstantInt *CI1,
1903218893Sdim                                          InstCombiner &IC) {
1904218893Sdim  // The transformation we're trying to do here is to transform this into an
1905218893Sdim  // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1906218893Sdim  // with a narrower add, and discard the add-with-constant that is part of the
1907218893Sdim  // range check (if we can't eliminate it, this isn't profitable).
1908226890Sdim
1909218893Sdim  // In order to eliminate the add-with-constant, the compare can be its only
1910218893Sdim  // use.
1911218893Sdim  Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1912218893Sdim  if (!AddWithCst->hasOneUse()) return 0;
1913226890Sdim
1914218893Sdim  // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1915218893Sdim  if (!CI2->getValue().isPowerOf2()) return 0;
1916218893Sdim  unsigned NewWidth = CI2->getValue().countTrailingZeros();
1917218893Sdim  if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1918226890Sdim
1919218893Sdim  // The width of the new add formed is 1 more than the bias.
1920218893Sdim  ++NewWidth;
1921226890Sdim
1922218893Sdim  // Check to see that CI1 is an all-ones value with NewWidth bits.
1923218893Sdim  if (CI1->getBitWidth() == NewWidth ||
1924218893Sdim      CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1925218893Sdim    return 0;
1926226890Sdim
1927235633Sdim  // This is only really a signed overflow check if the inputs have been
1928235633Sdim  // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1929235633Sdim  // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1930235633Sdim  unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1931235633Sdim  if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1932235633Sdim      IC.ComputeNumSignBits(B) < NeededSignBits)
1933235633Sdim    return 0;
1934235633Sdim
1935226890Sdim  // In order to replace the original add with a narrower
1936218893Sdim  // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1937218893Sdim  // and truncates that discard the high bits of the add.  Verify that this is
1938218893Sdim  // the case.
1939218893Sdim  Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1940218893Sdim  for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end();
1941218893Sdim       UI != E; ++UI) {
1942218893Sdim    if (*UI == AddWithCst) continue;
1943226890Sdim
1944218893Sdim    // Only accept truncates for now.  We would really like a nice recursive
1945218893Sdim    // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1946218893Sdim    // chain to see which bits of a value are actually demanded.  If the
1947218893Sdim    // original add had another add which was then immediately truncated, we
1948218893Sdim    // could still do the transformation.
1949218893Sdim    TruncInst *TI = dyn_cast<TruncInst>(*UI);
1950218893Sdim    if (TI == 0 ||
1951218893Sdim        TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1952218893Sdim  }
1953226890Sdim
1954218893Sdim  // If the pattern matches, truncate the inputs to the narrower type and
1955218893Sdim  // use the sadd_with_overflow intrinsic to efficiently compute both the
1956218893Sdim  // result and the overflow bit.
1957218893Sdim  Module *M = I.getParent()->getParent()->getParent();
1958226890Sdim
1959224145Sdim  Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1960218893Sdim  Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1961224145Sdim                                       NewType);
1962202375Srdivacky
1963218893Sdim  InstCombiner::BuilderTy *Builder = IC.Builder;
1964226890Sdim
1965218893Sdim  // Put the new code above the original add, in case there are any uses of the
1966218893Sdim  // add between the add and the compare.
1967218893Sdim  Builder->SetInsertPoint(OrigAdd);
1968226890Sdim
1969218893Sdim  Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1970218893Sdim  Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1971218893Sdim  CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1972218893Sdim  Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1973218893Sdim  Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1974226890Sdim
1975218893Sdim  // The inner add was the result of the narrow add, zero extended to the
1976218893Sdim  // wider type.  Replace it with the result computed by the intrinsic.
1977218893Sdim  IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
1978226890Sdim
1979218893Sdim  // The original icmp gets replaced with the overflow value.
1980218893Sdim  return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1981218893Sdim}
1982202375Srdivacky
1983218893Sdimstatic Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1984218893Sdim                                     InstCombiner &IC) {
1985218893Sdim  // Don't bother doing this transformation for pointers, don't do it for
1986218893Sdim  // vectors.
1987218893Sdim  if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1988226890Sdim
1989218893Sdim  // If the add is a constant expr, then we don't bother transforming it.
1990218893Sdim  Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1991218893Sdim  if (OrigAdd == 0) return 0;
1992226890Sdim
1993218893Sdim  Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1994226890Sdim
1995218893Sdim  // Put the new code above the original add, in case there are any uses of the
1996218893Sdim  // add between the add and the compare.
1997218893Sdim  InstCombiner::BuilderTy *Builder = IC.Builder;
1998218893Sdim  Builder->SetInsertPoint(OrigAdd);
1999218893Sdim
2000218893Sdim  Module *M = I.getParent()->getParent()->getParent();
2001224145Sdim  Type *Ty = LHS->getType();
2002224145Sdim  Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
2003218893Sdim  CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
2004218893Sdim  Value *Add = Builder->CreateExtractValue(Call, 0);
2005218893Sdim
2006218893Sdim  IC.ReplaceInstUsesWith(*OrigAdd, Add);
2007218893Sdim
2008218893Sdim  // The original icmp gets replaced with the overflow value.
2009218893Sdim  return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2010218893Sdim}
2011218893Sdim
2012218893Sdim// DemandedBitsLHSMask - When performing a comparison against a constant,
2013218893Sdim// it is possible that not all the bits in the LHS are demanded.  This helper
2014218893Sdim// method computes the mask that IS demanded.
2015218893Sdimstatic APInt DemandedBitsLHSMask(ICmpInst &I,
2016218893Sdim                                 unsigned BitWidth, bool isSignCheck) {
2017218893Sdim  if (isSignCheck)
2018218893Sdim    return APInt::getSignBit(BitWidth);
2019226890Sdim
2020218893Sdim  ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2021218893Sdim  if (!CI) return APInt::getAllOnesValue(BitWidth);
2022218893Sdim  const APInt &RHS = CI->getValue();
2023226890Sdim
2024218893Sdim  switch (I.getPredicate()) {
2025226890Sdim  // For a UGT comparison, we don't care about any bits that
2026218893Sdim  // correspond to the trailing ones of the comparand.  The value of these
2027218893Sdim  // bits doesn't impact the outcome of the comparison, because any value
2028218893Sdim  // greater than the RHS must differ in a bit higher than these due to carry.
2029218893Sdim  case ICmpInst::ICMP_UGT: {
2030218893Sdim    unsigned trailingOnes = RHS.countTrailingOnes();
2031218893Sdim    APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2032218893Sdim    return ~lowBitsSet;
2033218893Sdim  }
2034226890Sdim
2035218893Sdim  // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2036218893Sdim  // Any value less than the RHS must differ in a higher bit because of carries.
2037218893Sdim  case ICmpInst::ICMP_ULT: {
2038218893Sdim    unsigned trailingZeros = RHS.countTrailingZeros();
2039218893Sdim    APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2040218893Sdim    return ~lowBitsSet;
2041218893Sdim  }
2042226890Sdim
2043218893Sdim  default:
2044218893Sdim    return APInt::getAllOnesValue(BitWidth);
2045218893Sdim  }
2046226890Sdim
2047218893Sdim}
2048218893Sdim
2049263509Sdim/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2050263509Sdim/// should be swapped.
2051263509Sdim/// The descision is based on how many times these two operands are reused
2052263509Sdim/// as subtract operands and their positions in those instructions.
2053263509Sdim/// The rational is that several architectures use the same instruction for
2054263509Sdim/// both subtract and cmp, thus it is better if the order of those operands
2055263509Sdim/// match.
2056263509Sdim/// \return true if Op0 and Op1 should be swapped.
2057263509Sdimstatic bool swapMayExposeCSEOpportunities(const Value * Op0,
2058263509Sdim                                          const Value * Op1) {
2059263509Sdim  // Filter out pointer value as those cannot appears directly in subtract.
2060263509Sdim  // FIXME: we may want to go through inttoptrs or bitcasts.
2061263509Sdim  if (Op0->getType()->isPointerTy())
2062263509Sdim    return false;
2063263509Sdim  // Count every uses of both Op0 and Op1 in a subtract.
2064263509Sdim  // Each time Op0 is the first operand, count -1: swapping is bad, the
2065263509Sdim  // subtract has already the same layout as the compare.
2066263509Sdim  // Each time Op0 is the second operand, count +1: swapping is good, the
2067263509Sdim  // subtract has a diffrent layout as the compare.
2068263509Sdim  // At the end, if the benefit is greater than 0, Op0 should come second to
2069263509Sdim  // expose more CSE opportunities.
2070263509Sdim  int GlobalSwapBenefits = 0;
2071263509Sdim  for (Value::const_use_iterator UI = Op0->use_begin(), UIEnd = Op0->use_end(); UI != UIEnd; ++UI) {
2072263509Sdim    const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(*UI);
2073263509Sdim    if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2074263509Sdim      continue;
2075263509Sdim    // If Op0 is the first argument, this is not beneficial to swap the
2076263509Sdim    // arguments.
2077263509Sdim    int LocalSwapBenefits = -1;
2078263509Sdim    unsigned Op1Idx = 1;
2079263509Sdim    if (BinOp->getOperand(Op1Idx) == Op0) {
2080263509Sdim      Op1Idx = 0;
2081263509Sdim      LocalSwapBenefits = 1;
2082263509Sdim    }
2083263509Sdim    if (BinOp->getOperand(Op1Idx) != Op1)
2084263509Sdim      continue;
2085263509Sdim    GlobalSwapBenefits += LocalSwapBenefits;
2086263509Sdim  }
2087263509Sdim  return GlobalSwapBenefits > 0;
2088263509Sdim}
2089263509Sdim
2090202375SrdivackyInstruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2091202375Srdivacky  bool Changed = false;
2092203954Srdivacky  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2093263509Sdim  unsigned Op0Cplxity = getComplexity(Op0);
2094263509Sdim  unsigned Op1Cplxity = getComplexity(Op1);
2095226890Sdim
2096202375Srdivacky  /// Orders the operands of the compare so that they are listed from most
2097202375Srdivacky  /// complex to least complex.  This puts constants before unary operators,
2098202375Srdivacky  /// before binary operators.
2099263509Sdim  if (Op0Cplxity < Op1Cplxity ||
2100263509Sdim        (Op0Cplxity == Op1Cplxity &&
2101263509Sdim         swapMayExposeCSEOpportunities(Op0, Op1))) {
2102202375Srdivacky    I.swapOperands();
2103203954Srdivacky    std::swap(Op0, Op1);
2104202375Srdivacky    Changed = true;
2105202375Srdivacky  }
2106226890Sdim
2107202375Srdivacky  if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
2108202375Srdivacky    return ReplaceInstUsesWith(I, V);
2109202375Srdivacky
2110235633Sdim  // comparing -val or val with non-zero is the same as just comparing val
2111235633Sdim  // ie, abs(val) != 0 -> val != 0
2112235633Sdim  if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2113235633Sdim  {
2114235633Sdim    Value *Cond, *SelectTrue, *SelectFalse;
2115235633Sdim    if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
2116235633Sdim                            m_Value(SelectFalse)))) {
2117235633Sdim      if (Value *V = dyn_castNegVal(SelectTrue)) {
2118235633Sdim        if (V == SelectFalse)
2119235633Sdim          return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2120235633Sdim      }
2121235633Sdim      else if (Value *V = dyn_castNegVal(SelectFalse)) {
2122235633Sdim        if (V == SelectTrue)
2123235633Sdim          return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2124235633Sdim      }
2125235633Sdim    }
2126235633Sdim  }
2127235633Sdim
2128226890Sdim  Type *Ty = Op0->getType();
2129226890Sdim
2130202375Srdivacky  // icmp's with boolean values can always be turned into bitwise operations
2131203954Srdivacky  if (Ty->isIntegerTy(1)) {
2132202375Srdivacky    switch (I.getPredicate()) {
2133202375Srdivacky    default: llvm_unreachable("Invalid icmp instruction!");
2134202375Srdivacky    case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
2135202375Srdivacky      Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2136202375Srdivacky      return BinaryOperator::CreateNot(Xor);
2137202375Srdivacky    }
2138202375Srdivacky    case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
2139202375Srdivacky      return BinaryOperator::CreateXor(Op0, Op1);
2140202375Srdivacky
2141202375Srdivacky    case ICmpInst::ICMP_UGT:
2142202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
2143202375Srdivacky      // FALL THROUGH
2144202375Srdivacky    case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
2145202375Srdivacky      Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2146202375Srdivacky      return BinaryOperator::CreateAnd(Not, Op1);
2147202375Srdivacky    }
2148202375Srdivacky    case ICmpInst::ICMP_SGT:
2149202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
2150202375Srdivacky      // FALL THROUGH
2151202375Srdivacky    case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
2152202375Srdivacky      Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2153202375Srdivacky      return BinaryOperator::CreateAnd(Not, Op0);
2154202375Srdivacky    }
2155202375Srdivacky    case ICmpInst::ICMP_UGE:
2156202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
2157202375Srdivacky      // FALL THROUGH
2158202375Srdivacky    case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
2159202375Srdivacky      Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2160202375Srdivacky      return BinaryOperator::CreateOr(Not, Op1);
2161202375Srdivacky    }
2162202375Srdivacky    case ICmpInst::ICMP_SGE:
2163202375Srdivacky      std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
2164202375Srdivacky      // FALL THROUGH
2165202375Srdivacky    case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
2166202375Srdivacky      Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2167202375Srdivacky      return BinaryOperator::CreateOr(Not, Op0);
2168202375Srdivacky    }
2169202375Srdivacky    }
2170202375Srdivacky  }
2171202375Srdivacky
2172202375Srdivacky  unsigned BitWidth = 0;
2173218893Sdim  if (Ty->isIntOrIntVectorTy())
2174218893Sdim    BitWidth = Ty->getScalarSizeInBits();
2175218893Sdim  else if (TD)  // Pointers require TD info to get their size.
2176202375Srdivacky    BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
2177226890Sdim
2178202375Srdivacky  bool isSignBit = false;
2179202375Srdivacky
2180202375Srdivacky  // See if we are doing a comparison with a constant.
2181202375Srdivacky  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2182202375Srdivacky    Value *A = 0, *B = 0;
2183226890Sdim
2184218893Sdim    // Match the following pattern, which is a common idiom when writing
2185218893Sdim    // overflow-safe integer arithmetic function.  The source performs an
2186218893Sdim    // addition in wider type, and explicitly checks for overflow using
2187218893Sdim    // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
2188218893Sdim    // sadd_with_overflow intrinsic.
2189218893Sdim    //
2190218893Sdim    // TODO: This could probably be generalized to handle other overflow-safe
2191226890Sdim    // operations if we worked out the formulas to compute the appropriate
2192218893Sdim    // magic constants.
2193226890Sdim    //
2194218893Sdim    // sum = a + b
2195218893Sdim    // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
2196218893Sdim    {
2197218893Sdim    ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
2198218893Sdim    if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2199218893Sdim        match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
2200218893Sdim      if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
2201218893Sdim        return Res;
2202218893Sdim    }
2203226890Sdim
2204202375Srdivacky    // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2205202375Srdivacky    if (I.isEquality() && CI->isZero() &&
2206202375Srdivacky        match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2207202375Srdivacky      // (icmp cond A B) if cond is equality
2208202375Srdivacky      return new ICmpInst(I.getPredicate(), A, B);
2209202375Srdivacky    }
2210226890Sdim
2211202375Srdivacky    // If we have an icmp le or icmp ge instruction, turn it into the
2212202375Srdivacky    // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
2213202375Srdivacky    // them being folded in the code below.  The SimplifyICmpInst code has
2214202375Srdivacky    // already handled the edge cases for us, so we just assert on them.
2215202375Srdivacky    switch (I.getPredicate()) {
2216202375Srdivacky    default: break;
2217202375Srdivacky    case ICmpInst::ICMP_ULE:
2218202375Srdivacky      assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
2219202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
2220263509Sdim                          Builder->getInt(CI->getValue()+1));
2221202375Srdivacky    case ICmpInst::ICMP_SLE:
2222202375Srdivacky      assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
2223202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2224263509Sdim                          Builder->getInt(CI->getValue()+1));
2225202375Srdivacky    case ICmpInst::ICMP_UGE:
2226221345Sdim      assert(!CI->isMinValue(false));                 // A >=u MIN -> TRUE
2227202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
2228263509Sdim                          Builder->getInt(CI->getValue()-1));
2229202375Srdivacky    case ICmpInst::ICMP_SGE:
2230221345Sdim      assert(!CI->isMinValue(true));                  // A >=s MIN -> TRUE
2231202375Srdivacky      return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2232263509Sdim                          Builder->getInt(CI->getValue()-1));
2233202375Srdivacky    }
2234226890Sdim
2235202375Srdivacky    // If this comparison is a normal comparison, it demands all
2236202375Srdivacky    // bits, if it is a sign bit comparison, it only demands the sign bit.
2237202375Srdivacky    bool UnusedBit;
2238202375Srdivacky    isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2239202375Srdivacky  }
2240202375Srdivacky
2241202375Srdivacky  // See if we can fold the comparison based on range information we can get
2242202375Srdivacky  // by checking whether bits are known to be zero or one in the input.
2243202375Srdivacky  if (BitWidth != 0) {
2244202375Srdivacky    APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2245202375Srdivacky    APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2246202375Srdivacky
2247202375Srdivacky    if (SimplifyDemandedBits(I.getOperandUse(0),
2248218893Sdim                             DemandedBitsLHSMask(I, BitWidth, isSignBit),
2249202375Srdivacky                             Op0KnownZero, Op0KnownOne, 0))
2250202375Srdivacky      return &I;
2251202375Srdivacky    if (SimplifyDemandedBits(I.getOperandUse(1),
2252202375Srdivacky                             APInt::getAllOnesValue(BitWidth),
2253202375Srdivacky                             Op1KnownZero, Op1KnownOne, 0))
2254202375Srdivacky      return &I;
2255202375Srdivacky
2256202375Srdivacky    // Given the known and unknown bits, compute a range that the LHS could be
2257202375Srdivacky    // in.  Compute the Min, Max and RHS values based on the known bits. For the
2258202375Srdivacky    // EQ and NE we use unsigned values.
2259202375Srdivacky    APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2260202375Srdivacky    APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2261202375Srdivacky    if (I.isSigned()) {
2262202375Srdivacky      ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2263202375Srdivacky                                             Op0Min, Op0Max);
2264202375Srdivacky      ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2265202375Srdivacky                                             Op1Min, Op1Max);
2266202375Srdivacky    } else {
2267202375Srdivacky      ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2268202375Srdivacky                                               Op0Min, Op0Max);
2269202375Srdivacky      ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2270202375Srdivacky                                               Op1Min, Op1Max);
2271202375Srdivacky    }
2272202375Srdivacky
2273202375Srdivacky    // If Min and Max are known to be the same, then SimplifyDemandedBits
2274202375Srdivacky    // figured out that the LHS is a constant.  Just constant fold this now so
2275202375Srdivacky    // that code below can assume that Min != Max.
2276202375Srdivacky    if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2277202375Srdivacky      return new ICmpInst(I.getPredicate(),
2278221345Sdim                          ConstantInt::get(Op0->getType(), Op0Min), Op1);
2279202375Srdivacky    if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2280202375Srdivacky      return new ICmpInst(I.getPredicate(), Op0,
2281221345Sdim                          ConstantInt::get(Op1->getType(), Op1Min));
2282202375Srdivacky
2283202375Srdivacky    // Based on the range information we know about the LHS, see if we can
2284221345Sdim    // simplify this comparison.  For example, (x&4) < 8 is always true.
2285202375Srdivacky    switch (I.getPredicate()) {
2286202375Srdivacky    default: llvm_unreachable("Unknown icmp opcode!");
2287218893Sdim    case ICmpInst::ICMP_EQ: {
2288202375Srdivacky      if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2289221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2290226890Sdim
2291218893Sdim      // If all bits are known zero except for one, then we know at most one
2292218893Sdim      // bit is set.   If the comparison is against zero, then this is a check
2293218893Sdim      // to see if *that* bit is set.
2294218893Sdim      APInt Op0KnownZeroInverted = ~Op0KnownZero;
2295218893Sdim      if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2296218893Sdim        // If the LHS is an AND with the same constant, look through it.
2297218893Sdim        Value *LHS = 0;
2298218893Sdim        ConstantInt *LHSC = 0;
2299218893Sdim        if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2300218893Sdim            LHSC->getValue() != Op0KnownZeroInverted)
2301218893Sdim          LHS = Op0;
2302226890Sdim
2303218893Sdim        // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2304218893Sdim        // then turn "((1 << x)&8) == 0" into "x != 3".
2305218893Sdim        Value *X = 0;
2306218893Sdim        if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2307218893Sdim          unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2308218893Sdim          return new ICmpInst(ICmpInst::ICMP_NE, X,
2309218893Sdim                              ConstantInt::get(X->getType(), CmpVal));
2310218893Sdim        }
2311226890Sdim
2312218893Sdim        // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2313218893Sdim        // then turn "((8 >>u x)&1) == 0" into "x != 3".
2314218893Sdim        const APInt *CI;
2315218893Sdim        if (Op0KnownZeroInverted == 1 &&
2316218893Sdim            match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2317218893Sdim          return new ICmpInst(ICmpInst::ICMP_NE, X,
2318218893Sdim                              ConstantInt::get(X->getType(),
2319218893Sdim                                               CI->countTrailingZeros()));
2320218893Sdim      }
2321226890Sdim
2322202375Srdivacky      break;
2323218893Sdim    }
2324218893Sdim    case ICmpInst::ICMP_NE: {
2325202375Srdivacky      if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2326221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2327226890Sdim
2328218893Sdim      // If all bits are known zero except for one, then we know at most one
2329218893Sdim      // bit is set.   If the comparison is against zero, then this is a check
2330218893Sdim      // to see if *that* bit is set.
2331218893Sdim      APInt Op0KnownZeroInverted = ~Op0KnownZero;
2332218893Sdim      if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2333218893Sdim        // If the LHS is an AND with the same constant, look through it.
2334218893Sdim        Value *LHS = 0;
2335218893Sdim        ConstantInt *LHSC = 0;
2336218893Sdim        if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2337218893Sdim            LHSC->getValue() != Op0KnownZeroInverted)
2338218893Sdim          LHS = Op0;
2339226890Sdim
2340218893Sdim        // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2341218893Sdim        // then turn "((1 << x)&8) != 0" into "x == 3".
2342218893Sdim        Value *X = 0;
2343218893Sdim        if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2344218893Sdim          unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2345218893Sdim          return new ICmpInst(ICmpInst::ICMP_EQ, X,
2346218893Sdim                              ConstantInt::get(X->getType(), CmpVal));
2347218893Sdim        }
2348226890Sdim
2349218893Sdim        // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2350218893Sdim        // then turn "((8 >>u x)&1) != 0" into "x == 3".
2351218893Sdim        const APInt *CI;
2352218893Sdim        if (Op0KnownZeroInverted == 1 &&
2353218893Sdim            match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2354218893Sdim          return new ICmpInst(ICmpInst::ICMP_EQ, X,
2355218893Sdim                              ConstantInt::get(X->getType(),
2356218893Sdim                                               CI->countTrailingZeros()));
2357218893Sdim      }
2358226890Sdim
2359202375Srdivacky      break;
2360218893Sdim    }
2361202375Srdivacky    case ICmpInst::ICMP_ULT:
2362202375Srdivacky      if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
2363221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2364202375Srdivacky      if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
2365221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2366202375Srdivacky      if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
2367202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2368202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2369202375Srdivacky        if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
2370202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2371263509Sdim                              Builder->getInt(CI->getValue()-1));
2372202375Srdivacky
2373202375Srdivacky        // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
2374202375Srdivacky        if (CI->isMinValue(true))
2375202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2376202375Srdivacky                           Constant::getAllOnesValue(Op0->getType()));
2377202375Srdivacky      }
2378202375Srdivacky      break;
2379202375Srdivacky    case ICmpInst::ICMP_UGT:
2380202375Srdivacky      if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
2381221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2382202375Srdivacky      if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
2383221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2384202375Srdivacky
2385202375Srdivacky      if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
2386202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2387202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2388202375Srdivacky        if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
2389202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2390263509Sdim                              Builder->getInt(CI->getValue()+1));
2391202375Srdivacky
2392202375Srdivacky        // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
2393202375Srdivacky        if (CI->isMaxValue(true))
2394202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2395202375Srdivacky                              Constant::getNullValue(Op0->getType()));
2396202375Srdivacky      }
2397202375Srdivacky      break;
2398202375Srdivacky    case ICmpInst::ICMP_SLT:
2399202375Srdivacky      if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
2400221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2401202375Srdivacky      if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
2402221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2403202375Srdivacky      if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
2404202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2405202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2406202375Srdivacky        if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
2407202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2408263509Sdim                              Builder->getInt(CI->getValue()-1));
2409202375Srdivacky      }
2410202375Srdivacky      break;
2411202375Srdivacky    case ICmpInst::ICMP_SGT:
2412202375Srdivacky      if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
2413221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2414202375Srdivacky      if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
2415221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2416202375Srdivacky
2417202375Srdivacky      if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
2418202375Srdivacky        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2419202375Srdivacky      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2420202375Srdivacky        if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
2421202375Srdivacky          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2422263509Sdim                              Builder->getInt(CI->getValue()+1));
2423202375Srdivacky      }
2424202375Srdivacky      break;
2425202375Srdivacky    case ICmpInst::ICMP_SGE:
2426202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2427202375Srdivacky      if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
2428221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2429202375Srdivacky      if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
2430221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2431202375Srdivacky      break;
2432202375Srdivacky    case ICmpInst::ICMP_SLE:
2433202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2434202375Srdivacky      if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
2435221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2436202375Srdivacky      if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
2437221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2438202375Srdivacky      break;
2439202375Srdivacky    case ICmpInst::ICMP_UGE:
2440202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2441202375Srdivacky      if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
2442221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2443202375Srdivacky      if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
2444221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2445202375Srdivacky      break;
2446202375Srdivacky    case ICmpInst::ICMP_ULE:
2447202375Srdivacky      assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2448202375Srdivacky      if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
2449221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2450202375Srdivacky      if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
2451221345Sdim        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2452202375Srdivacky      break;
2453202375Srdivacky    }
2454202375Srdivacky
2455202375Srdivacky    // Turn a signed comparison into an unsigned one if both operands
2456202375Srdivacky    // are known to have the same sign.
2457202375Srdivacky    if (I.isSigned() &&
2458202375Srdivacky        ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2459202375Srdivacky         (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2460202375Srdivacky      return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2461202375Srdivacky  }
2462202375Srdivacky
2463202375Srdivacky  // Test if the ICmpInst instruction is used exclusively by a select as
2464202375Srdivacky  // part of a minimum or maximum operation. If so, refrain from doing
2465202375Srdivacky  // any other folding. This helps out other analyses which understand
2466202375Srdivacky  // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2467202375Srdivacky  // and CodeGen. And in this case, at least one of the comparison
2468202375Srdivacky  // operands has at least one user besides the compare (the select),
2469202375Srdivacky  // which would often largely negate the benefit of folding anyway.
2470202375Srdivacky  if (I.hasOneUse())
2471202375Srdivacky    if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
2472202375Srdivacky      if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2473202375Srdivacky          (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2474202375Srdivacky        return 0;
2475202375Srdivacky
2476202375Srdivacky  // See if we are doing a comparison between a constant and an instruction that
2477202375Srdivacky  // can be folded into the comparison.
2478202375Srdivacky  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2479226890Sdim    // Since the RHS is a ConstantInt (CI), if the left hand side is an
2480226890Sdim    // instruction, see if that instruction also has constants so that the
2481226890Sdim    // instruction can be folded into the icmp
2482202375Srdivacky    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2483202375Srdivacky      if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2484202375Srdivacky        return Res;
2485202375Srdivacky  }
2486202375Srdivacky
2487202375Srdivacky  // Handle icmp with constant (but not simple integer constant) RHS
2488202375Srdivacky  if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2489202375Srdivacky    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2490202375Srdivacky      switch (LHSI->getOpcode()) {
2491202375Srdivacky      case Instruction::GetElementPtr:
2492202375Srdivacky          // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2493202375Srdivacky        if (RHSC->isNullValue() &&
2494202375Srdivacky            cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2495202375Srdivacky          return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2496202375Srdivacky                  Constant::getNullValue(LHSI->getOperand(0)->getType()));
2497202375Srdivacky        break;
2498202375Srdivacky      case Instruction::PHI:
2499202375Srdivacky        // Only fold icmp into the PHI if the phi and icmp are in the same
2500202375Srdivacky        // block.  If in the same block, we're encouraging jump threading.  If
2501202375Srdivacky        // not, we are just pessimizing the code by making an i1 phi.
2502202375Srdivacky        if (LHSI->getParent() == I.getParent())
2503218893Sdim          if (Instruction *NV = FoldOpIntoPhi(I))
2504202375Srdivacky            return NV;
2505202375Srdivacky        break;
2506202375Srdivacky      case Instruction::Select: {
2507202375Srdivacky        // If either operand of the select is a constant, we can fold the
2508202375Srdivacky        // comparison into the select arms, which will cause one to be
2509202375Srdivacky        // constant folded and the select turned into a bitwise or.
2510202375Srdivacky        Value *Op1 = 0, *Op2 = 0;
2511202375Srdivacky        if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2512202375Srdivacky          Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2513202375Srdivacky        if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2514202375Srdivacky          Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2515202375Srdivacky
2516202375Srdivacky        // We only want to perform this transformation if it will not lead to
2517202375Srdivacky        // additional code. This is true if either both sides of the select
2518202375Srdivacky        // fold to a constant (in which case the icmp is replaced with a select
2519202375Srdivacky        // which will usually simplify) or this is the only user of the
2520202375Srdivacky        // select (in which case we are trading a select+icmp for a simpler
2521202375Srdivacky        // select+icmp).
2522202375Srdivacky        if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2523202375Srdivacky          if (!Op1)
2524202375Srdivacky            Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2525202375Srdivacky                                      RHSC, I.getName());
2526202375Srdivacky          if (!Op2)
2527202375Srdivacky            Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2528202375Srdivacky                                      RHSC, I.getName());
2529202375Srdivacky          return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2530202375Srdivacky        }
2531202375Srdivacky        break;
2532202375Srdivacky      }
2533202375Srdivacky      case Instruction::IntToPtr:
2534202375Srdivacky        // icmp pred inttoptr(X), null -> icmp pred X, 0
2535202375Srdivacky        if (RHSC->isNullValue() && TD &&
2536263509Sdim            TD->getIntPtrType(RHSC->getType()) ==
2537202375Srdivacky               LHSI->getOperand(0)->getType())
2538202375Srdivacky          return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2539202375Srdivacky                        Constant::getNullValue(LHSI->getOperand(0)->getType()));
2540202375Srdivacky        break;
2541202375Srdivacky
2542202375Srdivacky      case Instruction::Load:
2543202375Srdivacky        // Try to optimize things like "A[i] > 4" to index computations.
2544202375Srdivacky        if (GetElementPtrInst *GEP =
2545202375Srdivacky              dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2546202375Srdivacky          if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2547202375Srdivacky            if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2548202375Srdivacky                !cast<LoadInst>(LHSI)->isVolatile())
2549202375Srdivacky              if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2550202375Srdivacky                return Res;
2551202375Srdivacky        }
2552202375Srdivacky        break;
2553202375Srdivacky      }
2554202375Srdivacky  }
2555202375Srdivacky
2556202375Srdivacky  // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2557202375Srdivacky  if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2558202375Srdivacky    if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2559202375Srdivacky      return NI;
2560202375Srdivacky  if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2561202375Srdivacky    if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2562202375Srdivacky                           ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2563202375Srdivacky      return NI;
2564202375Srdivacky
2565202375Srdivacky  // Test to see if the operands of the icmp are casted versions of other
2566202375Srdivacky  // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
2567202375Srdivacky  // now.
2568202375Srdivacky  if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
2569226890Sdim    if (Op0->getType()->isPointerTy() &&
2570226890Sdim        (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2571202375Srdivacky      // We keep moving the cast from the left operand over to the right
2572202375Srdivacky      // operand, where it can often be eliminated completely.
2573202375Srdivacky      Op0 = CI->getOperand(0);
2574202375Srdivacky
2575202375Srdivacky      // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2576202375Srdivacky      // so eliminate it as well.
2577202375Srdivacky      if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2578202375Srdivacky        Op1 = CI2->getOperand(0);
2579202375Srdivacky
2580202375Srdivacky      // If Op1 is a constant, we can fold the cast into the constant.
2581202375Srdivacky      if (Op0->getType() != Op1->getType()) {
2582202375Srdivacky        if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2583202375Srdivacky          Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2584202375Srdivacky        } else {
2585202375Srdivacky          // Otherwise, cast the RHS right before the icmp
2586202375Srdivacky          Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2587202375Srdivacky        }
2588202375Srdivacky      }
2589202375Srdivacky      return new ICmpInst(I.getPredicate(), Op0, Op1);
2590202375Srdivacky    }
2591202375Srdivacky  }
2592226890Sdim
2593202375Srdivacky  if (isa<CastInst>(Op0)) {
2594202375Srdivacky    // Handle the special case of: icmp (cast bool to X), <cst>
2595202375Srdivacky    // This comes up when you have code like
2596202375Srdivacky    //   int X = A < B;
2597202375Srdivacky    //   if (X) ...
2598202375Srdivacky    // For generality, we handle any zero-extension of any operand comparison
2599202375Srdivacky    // with a constant or another cast from the same type.
2600202375Srdivacky    if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2601202375Srdivacky      if (Instruction *R = visitICmpInstWithCastAndCast(I))
2602202375Srdivacky        return R;
2603202375Srdivacky  }
2604218893Sdim
2605218893Sdim  // Special logic for binary operators.
2606218893Sdim  BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2607218893Sdim  BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2608218893Sdim  if (BO0 || BO1) {
2609218893Sdim    CmpInst::Predicate Pred = I.getPredicate();
2610218893Sdim    bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2611218893Sdim    if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2612218893Sdim      NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2613218893Sdim        (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2614218893Sdim        (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2615218893Sdim    if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2616218893Sdim      NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2617218893Sdim        (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2618218893Sdim        (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2619218893Sdim
2620218893Sdim    // Analyze the case when either Op0 or Op1 is an add instruction.
2621218893Sdim    // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2622218893Sdim    Value *A = 0, *B = 0, *C = 0, *D = 0;
2623218893Sdim    if (BO0 && BO0->getOpcode() == Instruction::Add)
2624218893Sdim      A = BO0->getOperand(0), B = BO0->getOperand(1);
2625218893Sdim    if (BO1 && BO1->getOpcode() == Instruction::Add)
2626218893Sdim      C = BO1->getOperand(0), D = BO1->getOperand(1);
2627218893Sdim
2628218893Sdim    // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2629218893Sdim    if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2630218893Sdim      return new ICmpInst(Pred, A == Op1 ? B : A,
2631218893Sdim                          Constant::getNullValue(Op1->getType()));
2632218893Sdim
2633218893Sdim    // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2634218893Sdim    if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2635218893Sdim      return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2636218893Sdim                          C == Op0 ? D : C);
2637218893Sdim
2638218893Sdim    // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2639218893Sdim    if (A && C && (A == C || A == D || B == C || B == D) &&
2640218893Sdim        NoOp0WrapProblem && NoOp1WrapProblem &&
2641218893Sdim        // Try not to increase register pressure.
2642218893Sdim        BO0->hasOneUse() && BO1->hasOneUse()) {
2643218893Sdim      // Determine Y and Z in the form icmp (X+Y), (X+Z).
2644245431Sdim      Value *Y, *Z;
2645245431Sdim      if (A == C) {
2646245431Sdim        // C + B == C + D  ->  B == D
2647245431Sdim        Y = B;
2648245431Sdim        Z = D;
2649245431Sdim      } else if (A == D) {
2650245431Sdim        // D + B == C + D  ->  B == C
2651245431Sdim        Y = B;
2652245431Sdim        Z = C;
2653245431Sdim      } else if (B == C) {
2654245431Sdim        // A + C == C + D  ->  A == D
2655245431Sdim        Y = A;
2656245431Sdim        Z = D;
2657245431Sdim      } else {
2658245431Sdim        assert(B == D);
2659245431Sdim        // A + D == C + D  ->  A == C
2660245431Sdim        Y = A;
2661245431Sdim        Z = C;
2662245431Sdim      }
2663218893Sdim      return new ICmpInst(Pred, Y, Z);
2664218893Sdim    }
2665218893Sdim
2666252723Sdim    // icmp slt (X + -1), Y -> icmp sle X, Y
2667252723Sdim    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2668252723Sdim        match(B, m_AllOnes()))
2669252723Sdim      return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2670252723Sdim
2671252723Sdim    // icmp sge (X + -1), Y -> icmp sgt X, Y
2672252723Sdim    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2673252723Sdim        match(B, m_AllOnes()))
2674252723Sdim      return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2675252723Sdim
2676252723Sdim    // icmp sle (X + 1), Y -> icmp slt X, Y
2677252723Sdim    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2678252723Sdim        match(B, m_One()))
2679252723Sdim      return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2680252723Sdim
2681252723Sdim    // icmp sgt (X + 1), Y -> icmp sge X, Y
2682252723Sdim    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2683252723Sdim        match(B, m_One()))
2684252723Sdim      return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2685252723Sdim
2686252723Sdim    // if C1 has greater magnitude than C2:
2687252723Sdim    //  icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2688252723Sdim    //  s.t. C3 = C1 - C2
2689252723Sdim    //
2690252723Sdim    // if C2 has greater magnitude than C1:
2691252723Sdim    //  icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2692252723Sdim    //  s.t. C3 = C2 - C1
2693252723Sdim    if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2694252723Sdim        (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2695252723Sdim      if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2696252723Sdim        if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2697252723Sdim          const APInt &AP1 = C1->getValue();
2698252723Sdim          const APInt &AP2 = C2->getValue();
2699252723Sdim          if (AP1.isNegative() == AP2.isNegative()) {
2700252723Sdim            APInt AP1Abs = C1->getValue().abs();
2701252723Sdim            APInt AP2Abs = C2->getValue().abs();
2702252723Sdim            if (AP1Abs.uge(AP2Abs)) {
2703252723Sdim              ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2704252723Sdim              Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2705252723Sdim              return new ICmpInst(Pred, NewAdd, C);
2706252723Sdim            } else {
2707252723Sdim              ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2708252723Sdim              Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2709252723Sdim              return new ICmpInst(Pred, A, NewAdd);
2710252723Sdim            }
2711252723Sdim          }
2712252723Sdim        }
2713252723Sdim
2714252723Sdim
2715218893Sdim    // Analyze the case when either Op0 or Op1 is a sub instruction.
2716218893Sdim    // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2717218893Sdim    A = 0; B = 0; C = 0; D = 0;
2718218893Sdim    if (BO0 && BO0->getOpcode() == Instruction::Sub)
2719218893Sdim      A = BO0->getOperand(0), B = BO0->getOperand(1);
2720218893Sdim    if (BO1 && BO1->getOpcode() == Instruction::Sub)
2721218893Sdim      C = BO1->getOperand(0), D = BO1->getOperand(1);
2722218893Sdim
2723218893Sdim    // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2724218893Sdim    if (A == Op1 && NoOp0WrapProblem)
2725218893Sdim      return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2726218893Sdim
2727218893Sdim    // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2728218893Sdim    if (C == Op0 && NoOp1WrapProblem)
2729218893Sdim      return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2730218893Sdim
2731218893Sdim    // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2732218893Sdim    if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2733218893Sdim        // Try not to increase register pressure.
2734218893Sdim        BO0->hasOneUse() && BO1->hasOneUse())
2735218893Sdim      return new ICmpInst(Pred, A, C);
2736218893Sdim
2737218893Sdim    // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2738218893Sdim    if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2739218893Sdim        // Try not to increase register pressure.
2740218893Sdim        BO0->hasOneUse() && BO1->hasOneUse())
2741218893Sdim      return new ICmpInst(Pred, D, B);
2742218893Sdim
2743221345Sdim    BinaryOperator *SRem = NULL;
2744221345Sdim    // icmp (srem X, Y), Y
2745221345Sdim    if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2746221345Sdim        Op1 == BO0->getOperand(1))
2747221345Sdim      SRem = BO0;
2748221345Sdim    // icmp Y, (srem X, Y)
2749221345Sdim    else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2750221345Sdim             Op0 == BO1->getOperand(1))
2751221345Sdim      SRem = BO1;
2752221345Sdim    if (SRem) {
2753221345Sdim      // We don't check hasOneUse to avoid increasing register pressure because
2754221345Sdim      // the value we use is the same value this instruction was already using.
2755221345Sdim      switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2756221345Sdim        default: break;
2757221345Sdim        case ICmpInst::ICMP_EQ:
2758221345Sdim          return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2759221345Sdim        case ICmpInst::ICMP_NE:
2760221345Sdim          return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2761221345Sdim        case ICmpInst::ICMP_SGT:
2762221345Sdim        case ICmpInst::ICMP_SGE:
2763221345Sdim          return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2764221345Sdim                              Constant::getAllOnesValue(SRem->getType()));
2765221345Sdim        case ICmpInst::ICMP_SLT:
2766221345Sdim        case ICmpInst::ICMP_SLE:
2767221345Sdim          return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2768221345Sdim                              Constant::getNullValue(SRem->getType()));
2769221345Sdim      }
2770221345Sdim    }
2771221345Sdim
2772218893Sdim    if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2773218893Sdim        BO0->hasOneUse() && BO1->hasOneUse() &&
2774218893Sdim        BO0->getOperand(1) == BO1->getOperand(1)) {
2775218893Sdim      switch (BO0->getOpcode()) {
2776218893Sdim      default: break;
2777218893Sdim      case Instruction::Add:
2778218893Sdim      case Instruction::Sub:
2779218893Sdim      case Instruction::Xor:
2780218893Sdim        if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
2781218893Sdim          return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2782218893Sdim                              BO1->getOperand(0));
2783218893Sdim        // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2784218893Sdim        if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2785218893Sdim          if (CI->getValue().isSignBit()) {
2786218893Sdim            ICmpInst::Predicate Pred = I.isSigned()
2787218893Sdim                                           ? I.getUnsignedPredicate()
2788218893Sdim                                           : I.getSignedPredicate();
2789218893Sdim            return new ICmpInst(Pred, BO0->getOperand(0),
2790218893Sdim                                BO1->getOperand(0));
2791202375Srdivacky          }
2792226890Sdim
2793224145Sdim          if (CI->isMaxValue(true)) {
2794218893Sdim            ICmpInst::Predicate Pred = I.isSigned()
2795218893Sdim                                           ? I.getUnsignedPredicate()
2796218893Sdim                                           : I.getSignedPredicate();
2797218893Sdim            Pred = I.getSwappedPredicate(Pred);
2798218893Sdim            return new ICmpInst(Pred, BO0->getOperand(0),
2799218893Sdim                                BO1->getOperand(0));
2800218893Sdim          }
2801218893Sdim        }
2802218893Sdim        break;
2803218893Sdim      case Instruction::Mul:
2804218893Sdim        if (!I.isEquality())
2805202375Srdivacky          break;
2806202375Srdivacky
2807218893Sdim        if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2808218893Sdim          // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2809218893Sdim          // Mask = -1 >> count-trailing-zeros(Cst).
2810218893Sdim          if (!CI->isZero() && !CI->isOne()) {
2811218893Sdim            const APInt &AP = CI->getValue();
2812226890Sdim            ConstantInt *Mask = ConstantInt::get(I.getContext(),
2813218893Sdim                                    APInt::getLowBitsSet(AP.getBitWidth(),
2814218893Sdim                                                         AP.getBitWidth() -
2815218893Sdim                                                    AP.countTrailingZeros()));
2816218893Sdim            Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2817218893Sdim            Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2818218893Sdim            return new ICmpInst(I.getPredicate(), And1, And2);
2819202375Srdivacky          }
2820202375Srdivacky        }
2821218893Sdim        break;
2822221345Sdim      case Instruction::UDiv:
2823221345Sdim      case Instruction::LShr:
2824221345Sdim        if (I.isSigned())
2825221345Sdim          break;
2826221345Sdim        // fall-through
2827221345Sdim      case Instruction::SDiv:
2828221345Sdim      case Instruction::AShr:
2829223017Sdim        if (!BO0->isExact() || !BO1->isExact())
2830221345Sdim          break;
2831221345Sdim        return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2832221345Sdim                            BO1->getOperand(0));
2833221345Sdim      case Instruction::Shl: {
2834221345Sdim        bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2835221345Sdim        bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2836221345Sdim        if (!NUW && !NSW)
2837221345Sdim          break;
2838221345Sdim        if (!NSW && I.isSigned())
2839221345Sdim          break;
2840221345Sdim        return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2841221345Sdim                            BO1->getOperand(0));
2842202375Srdivacky      }
2843221345Sdim      }
2844202375Srdivacky    }
2845202375Srdivacky  }
2846226890Sdim
2847202375Srdivacky  { Value *A, *B;
2848252723Sdim    // Transform (A & ~B) == 0 --> (A & B) != 0
2849252723Sdim    // and       (A & ~B) != 0 --> (A & B) == 0
2850252723Sdim    // if A is a power of 2.
2851252723Sdim    if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2852252723Sdim        match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
2853252723Sdim      return new ICmpInst(I.getInversePredicate(),
2854252723Sdim                          Builder->CreateAnd(A, B),
2855252723Sdim                          Op1);
2856252723Sdim
2857218893Sdim    // ~x < ~y --> y < x
2858218893Sdim    // ~x < cst --> ~cst < x
2859218893Sdim    if (match(Op0, m_Not(m_Value(A)))) {
2860218893Sdim      if (match(Op1, m_Not(m_Value(B))))
2861218893Sdim        return new ICmpInst(I.getPredicate(), B, A);
2862218893Sdim      if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2863218893Sdim        return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2864218893Sdim    }
2865218893Sdim
2866218893Sdim    // (a+b) <u a  --> llvm.uadd.with.overflow.
2867218893Sdim    // (a+b) <u b  --> llvm.uadd.with.overflow.
2868218893Sdim    if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2869226890Sdim        match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2870218893Sdim        (Op1 == A || Op1 == B))
2871218893Sdim      if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2872218893Sdim        return R;
2873226890Sdim
2874218893Sdim    // a >u (a+b)  --> llvm.uadd.with.overflow.
2875218893Sdim    // b >u (a+b)  --> llvm.uadd.with.overflow.
2876218893Sdim    if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2877218893Sdim        match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2878218893Sdim        (Op0 == A || Op0 == B))
2879218893Sdim      if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2880218893Sdim        return R;
2881202375Srdivacky  }
2882226890Sdim
2883202375Srdivacky  if (I.isEquality()) {
2884202375Srdivacky    Value *A, *B, *C, *D;
2885218893Sdim
2886202375Srdivacky    if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2887202375Srdivacky      if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
2888202375Srdivacky        Value *OtherVal = A == Op1 ? B : A;
2889202375Srdivacky        return new ICmpInst(I.getPredicate(), OtherVal,
2890202375Srdivacky                            Constant::getNullValue(A->getType()));
2891202375Srdivacky      }
2892202375Srdivacky
2893202375Srdivacky      if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2894202375Srdivacky        // A^c1 == C^c2 --> A == C^(c1^c2)
2895202375Srdivacky        ConstantInt *C1, *C2;
2896202375Srdivacky        if (match(B, m_ConstantInt(C1)) &&
2897202375Srdivacky            match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2898263509Sdim          Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
2899226890Sdim          Value *Xor = Builder->CreateXor(C, NC);
2900202375Srdivacky          return new ICmpInst(I.getPredicate(), A, Xor);
2901202375Srdivacky        }
2902226890Sdim
2903202375Srdivacky        // A^B == A^D -> B == D
2904202375Srdivacky        if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2905202375Srdivacky        if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2906202375Srdivacky        if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2907202375Srdivacky        if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2908202375Srdivacky      }
2909202375Srdivacky    }
2910226890Sdim
2911202375Srdivacky    if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2912202375Srdivacky        (A == Op0 || B == Op0)) {
2913202375Srdivacky      // A == (A^B)  ->  B == 0
2914202375Srdivacky      Value *OtherVal = A == Op0 ? B : A;
2915202375Srdivacky      return new ICmpInst(I.getPredicate(), OtherVal,
2916202375Srdivacky                          Constant::getNullValue(A->getType()));
2917202375Srdivacky    }
2918202375Srdivacky
2919202375Srdivacky    // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2920226890Sdim    if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
2921221345Sdim        match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
2922202375Srdivacky      Value *X = 0, *Y = 0, *Z = 0;
2923226890Sdim
2924202375Srdivacky      if (A == C) {
2925202375Srdivacky        X = B; Y = D; Z = A;
2926202375Srdivacky      } else if (A == D) {
2927202375Srdivacky        X = B; Y = C; Z = A;
2928202375Srdivacky      } else if (B == C) {
2929202375Srdivacky        X = A; Y = D; Z = B;
2930202375Srdivacky      } else if (B == D) {
2931202375Srdivacky        X = A; Y = C; Z = B;
2932202375Srdivacky      }
2933226890Sdim
2934202375Srdivacky      if (X) {   // Build (X^Y) & Z
2935226890Sdim        Op1 = Builder->CreateXor(X, Y);
2936226890Sdim        Op1 = Builder->CreateAnd(Op1, Z);
2937202375Srdivacky        I.setOperand(0, Op1);
2938202375Srdivacky        I.setOperand(1, Constant::getNullValue(Op1->getType()));
2939202375Srdivacky        return &I;
2940202375Srdivacky      }
2941202375Srdivacky    }
2942226890Sdim
2943245431Sdim    // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
2944245431Sdim    // and       (B & (1<<X)-1) == (zext A) --> A == (trunc B)
2945245431Sdim    ConstantInt *Cst1;
2946245431Sdim    if ((Op0->hasOneUse() &&
2947245431Sdim         match(Op0, m_ZExt(m_Value(A))) &&
2948245431Sdim         match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2949245431Sdim        (Op1->hasOneUse() &&
2950245431Sdim         match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2951245431Sdim         match(Op1, m_ZExt(m_Value(A))))) {
2952245431Sdim      APInt Pow2 = Cst1->getValue() + 1;
2953245431Sdim      if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2954245431Sdim          Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2955245431Sdim        return new ICmpInst(I.getPredicate(), A,
2956245431Sdim                            Builder->CreateTrunc(B, A->getType()));
2957245431Sdim    }
2958245431Sdim
2959263509Sdim    // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
2960263509Sdim    // For lshr and ashr pairs.
2961263509Sdim    if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2962263509Sdim         match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
2963263509Sdim        (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2964263509Sdim         match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
2965263509Sdim      unsigned TypeBits = Cst1->getBitWidth();
2966263509Sdim      unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
2967263509Sdim      if (ShAmt < TypeBits && ShAmt != 0) {
2968263509Sdim        ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
2969263509Sdim                                       ? ICmpInst::ICMP_UGE
2970263509Sdim                                       : ICmpInst::ICMP_ULT;
2971263509Sdim        Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
2972263509Sdim        APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
2973263509Sdim        return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
2974263509Sdim      }
2975263509Sdim    }
2976263509Sdim
2977221345Sdim    // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2978221345Sdim    // "icmp (and X, mask), cst"
2979221345Sdim    uint64_t ShAmt = 0;
2980221345Sdim    if (Op0->hasOneUse() &&
2981221345Sdim        match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2982221345Sdim                                           m_ConstantInt(ShAmt))))) &&
2983221345Sdim        match(Op1, m_ConstantInt(Cst1)) &&
2984221345Sdim        // Only do this when A has multiple uses.  This is most important to do
2985221345Sdim        // when it exposes other optimizations.
2986221345Sdim        !A->hasOneUse()) {
2987221345Sdim      unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
2988226890Sdim
2989221345Sdim      if (ShAmt < ASize) {
2990221345Sdim        APInt MaskV =
2991221345Sdim          APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2992221345Sdim        MaskV <<= ShAmt;
2993226890Sdim
2994221345Sdim        APInt CmpV = Cst1->getValue().zext(ASize);
2995221345Sdim        CmpV <<= ShAmt;
2996226890Sdim
2997221345Sdim        Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2998221345Sdim        return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2999221345Sdim      }
3000221345Sdim    }
3001202375Srdivacky  }
3002226890Sdim
3003202375Srdivacky  {
3004202375Srdivacky    Value *X; ConstantInt *Cst;
3005202375Srdivacky    // icmp X+Cst, X
3006202375Srdivacky    if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
3007263509Sdim      return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
3008202375Srdivacky
3009202375Srdivacky    // icmp X, X+Cst
3010202375Srdivacky    if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
3011263509Sdim      return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
3012202375Srdivacky  }
3013202375Srdivacky  return Changed ? &I : 0;
3014202375Srdivacky}
3015202375Srdivacky
3016202375Srdivacky/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
3017202375Srdivacky///
3018202375SrdivackyInstruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3019202375Srdivacky                                                Instruction *LHSI,
3020202375Srdivacky                                                Constant *RHSC) {
3021202375Srdivacky  if (!isa<ConstantFP>(RHSC)) return 0;
3022202375Srdivacky  const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
3023226890Sdim
3024202375Srdivacky  // Get the width of the mantissa.  We don't want to hack on conversions that
3025202375Srdivacky  // might lose information from the integer, e.g. "i64 -> float"
3026202375Srdivacky  int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
3027202375Srdivacky  if (MantissaWidth == -1) return 0;  // Unknown.
3028226890Sdim
3029202375Srdivacky  // Check to see that the input is converted from an integer type that is small
3030202375Srdivacky  // enough that preserves all bits.  TODO: check here for "known" sign bits.
3031202375Srdivacky  // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3032202375Srdivacky  unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
3033226890Sdim
3034202375Srdivacky  // If this is a uitofp instruction, we need an extra bit to hold the sign.
3035202375Srdivacky  bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3036202375Srdivacky  if (LHSUnsigned)
3037202375Srdivacky    ++InputSize;
3038226890Sdim
3039202375Srdivacky  // If the conversion would lose info, don't hack on this.
3040202375Srdivacky  if ((int)InputSize > MantissaWidth)
3041202375Srdivacky    return 0;
3042226890Sdim
3043202375Srdivacky  // Otherwise, we can potentially simplify the comparison.  We know that it
3044202375Srdivacky  // will always come through as an integer value and we know the constant is
3045202375Srdivacky  // not a NAN (it would have been previously simplified).
3046202375Srdivacky  assert(!RHS.isNaN() && "NaN comparison not already folded!");
3047226890Sdim
3048202375Srdivacky  ICmpInst::Predicate Pred;
3049202375Srdivacky  switch (I.getPredicate()) {
3050202375Srdivacky  default: llvm_unreachable("Unexpected predicate!");
3051202375Srdivacky  case FCmpInst::FCMP_UEQ:
3052202375Srdivacky  case FCmpInst::FCMP_OEQ:
3053202375Srdivacky    Pred = ICmpInst::ICMP_EQ;
3054202375Srdivacky    break;
3055202375Srdivacky  case FCmpInst::FCMP_UGT:
3056202375Srdivacky  case FCmpInst::FCMP_OGT:
3057202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3058202375Srdivacky    break;
3059202375Srdivacky  case FCmpInst::FCMP_UGE:
3060202375Srdivacky  case FCmpInst::FCMP_OGE:
3061202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3062202375Srdivacky    break;
3063202375Srdivacky  case FCmpInst::FCMP_ULT:
3064202375Srdivacky  case FCmpInst::FCMP_OLT:
3065202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3066202375Srdivacky    break;
3067202375Srdivacky  case FCmpInst::FCMP_ULE:
3068202375Srdivacky  case FCmpInst::FCMP_OLE:
3069202375Srdivacky    Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3070202375Srdivacky    break;
3071202375Srdivacky  case FCmpInst::FCMP_UNE:
3072202375Srdivacky  case FCmpInst::FCMP_ONE:
3073202375Srdivacky    Pred = ICmpInst::ICMP_NE;
3074202375Srdivacky    break;
3075202375Srdivacky  case FCmpInst::FCMP_ORD:
3076263509Sdim    return ReplaceInstUsesWith(I, Builder->getTrue());
3077202375Srdivacky  case FCmpInst::FCMP_UNO:
3078263509Sdim    return ReplaceInstUsesWith(I, Builder->getFalse());
3079202375Srdivacky  }
3080226890Sdim
3081226890Sdim  IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
3082226890Sdim
3083202375Srdivacky  // Now we know that the APFloat is a normal number, zero or inf.
3084226890Sdim
3085202375Srdivacky  // See if the FP constant is too large for the integer.  For example,
3086202375Srdivacky  // comparing an i8 to 300.0.
3087202375Srdivacky  unsigned IntWidth = IntTy->getScalarSizeInBits();
3088226890Sdim
3089202375Srdivacky  if (!LHSUnsigned) {
3090202375Srdivacky    // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
3091202375Srdivacky    // and large values.
3092263509Sdim    APFloat SMax(RHS.getSemantics());
3093202375Srdivacky    SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3094202375Srdivacky                          APFloat::rmNearestTiesToEven);
3095202375Srdivacky    if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
3096202375Srdivacky      if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
3097202375Srdivacky          Pred == ICmpInst::ICMP_SLE)
3098263509Sdim        return ReplaceInstUsesWith(I, Builder->getTrue());
3099263509Sdim      return ReplaceInstUsesWith(I, Builder->getFalse());
3100202375Srdivacky    }
3101202375Srdivacky  } else {
3102202375Srdivacky    // If the RHS value is > UnsignedMax, fold the comparison. This handles
3103202375Srdivacky    // +INF and large values.
3104263509Sdim    APFloat UMax(RHS.getSemantics());
3105202375Srdivacky    UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3106202375Srdivacky                          APFloat::rmNearestTiesToEven);
3107202375Srdivacky    if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
3108202375Srdivacky      if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
3109202375Srdivacky          Pred == ICmpInst::ICMP_ULE)
3110263509Sdim        return ReplaceInstUsesWith(I, Builder->getTrue());
3111263509Sdim      return ReplaceInstUsesWith(I, Builder->getFalse());
3112202375Srdivacky    }
3113202375Srdivacky  }
3114226890Sdim
3115202375Srdivacky  if (!LHSUnsigned) {
3116202375Srdivacky    // See if the RHS value is < SignedMin.
3117263509Sdim    APFloat SMin(RHS.getSemantics());
3118202375Srdivacky    SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3119202375Srdivacky                          APFloat::rmNearestTiesToEven);
3120202375Srdivacky    if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3121202375Srdivacky      if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3122202375Srdivacky          Pred == ICmpInst::ICMP_SGE)
3123263509Sdim        return ReplaceInstUsesWith(I, Builder->getTrue());
3124263509Sdim      return ReplaceInstUsesWith(I, Builder->getFalse());
3125202375Srdivacky    }
3126235633Sdim  } else {
3127235633Sdim    // See if the RHS value is < UnsignedMin.
3128263509Sdim    APFloat SMin(RHS.getSemantics());
3129235633Sdim    SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3130235633Sdim                          APFloat::rmNearestTiesToEven);
3131235633Sdim    if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3132235633Sdim      if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3133235633Sdim          Pred == ICmpInst::ICMP_UGE)
3134263509Sdim        return ReplaceInstUsesWith(I, Builder->getTrue());
3135263509Sdim      return ReplaceInstUsesWith(I, Builder->getFalse());
3136235633Sdim    }
3137202375Srdivacky  }
3138202375Srdivacky
3139202375Srdivacky  // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3140202375Srdivacky  // [0, UMAX], but it may still be fractional.  See if it is fractional by
3141202375Srdivacky  // casting the FP value to the integer value and back, checking for equality.
3142202375Srdivacky  // Don't do this for zero, because -0.0 is not fractional.
3143202375Srdivacky  Constant *RHSInt = LHSUnsigned
3144202375Srdivacky    ? ConstantExpr::getFPToUI(RHSC, IntTy)
3145202375Srdivacky    : ConstantExpr::getFPToSI(RHSC, IntTy);
3146202375Srdivacky  if (!RHS.isZero()) {
3147202375Srdivacky    bool Equal = LHSUnsigned
3148202375Srdivacky      ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3149202375Srdivacky      : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3150202375Srdivacky    if (!Equal) {
3151202375Srdivacky      // If we had a comparison against a fractional value, we have to adjust
3152202375Srdivacky      // the compare predicate and sometimes the value.  RHSC is rounded towards
3153202375Srdivacky      // zero at this point.
3154202375Srdivacky      switch (Pred) {
3155202375Srdivacky      default: llvm_unreachable("Unexpected integer comparison!");
3156202375Srdivacky      case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
3157263509Sdim        return ReplaceInstUsesWith(I, Builder->getTrue());
3158202375Srdivacky      case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
3159263509Sdim        return ReplaceInstUsesWith(I, Builder->getFalse());
3160202375Srdivacky      case ICmpInst::ICMP_ULE:
3161202375Srdivacky        // (float)int <= 4.4   --> int <= 4
3162202375Srdivacky        // (float)int <= -4.4  --> false
3163202375Srdivacky        if (RHS.isNegative())
3164263509Sdim          return ReplaceInstUsesWith(I, Builder->getFalse());
3165202375Srdivacky        break;
3166202375Srdivacky      case ICmpInst::ICMP_SLE:
3167202375Srdivacky        // (float)int <= 4.4   --> int <= 4
3168202375Srdivacky        // (float)int <= -4.4  --> int < -4
3169202375Srdivacky        if (RHS.isNegative())
3170202375Srdivacky          Pred = ICmpInst::ICMP_SLT;
3171202375Srdivacky        break;
3172202375Srdivacky      case ICmpInst::ICMP_ULT:
3173202375Srdivacky        // (float)int < -4.4   --> false
3174202375Srdivacky        // (float)int < 4.4    --> int <= 4
3175202375Srdivacky        if (RHS.isNegative())
3176263509Sdim          return ReplaceInstUsesWith(I, Builder->getFalse());
3177202375Srdivacky        Pred = ICmpInst::ICMP_ULE;
3178202375Srdivacky        break;
3179202375Srdivacky      case ICmpInst::ICMP_SLT:
3180202375Srdivacky        // (float)int < -4.4   --> int < -4
3181202375Srdivacky        // (float)int < 4.4    --> int <= 4
3182202375Srdivacky        if (!RHS.isNegative())
3183202375Srdivacky          Pred = ICmpInst::ICMP_SLE;
3184202375Srdivacky        break;
3185202375Srdivacky      case ICmpInst::ICMP_UGT:
3186202375Srdivacky        // (float)int > 4.4    --> int > 4
3187202375Srdivacky        // (float)int > -4.4   --> true
3188202375Srdivacky        if (RHS.isNegative())
3189263509Sdim          return ReplaceInstUsesWith(I, Builder->getTrue());
3190202375Srdivacky        break;
3191202375Srdivacky      case ICmpInst::ICMP_SGT:
3192202375Srdivacky        // (float)int > 4.4    --> int > 4
3193202375Srdivacky        // (float)int > -4.4   --> int >= -4
3194202375Srdivacky        if (RHS.isNegative())
3195202375Srdivacky          Pred = ICmpInst::ICMP_SGE;
3196202375Srdivacky        break;
3197202375Srdivacky      case ICmpInst::ICMP_UGE:
3198202375Srdivacky        // (float)int >= -4.4   --> true
3199202375Srdivacky        // (float)int >= 4.4    --> int > 4
3200245431Sdim        if (RHS.isNegative())
3201263509Sdim          return ReplaceInstUsesWith(I, Builder->getTrue());
3202202375Srdivacky        Pred = ICmpInst::ICMP_UGT;
3203202375Srdivacky        break;
3204202375Srdivacky      case ICmpInst::ICMP_SGE:
3205202375Srdivacky        // (float)int >= -4.4   --> int >= -4
3206202375Srdivacky        // (float)int >= 4.4    --> int > 4
3207202375Srdivacky        if (!RHS.isNegative())
3208202375Srdivacky          Pred = ICmpInst::ICMP_SGT;
3209202375Srdivacky        break;
3210202375Srdivacky      }
3211202375Srdivacky    }
3212202375Srdivacky  }
3213202375Srdivacky
3214202375Srdivacky  // Lower this FP comparison into an appropriate integer version of the
3215202375Srdivacky  // comparison.
3216202375Srdivacky  return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3217202375Srdivacky}
3218202375Srdivacky
3219202375SrdivackyInstruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3220202375Srdivacky  bool Changed = false;
3221226890Sdim
3222202375Srdivacky  /// Orders the operands of the compare so that they are listed from most
3223202375Srdivacky  /// complex to least complex.  This puts constants before unary operators,
3224202375Srdivacky  /// before binary operators.
3225202375Srdivacky  if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3226202375Srdivacky    I.swapOperands();
3227202375Srdivacky    Changed = true;
3228202375Srdivacky  }
3229202375Srdivacky
3230202375Srdivacky  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3231226890Sdim
3232202375Srdivacky  if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
3233202375Srdivacky    return ReplaceInstUsesWith(I, V);
3234202375Srdivacky
3235202375Srdivacky  // Simplify 'fcmp pred X, X'
3236202375Srdivacky  if (Op0 == Op1) {
3237202375Srdivacky    switch (I.getPredicate()) {
3238202375Srdivacky    default: llvm_unreachable("Unknown predicate!");
3239202375Srdivacky    case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
3240202375Srdivacky    case FCmpInst::FCMP_ULT:    // True if unordered or less than
3241202375Srdivacky    case FCmpInst::FCMP_UGT:    // True if unordered or greater than
3242202375Srdivacky    case FCmpInst::FCMP_UNE:    // True if unordered or not equal
3243202375Srdivacky      // Canonicalize these to be 'fcmp uno %X, 0.0'.
3244202375Srdivacky      I.setPredicate(FCmpInst::FCMP_UNO);
3245202375Srdivacky      I.setOperand(1, Constant::getNullValue(Op0->getType()));
3246202375Srdivacky      return &I;
3247226890Sdim
3248202375Srdivacky    case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
3249202375Srdivacky    case FCmpInst::FCMP_OEQ:    // True if ordered and equal
3250202375Srdivacky    case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
3251202375Srdivacky    case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
3252202375Srdivacky      // Canonicalize these to be 'fcmp ord %X, 0.0'.
3253202375Srdivacky      I.setPredicate(FCmpInst::FCMP_ORD);
3254202375Srdivacky      I.setOperand(1, Constant::getNullValue(Op0->getType()));
3255202375Srdivacky      return &I;
3256202375Srdivacky    }
3257202375Srdivacky  }
3258226890Sdim
3259202375Srdivacky  // Handle fcmp with constant RHS
3260202375Srdivacky  if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3261202375Srdivacky    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3262202375Srdivacky      switch (LHSI->getOpcode()) {
3263221345Sdim      case Instruction::FPExt: {
3264221345Sdim        // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3265221345Sdim        FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3266221345Sdim        ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3267221345Sdim        if (!RHSF)
3268221345Sdim          break;
3269221345Sdim
3270221345Sdim        const fltSemantics *Sem;
3271221345Sdim        // FIXME: This shouldn't be here.
3272235633Sdim        if (LHSExt->getSrcTy()->isHalfTy())
3273235633Sdim          Sem = &APFloat::IEEEhalf;
3274235633Sdim        else if (LHSExt->getSrcTy()->isFloatTy())
3275221345Sdim          Sem = &APFloat::IEEEsingle;
3276221345Sdim        else if (LHSExt->getSrcTy()->isDoubleTy())
3277221345Sdim          Sem = &APFloat::IEEEdouble;
3278221345Sdim        else if (LHSExt->getSrcTy()->isFP128Ty())
3279221345Sdim          Sem = &APFloat::IEEEquad;
3280221345Sdim        else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3281221345Sdim          Sem = &APFloat::x87DoubleExtended;
3282245431Sdim        else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3283245431Sdim          Sem = &APFloat::PPCDoubleDouble;
3284221345Sdim        else
3285221345Sdim          break;
3286221345Sdim
3287221345Sdim        bool Lossy;
3288221345Sdim        APFloat F = RHSF->getValueAPF();
3289221345Sdim        F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3290221345Sdim
3291226890Sdim        // Avoid lossy conversions and denormals. Zero is a special case
3292226890Sdim        // that's OK to convert.
3293226890Sdim        APFloat Fabs = F;
3294226890Sdim        Fabs.clearSign();
3295221345Sdim        if (!Lossy &&
3296226890Sdim            ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3297226890Sdim                 APFloat::cmpLessThan) || Fabs.isZero()))
3298226890Sdim
3299221345Sdim          return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3300221345Sdim                              ConstantFP::get(RHSC->getContext(), F));
3301221345Sdim        break;
3302221345Sdim      }
3303202375Srdivacky      case Instruction::PHI:
3304202375Srdivacky        // Only fold fcmp into the PHI if the phi and fcmp are in the same
3305202375Srdivacky        // block.  If in the same block, we're encouraging jump threading.  If
3306202375Srdivacky        // not, we are just pessimizing the code by making an i1 phi.
3307202375Srdivacky        if (LHSI->getParent() == I.getParent())
3308218893Sdim          if (Instruction *NV = FoldOpIntoPhi(I))
3309202375Srdivacky            return NV;
3310202375Srdivacky        break;
3311202375Srdivacky      case Instruction::SIToFP:
3312202375Srdivacky      case Instruction::UIToFP:
3313202375Srdivacky        if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3314202375Srdivacky          return NV;
3315202375Srdivacky        break;
3316202375Srdivacky      case Instruction::Select: {
3317202375Srdivacky        // If either operand of the select is a constant, we can fold the
3318202375Srdivacky        // comparison into the select arms, which will cause one to be
3319202375Srdivacky        // constant folded and the select turned into a bitwise or.
3320202375Srdivacky        Value *Op1 = 0, *Op2 = 0;
3321202375Srdivacky        if (LHSI->hasOneUse()) {
3322202375Srdivacky          if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3323202375Srdivacky            // Fold the known value into the constant operand.
3324202375Srdivacky            Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3325202375Srdivacky            // Insert a new FCmp of the other select operand.
3326202375Srdivacky            Op2 = Builder->CreateFCmp(I.getPredicate(),
3327202375Srdivacky                                      LHSI->getOperand(2), RHSC, I.getName());
3328202375Srdivacky          } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3329202375Srdivacky            // Fold the known value into the constant operand.
3330202375Srdivacky            Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
3331202375Srdivacky            // Insert a new FCmp of the other select operand.
3332202375Srdivacky            Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
3333202375Srdivacky                                      RHSC, I.getName());
3334202375Srdivacky          }
3335202375Srdivacky        }
3336202375Srdivacky
3337202375Srdivacky        if (Op1)
3338202375Srdivacky          return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
3339202375Srdivacky        break;
3340202375Srdivacky      }
3341221345Sdim      case Instruction::FSub: {
3342221345Sdim        // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3343221345Sdim        Value *Op;
3344221345Sdim        if (match(LHSI, m_FNeg(m_Value(Op))))
3345221345Sdim          return new FCmpInst(I.getSwappedPredicate(), Op,
3346221345Sdim                              ConstantExpr::getFNeg(RHSC));
3347221345Sdim        break;
3348221345Sdim      }
3349204642Srdivacky      case Instruction::Load:
3350204642Srdivacky        if (GetElementPtrInst *GEP =
3351204642Srdivacky            dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3352204642Srdivacky          if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3353204642Srdivacky            if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3354204642Srdivacky                !cast<LoadInst>(LHSI)->isVolatile())
3355204642Srdivacky              if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3356204642Srdivacky                return Res;
3357204642Srdivacky        }
3358204642Srdivacky        break;
3359245431Sdim      case Instruction::Call: {
3360245431Sdim        CallInst *CI = cast<CallInst>(LHSI);
3361245431Sdim        LibFunc::Func Func;
3362245431Sdim        // Various optimization for fabs compared with zero.
3363245431Sdim        if (RHSC->isNullValue() && CI->getCalledFunction() &&
3364245431Sdim            TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3365245431Sdim            TLI->has(Func)) {
3366245431Sdim          if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3367245431Sdim              Func == LibFunc::fabsl) {
3368245431Sdim            switch (I.getPredicate()) {
3369245431Sdim            default: break;
3370245431Sdim            // fabs(x) < 0 --> false
3371245431Sdim            case FCmpInst::FCMP_OLT:
3372245431Sdim              return ReplaceInstUsesWith(I, Builder->getFalse());
3373245431Sdim            // fabs(x) > 0 --> x != 0
3374245431Sdim            case FCmpInst::FCMP_OGT:
3375245431Sdim              return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3376245431Sdim                                  RHSC);
3377245431Sdim            // fabs(x) <= 0 --> x == 0
3378245431Sdim            case FCmpInst::FCMP_OLE:
3379245431Sdim              return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3380245431Sdim                                  RHSC);
3381245431Sdim            // fabs(x) >= 0 --> !isnan(x)
3382245431Sdim            case FCmpInst::FCMP_OGE:
3383245431Sdim              return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3384245431Sdim                                  RHSC);
3385245431Sdim            // fabs(x) == 0 --> x == 0
3386245431Sdim            // fabs(x) != 0 --> x != 0
3387245431Sdim            case FCmpInst::FCMP_OEQ:
3388245431Sdim            case FCmpInst::FCMP_UEQ:
3389245431Sdim            case FCmpInst::FCMP_ONE:
3390245431Sdim            case FCmpInst::FCMP_UNE:
3391245431Sdim              return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3392245431Sdim                                  RHSC);
3393245431Sdim            }
3394245431Sdim          }
3395245431Sdim        }
3396202375Srdivacky      }
3397245431Sdim      }
3398202375Srdivacky  }
3399202375Srdivacky
3400221345Sdim  // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
3401221345Sdim  Value *X, *Y;
3402221345Sdim  if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
3403221345Sdim    return new FCmpInst(I.getSwappedPredicate(), X, Y);
3404221345Sdim
3405221345Sdim  // fcmp (fpext x), (fpext y) -> fcmp x, y
3406221345Sdim  if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3407221345Sdim    if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3408221345Sdim      if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3409221345Sdim        return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3410221345Sdim                            RHSExt->getOperand(0));
3411221345Sdim
3412202375Srdivacky  return Changed ? &I : 0;
3413202375Srdivacky}
3414