InstCombineCompares.cpp revision 36b56886974eae4f9c5ebc96befd3e7bfe5de338
1//===- InstCombineCompares.cpp --------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitICmp and visitFCmp functions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
15#include "llvm/Analysis/ConstantFolding.h"
16#include "llvm/Analysis/InstructionSimplify.h"
17#include "llvm/Analysis/MemoryBuiltins.h"
18#include "llvm/IR/ConstantRange.h"
19#include "llvm/IR/DataLayout.h"
20#include "llvm/IR/GetElementPtrTypeIterator.h"
21#include "llvm/IR/IntrinsicInst.h"
22#include "llvm/IR/PatternMatch.h"
23#include "llvm/Target/TargetLibraryInfo.h"
24using namespace llvm;
25using namespace PatternMatch;
26
27static ConstantInt *getOne(Constant *C) {
28  return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
29}
30
31static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
32  return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
33}
34
35static bool HasAddOverflow(ConstantInt *Result,
36                           ConstantInt *In1, ConstantInt *In2,
37                           bool IsSigned) {
38  if (!IsSigned)
39    return Result->getValue().ult(In1->getValue());
40
41  if (In2->isNegative())
42    return Result->getValue().sgt(In1->getValue());
43  return Result->getValue().slt(In1->getValue());
44}
45
46/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
47/// overflowed for this type.
48static bool AddWithOverflow(Constant *&Result, Constant *In1,
49                            Constant *In2, bool IsSigned = false) {
50  Result = ConstantExpr::getAdd(In1, In2);
51
52  if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
53    for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
54      Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
55      if (HasAddOverflow(ExtractElement(Result, Idx),
56                         ExtractElement(In1, Idx),
57                         ExtractElement(In2, Idx),
58                         IsSigned))
59        return true;
60    }
61    return false;
62  }
63
64  return HasAddOverflow(cast<ConstantInt>(Result),
65                        cast<ConstantInt>(In1), cast<ConstantInt>(In2),
66                        IsSigned);
67}
68
69static bool HasSubOverflow(ConstantInt *Result,
70                           ConstantInt *In1, ConstantInt *In2,
71                           bool IsSigned) {
72  if (!IsSigned)
73    return Result->getValue().ugt(In1->getValue());
74
75  if (In2->isNegative())
76    return Result->getValue().slt(In1->getValue());
77
78  return Result->getValue().sgt(In1->getValue());
79}
80
81/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
82/// overflowed for this type.
83static bool SubWithOverflow(Constant *&Result, Constant *In1,
84                            Constant *In2, bool IsSigned = false) {
85  Result = ConstantExpr::getSub(In1, In2);
86
87  if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
88    for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
89      Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
90      if (HasSubOverflow(ExtractElement(Result, Idx),
91                         ExtractElement(In1, Idx),
92                         ExtractElement(In2, Idx),
93                         IsSigned))
94        return true;
95    }
96    return false;
97  }
98
99  return HasSubOverflow(cast<ConstantInt>(Result),
100                        cast<ConstantInt>(In1), cast<ConstantInt>(In2),
101                        IsSigned);
102}
103
104/// isSignBitCheck - Given an exploded icmp instruction, return true if the
105/// comparison only checks the sign bit.  If it only checks the sign bit, set
106/// TrueIfSigned if the result of the comparison is true when the input value is
107/// signed.
108static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
109                           bool &TrueIfSigned) {
110  switch (pred) {
111  case ICmpInst::ICMP_SLT:   // True if LHS s< 0
112    TrueIfSigned = true;
113    return RHS->isZero();
114  case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
115    TrueIfSigned = true;
116    return RHS->isAllOnesValue();
117  case ICmpInst::ICMP_SGT:   // True if LHS s> -1
118    TrueIfSigned = false;
119    return RHS->isAllOnesValue();
120  case ICmpInst::ICMP_UGT:
121    // True if LHS u> RHS and RHS == high-bit-mask - 1
122    TrueIfSigned = true;
123    return RHS->isMaxValue(true);
124  case ICmpInst::ICMP_UGE:
125    // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
126    TrueIfSigned = true;
127    return RHS->getValue().isSignBit();
128  default:
129    return false;
130  }
131}
132
133/// Returns true if the exploded icmp can be expressed as a signed comparison
134/// to zero and updates the predicate accordingly.
135/// The signedness of the comparison is preserved.
136static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
137  if (!ICmpInst::isSigned(pred))
138    return false;
139
140  if (RHS->isZero())
141    return ICmpInst::isRelational(pred);
142
143  if (RHS->isOne()) {
144    if (pred == ICmpInst::ICMP_SLT) {
145      pred = ICmpInst::ICMP_SLE;
146      return true;
147    }
148  } else if (RHS->isAllOnesValue()) {
149    if (pred == ICmpInst::ICMP_SGT) {
150      pred = ICmpInst::ICMP_SGE;
151      return true;
152    }
153  }
154
155  return false;
156}
157
158// isHighOnes - Return true if the constant is of the form 1+0+.
159// This is the same as lowones(~X).
160static bool isHighOnes(const ConstantInt *CI) {
161  return (~CI->getValue() + 1).isPowerOf2();
162}
163
164/// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
165/// set of known zero and one bits, compute the maximum and minimum values that
166/// could have the specified known zero and known one bits, returning them in
167/// min/max.
168static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
169                                                   const APInt& KnownOne,
170                                                   APInt& Min, APInt& Max) {
171  assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
172         KnownZero.getBitWidth() == Min.getBitWidth() &&
173         KnownZero.getBitWidth() == Max.getBitWidth() &&
174         "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
175  APInt UnknownBits = ~(KnownZero|KnownOne);
176
177  // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
178  // bit if it is unknown.
179  Min = KnownOne;
180  Max = KnownOne|UnknownBits;
181
182  if (UnknownBits.isNegative()) { // Sign bit is unknown
183    Min.setBit(Min.getBitWidth()-1);
184    Max.clearBit(Max.getBitWidth()-1);
185  }
186}
187
188// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
189// a set of known zero and one bits, compute the maximum and minimum values that
190// could have the specified known zero and known one bits, returning them in
191// min/max.
192static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
193                                                     const APInt &KnownOne,
194                                                     APInt &Min, APInt &Max) {
195  assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
196         KnownZero.getBitWidth() == Min.getBitWidth() &&
197         KnownZero.getBitWidth() == Max.getBitWidth() &&
198         "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
199  APInt UnknownBits = ~(KnownZero|KnownOne);
200
201  // The minimum value is when the unknown bits are all zeros.
202  Min = KnownOne;
203  // The maximum value is when the unknown bits are all ones.
204  Max = KnownOne|UnknownBits;
205}
206
207
208
209/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
210///   cmp pred (load (gep GV, ...)), cmpcst
211/// where GV is a global variable with a constant initializer.  Try to simplify
212/// this into some simple computation that does not need the load.  For example
213/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
214///
215/// If AndCst is non-null, then the loaded value is masked with that constant
216/// before doing the comparison.  This handles cases like "A[i]&4 == 0".
217Instruction *InstCombiner::
218FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
219                             CmpInst &ICI, ConstantInt *AndCst) {
220  // We need TD information to know the pointer size unless this is inbounds.
221  if (!GEP->isInBounds() && DL == 0)
222    return 0;
223
224  Constant *Init = GV->getInitializer();
225  if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
226    return 0;
227
228  uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
229  if (ArrayElementCount > 1024) return 0;  // Don't blow up on huge arrays.
230
231  // There are many forms of this optimization we can handle, for now, just do
232  // the simple index into a single-dimensional array.
233  //
234  // Require: GEP GV, 0, i {{, constant indices}}
235  if (GEP->getNumOperands() < 3 ||
236      !isa<ConstantInt>(GEP->getOperand(1)) ||
237      !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
238      isa<Constant>(GEP->getOperand(2)))
239    return 0;
240
241  // Check that indices after the variable are constants and in-range for the
242  // type they index.  Collect the indices.  This is typically for arrays of
243  // structs.
244  SmallVector<unsigned, 4> LaterIndices;
245
246  Type *EltTy = Init->getType()->getArrayElementType();
247  for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
248    ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
249    if (Idx == 0) return 0;  // Variable index.
250
251    uint64_t IdxVal = Idx->getZExtValue();
252    if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
253
254    if (StructType *STy = dyn_cast<StructType>(EltTy))
255      EltTy = STy->getElementType(IdxVal);
256    else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
257      if (IdxVal >= ATy->getNumElements()) return 0;
258      EltTy = ATy->getElementType();
259    } else {
260      return 0; // Unknown type.
261    }
262
263    LaterIndices.push_back(IdxVal);
264  }
265
266  enum { Overdefined = -3, Undefined = -2 };
267
268  // Variables for our state machines.
269
270  // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
271  // "i == 47 | i == 87", where 47 is the first index the condition is true for,
272  // and 87 is the second (and last) index.  FirstTrueElement is -2 when
273  // undefined, otherwise set to the first true element.  SecondTrueElement is
274  // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
275  int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
276
277  // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
278  // form "i != 47 & i != 87".  Same state transitions as for true elements.
279  int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
280
281  /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
282  /// define a state machine that triggers for ranges of values that the index
283  /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
284  /// This is -2 when undefined, -3 when overdefined, and otherwise the last
285  /// index in the range (inclusive).  We use -2 for undefined here because we
286  /// use relative comparisons and don't want 0-1 to match -1.
287  int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
288
289  // MagicBitvector - This is a magic bitvector where we set a bit if the
290  // comparison is true for element 'i'.  If there are 64 elements or less in
291  // the array, this will fully represent all the comparison results.
292  uint64_t MagicBitvector = 0;
293
294
295  // Scan the array and see if one of our patterns matches.
296  Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
297  for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
298    Constant *Elt = Init->getAggregateElement(i);
299    if (Elt == 0) return 0;
300
301    // If this is indexing an array of structures, get the structure element.
302    if (!LaterIndices.empty())
303      Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
304
305    // If the element is masked, handle it.
306    if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
307
308    // Find out if the comparison would be true or false for the i'th element.
309    Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
310                                                  CompareRHS, DL, TLI);
311    // If the result is undef for this element, ignore it.
312    if (isa<UndefValue>(C)) {
313      // Extend range state machines to cover this element in case there is an
314      // undef in the middle of the range.
315      if (TrueRangeEnd == (int)i-1)
316        TrueRangeEnd = i;
317      if (FalseRangeEnd == (int)i-1)
318        FalseRangeEnd = i;
319      continue;
320    }
321
322    // If we can't compute the result for any of the elements, we have to give
323    // up evaluating the entire conditional.
324    if (!isa<ConstantInt>(C)) return 0;
325
326    // Otherwise, we know if the comparison is true or false for this element,
327    // update our state machines.
328    bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
329
330    // State machine for single/double/range index comparison.
331    if (IsTrueForElt) {
332      // Update the TrueElement state machine.
333      if (FirstTrueElement == Undefined)
334        FirstTrueElement = TrueRangeEnd = i;  // First true element.
335      else {
336        // Update double-compare state machine.
337        if (SecondTrueElement == Undefined)
338          SecondTrueElement = i;
339        else
340          SecondTrueElement = Overdefined;
341
342        // Update range state machine.
343        if (TrueRangeEnd == (int)i-1)
344          TrueRangeEnd = i;
345        else
346          TrueRangeEnd = Overdefined;
347      }
348    } else {
349      // Update the FalseElement state machine.
350      if (FirstFalseElement == Undefined)
351        FirstFalseElement = FalseRangeEnd = i; // First false element.
352      else {
353        // Update double-compare state machine.
354        if (SecondFalseElement == Undefined)
355          SecondFalseElement = i;
356        else
357          SecondFalseElement = Overdefined;
358
359        // Update range state machine.
360        if (FalseRangeEnd == (int)i-1)
361          FalseRangeEnd = i;
362        else
363          FalseRangeEnd = Overdefined;
364      }
365    }
366
367
368    // If this element is in range, update our magic bitvector.
369    if (i < 64 && IsTrueForElt)
370      MagicBitvector |= 1ULL << i;
371
372    // If all of our states become overdefined, bail out early.  Since the
373    // predicate is expensive, only check it every 8 elements.  This is only
374    // really useful for really huge arrays.
375    if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
376        SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
377        FalseRangeEnd == Overdefined)
378      return 0;
379  }
380
381  // Now that we've scanned the entire array, emit our new comparison(s).  We
382  // order the state machines in complexity of the generated code.
383  Value *Idx = GEP->getOperand(2);
384
385  // If the index is larger than the pointer size of the target, truncate the
386  // index down like the GEP would do implicitly.  We don't have to do this for
387  // an inbounds GEP because the index can't be out of range.
388  if (!GEP->isInBounds()) {
389    Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
390    unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
391    if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
392      Idx = Builder->CreateTrunc(Idx, IntPtrTy);
393  }
394
395  // If the comparison is only true for one or two elements, emit direct
396  // comparisons.
397  if (SecondTrueElement != Overdefined) {
398    // None true -> false.
399    if (FirstTrueElement == Undefined)
400      return ReplaceInstUsesWith(ICI, Builder->getFalse());
401
402    Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
403
404    // True for one element -> 'i == 47'.
405    if (SecondTrueElement == Undefined)
406      return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
407
408    // True for two elements -> 'i == 47 | i == 72'.
409    Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
410    Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
411    Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
412    return BinaryOperator::CreateOr(C1, C2);
413  }
414
415  // If the comparison is only false for one or two elements, emit direct
416  // comparisons.
417  if (SecondFalseElement != Overdefined) {
418    // None false -> true.
419    if (FirstFalseElement == Undefined)
420      return ReplaceInstUsesWith(ICI, Builder->getTrue());
421
422    Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
423
424    // False for one element -> 'i != 47'.
425    if (SecondFalseElement == Undefined)
426      return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
427
428    // False for two elements -> 'i != 47 & i != 72'.
429    Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
430    Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
431    Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
432    return BinaryOperator::CreateAnd(C1, C2);
433  }
434
435  // If the comparison can be replaced with a range comparison for the elements
436  // where it is true, emit the range check.
437  if (TrueRangeEnd != Overdefined) {
438    assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
439
440    // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
441    if (FirstTrueElement) {
442      Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
443      Idx = Builder->CreateAdd(Idx, Offs);
444    }
445
446    Value *End = ConstantInt::get(Idx->getType(),
447                                  TrueRangeEnd-FirstTrueElement+1);
448    return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
449  }
450
451  // False range check.
452  if (FalseRangeEnd != Overdefined) {
453    assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
454    // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
455    if (FirstFalseElement) {
456      Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
457      Idx = Builder->CreateAdd(Idx, Offs);
458    }
459
460    Value *End = ConstantInt::get(Idx->getType(),
461                                  FalseRangeEnd-FirstFalseElement);
462    return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
463  }
464
465
466  // If a magic bitvector captures the entire comparison state
467  // of this load, replace it with computation that does:
468  //   ((magic_cst >> i) & 1) != 0
469  {
470    Type *Ty = 0;
471
472    // Look for an appropriate type:
473    // - The type of Idx if the magic fits
474    // - The smallest fitting legal type if we have a DataLayout
475    // - Default to i32
476    if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
477      Ty = Idx->getType();
478    else if (DL)
479      Ty = DL->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
480    else if (ArrayElementCount <= 32)
481      Ty = Type::getInt32Ty(Init->getContext());
482
483    if (Ty != 0) {
484      Value *V = Builder->CreateIntCast(Idx, Ty, false);
485      V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
486      V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
487      return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
488    }
489  }
490
491  return 0;
492}
493
494
495/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
496/// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
497/// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
498/// be complex, and scales are involved.  The above expression would also be
499/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
500/// This later form is less amenable to optimization though, and we are allowed
501/// to generate the first by knowing that pointer arithmetic doesn't overflow.
502///
503/// If we can't emit an optimized form for this expression, this returns null.
504///
505static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
506  const DataLayout &DL = *IC.getDataLayout();
507  gep_type_iterator GTI = gep_type_begin(GEP);
508
509  // Check to see if this gep only has a single variable index.  If so, and if
510  // any constant indices are a multiple of its scale, then we can compute this
511  // in terms of the scale of the variable index.  For example, if the GEP
512  // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
513  // because the expression will cross zero at the same point.
514  unsigned i, e = GEP->getNumOperands();
515  int64_t Offset = 0;
516  for (i = 1; i != e; ++i, ++GTI) {
517    if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
518      // Compute the aggregate offset of constant indices.
519      if (CI->isZero()) continue;
520
521      // Handle a struct index, which adds its field offset to the pointer.
522      if (StructType *STy = dyn_cast<StructType>(*GTI)) {
523        Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
524      } else {
525        uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
526        Offset += Size*CI->getSExtValue();
527      }
528    } else {
529      // Found our variable index.
530      break;
531    }
532  }
533
534  // If there are no variable indices, we must have a constant offset, just
535  // evaluate it the general way.
536  if (i == e) return 0;
537
538  Value *VariableIdx = GEP->getOperand(i);
539  // Determine the scale factor of the variable element.  For example, this is
540  // 4 if the variable index is into an array of i32.
541  uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
542
543  // Verify that there are no other variable indices.  If so, emit the hard way.
544  for (++i, ++GTI; i != e; ++i, ++GTI) {
545    ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
546    if (!CI) return 0;
547
548    // Compute the aggregate offset of constant indices.
549    if (CI->isZero()) continue;
550
551    // Handle a struct index, which adds its field offset to the pointer.
552    if (StructType *STy = dyn_cast<StructType>(*GTI)) {
553      Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
554    } else {
555      uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
556      Offset += Size*CI->getSExtValue();
557    }
558  }
559
560
561
562  // Okay, we know we have a single variable index, which must be a
563  // pointer/array/vector index.  If there is no offset, life is simple, return
564  // the index.
565  Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
566  unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
567  if (Offset == 0) {
568    // Cast to intptrty in case a truncation occurs.  If an extension is needed,
569    // we don't need to bother extending: the extension won't affect where the
570    // computation crosses zero.
571    if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
572      VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
573    }
574    return VariableIdx;
575  }
576
577  // Otherwise, there is an index.  The computation we will do will be modulo
578  // the pointer size, so get it.
579  uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
580
581  Offset &= PtrSizeMask;
582  VariableScale &= PtrSizeMask;
583
584  // To do this transformation, any constant index must be a multiple of the
585  // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
586  // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
587  // multiple of the variable scale.
588  int64_t NewOffs = Offset / (int64_t)VariableScale;
589  if (Offset != NewOffs*(int64_t)VariableScale)
590    return 0;
591
592  // Okay, we can do this evaluation.  Start by converting the index to intptr.
593  if (VariableIdx->getType() != IntPtrTy)
594    VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
595                                            true /*Signed*/);
596  Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
597  return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
598}
599
600/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
601/// else.  At this point we know that the GEP is on the LHS of the comparison.
602Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
603                                       ICmpInst::Predicate Cond,
604                                       Instruction &I) {
605  // Don't transform signed compares of GEPs into index compares. Even if the
606  // GEP is inbounds, the final add of the base pointer can have signed overflow
607  // and would change the result of the icmp.
608  // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
609  // the maximum signed value for the pointer type.
610  if (ICmpInst::isSigned(Cond))
611    return 0;
612
613  // Look through bitcasts.
614  if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
615    RHS = BCI->getOperand(0);
616
617  Value *PtrBase = GEPLHS->getOperand(0);
618  if (DL && PtrBase == RHS && GEPLHS->isInBounds()) {
619    // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
620    // This transformation (ignoring the base and scales) is valid because we
621    // know pointers can't overflow since the gep is inbounds.  See if we can
622    // output an optimized form.
623    Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
624
625    // If not, synthesize the offset the hard way.
626    if (Offset == 0)
627      Offset = EmitGEPOffset(GEPLHS);
628    return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
629                        Constant::getNullValue(Offset->getType()));
630  } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
631    // If the base pointers are different, but the indices are the same, just
632    // compare the base pointer.
633    if (PtrBase != GEPRHS->getOperand(0)) {
634      bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
635      IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
636                        GEPRHS->getOperand(0)->getType();
637      if (IndicesTheSame)
638        for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
639          if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
640            IndicesTheSame = false;
641            break;
642          }
643
644      // If all indices are the same, just compare the base pointers.
645      if (IndicesTheSame)
646        return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
647
648      // If we're comparing GEPs with two base pointers that only differ in type
649      // and both GEPs have only constant indices or just one use, then fold
650      // the compare with the adjusted indices.
651      if (DL && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
652          (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
653          (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
654          PtrBase->stripPointerCasts() ==
655            GEPRHS->getOperand(0)->stripPointerCasts()) {
656        Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
657                                         EmitGEPOffset(GEPLHS),
658                                         EmitGEPOffset(GEPRHS));
659        return ReplaceInstUsesWith(I, Cmp);
660      }
661
662      // Otherwise, the base pointers are different and the indices are
663      // different, bail out.
664      return 0;
665    }
666
667    // If one of the GEPs has all zero indices, recurse.
668    bool AllZeros = true;
669    for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
670      if (!isa<Constant>(GEPLHS->getOperand(i)) ||
671          !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
672        AllZeros = false;
673        break;
674      }
675    if (AllZeros)
676      return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
677                         ICmpInst::getSwappedPredicate(Cond), I);
678
679    // If the other GEP has all zero indices, recurse.
680    AllZeros = true;
681    for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
682      if (!isa<Constant>(GEPRHS->getOperand(i)) ||
683          !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
684        AllZeros = false;
685        break;
686      }
687    if (AllZeros)
688      return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
689
690    bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
691    if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
692      // If the GEPs only differ by one index, compare it.
693      unsigned NumDifferences = 0;  // Keep track of # differences.
694      unsigned DiffOperand = 0;     // The operand that differs.
695      for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
696        if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
697          if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
698                   GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
699            // Irreconcilable differences.
700            NumDifferences = 2;
701            break;
702          } else {
703            if (NumDifferences++) break;
704            DiffOperand = i;
705          }
706        }
707
708      if (NumDifferences == 0)   // SAME GEP?
709        return ReplaceInstUsesWith(I, // No comparison is needed here.
710                             Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
711
712      else if (NumDifferences == 1 && GEPsInBounds) {
713        Value *LHSV = GEPLHS->getOperand(DiffOperand);
714        Value *RHSV = GEPRHS->getOperand(DiffOperand);
715        // Make sure we do a signed comparison here.
716        return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
717      }
718    }
719
720    // Only lower this if the icmp is the only user of the GEP or if we expect
721    // the result to fold to a constant!
722    if (DL &&
723        GEPsInBounds &&
724        (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
725        (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
726      // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
727      Value *L = EmitGEPOffset(GEPLHS);
728      Value *R = EmitGEPOffset(GEPRHS);
729      return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
730    }
731  }
732  return 0;
733}
734
735/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
736Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
737                                            Value *X, ConstantInt *CI,
738                                            ICmpInst::Predicate Pred) {
739  // If we have X+0, exit early (simplifying logic below) and let it get folded
740  // elsewhere.   icmp X+0, X  -> icmp X, X
741  if (CI->isZero()) {
742    bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
743    return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
744  }
745
746  // (X+4) == X -> false.
747  if (Pred == ICmpInst::ICMP_EQ)
748    return ReplaceInstUsesWith(ICI, Builder->getFalse());
749
750  // (X+4) != X -> true.
751  if (Pred == ICmpInst::ICMP_NE)
752    return ReplaceInstUsesWith(ICI, Builder->getTrue());
753
754  // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
755  // so the values can never be equal.  Similarly for all other "or equals"
756  // operators.
757
758  // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
759  // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
760  // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
761  if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
762    Value *R =
763      ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
764    return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
765  }
766
767  // (X+1) >u X        --> X <u (0-1)        --> X != 255
768  // (X+2) >u X        --> X <u (0-2)        --> X <u 254
769  // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
770  if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
771    return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
772
773  unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
774  ConstantInt *SMax = ConstantInt::get(X->getContext(),
775                                       APInt::getSignedMaxValue(BitWidth));
776
777  // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
778  // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
779  // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
780  // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
781  // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
782  // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
783  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
784    return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
785
786  // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
787  // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
788  // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
789  // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
790  // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
791  // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
792
793  assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
794  Constant *C = Builder->getInt(CI->getValue()-1);
795  return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
796}
797
798/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
799/// and CmpRHS are both known to be integer constants.
800Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
801                                          ConstantInt *DivRHS) {
802  ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
803  const APInt &CmpRHSV = CmpRHS->getValue();
804
805  // FIXME: If the operand types don't match the type of the divide
806  // then don't attempt this transform. The code below doesn't have the
807  // logic to deal with a signed divide and an unsigned compare (and
808  // vice versa). This is because (x /s C1) <s C2  produces different
809  // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
810  // (x /u C1) <u C2.  Simply casting the operands and result won't
811  // work. :(  The if statement below tests that condition and bails
812  // if it finds it.
813  bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
814  if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
815    return 0;
816  if (DivRHS->isZero())
817    return 0; // The ProdOV computation fails on divide by zero.
818  if (DivIsSigned && DivRHS->isAllOnesValue())
819    return 0; // The overflow computation also screws up here
820  if (DivRHS->isOne()) {
821    // This eliminates some funny cases with INT_MIN.
822    ICI.setOperand(0, DivI->getOperand(0));   // X/1 == X.
823    return &ICI;
824  }
825
826  // Compute Prod = CI * DivRHS. We are essentially solving an equation
827  // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
828  // C2 (CI). By solving for X we can turn this into a range check
829  // instead of computing a divide.
830  Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
831
832  // Determine if the product overflows by seeing if the product is
833  // not equal to the divide. Make sure we do the same kind of divide
834  // as in the LHS instruction that we're folding.
835  bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
836                 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
837
838  // Get the ICmp opcode
839  ICmpInst::Predicate Pred = ICI.getPredicate();
840
841  /// If the division is known to be exact, then there is no remainder from the
842  /// divide, so the covered range size is unit, otherwise it is the divisor.
843  ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
844
845  // Figure out the interval that is being checked.  For example, a comparison
846  // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
847  // Compute this interval based on the constants involved and the signedness of
848  // the compare/divide.  This computes a half-open interval, keeping track of
849  // whether either value in the interval overflows.  After analysis each
850  // overflow variable is set to 0 if it's corresponding bound variable is valid
851  // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
852  int LoOverflow = 0, HiOverflow = 0;
853  Constant *LoBound = 0, *HiBound = 0;
854
855  if (!DivIsSigned) {  // udiv
856    // e.g. X/5 op 3  --> [15, 20)
857    LoBound = Prod;
858    HiOverflow = LoOverflow = ProdOV;
859    if (!HiOverflow) {
860      // If this is not an exact divide, then many values in the range collapse
861      // to the same result value.
862      HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
863    }
864
865  } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
866    if (CmpRHSV == 0) {       // (X / pos) op 0
867      // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
868      LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
869      HiBound = RangeSize;
870    } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
871      LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
872      HiOverflow = LoOverflow = ProdOV;
873      if (!HiOverflow)
874        HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
875    } else {                       // (X / pos) op neg
876      // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
877      HiBound = AddOne(Prod);
878      LoOverflow = HiOverflow = ProdOV ? -1 : 0;
879      if (!LoOverflow) {
880        ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
881        LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
882      }
883    }
884  } else if (DivRHS->isNegative()) { // Divisor is < 0.
885    if (DivI->isExact())
886      RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
887    if (CmpRHSV == 0) {       // (X / neg) op 0
888      // e.g. X/-5 op 0  --> [-4, 5)
889      LoBound = AddOne(RangeSize);
890      HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
891      if (HiBound == DivRHS) {     // -INTMIN = INTMIN
892        HiOverflow = 1;            // [INTMIN+1, overflow)
893        HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
894      }
895    } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
896      // e.g. X/-5 op 3  --> [-19, -14)
897      HiBound = AddOne(Prod);
898      HiOverflow = LoOverflow = ProdOV ? -1 : 0;
899      if (!LoOverflow)
900        LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
901    } else {                       // (X / neg) op neg
902      LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
903      LoOverflow = HiOverflow = ProdOV;
904      if (!HiOverflow)
905        HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
906    }
907
908    // Dividing by a negative swaps the condition.  LT <-> GT
909    Pred = ICmpInst::getSwappedPredicate(Pred);
910  }
911
912  Value *X = DivI->getOperand(0);
913  switch (Pred) {
914  default: llvm_unreachable("Unhandled icmp opcode!");
915  case ICmpInst::ICMP_EQ:
916    if (LoOverflow && HiOverflow)
917      return ReplaceInstUsesWith(ICI, Builder->getFalse());
918    if (HiOverflow)
919      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
920                          ICmpInst::ICMP_UGE, X, LoBound);
921    if (LoOverflow)
922      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
923                          ICmpInst::ICMP_ULT, X, HiBound);
924    return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
925                                                    DivIsSigned, true));
926  case ICmpInst::ICMP_NE:
927    if (LoOverflow && HiOverflow)
928      return ReplaceInstUsesWith(ICI, Builder->getTrue());
929    if (HiOverflow)
930      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
931                          ICmpInst::ICMP_ULT, X, LoBound);
932    if (LoOverflow)
933      return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
934                          ICmpInst::ICMP_UGE, X, HiBound);
935    return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
936                                                    DivIsSigned, false));
937  case ICmpInst::ICMP_ULT:
938  case ICmpInst::ICMP_SLT:
939    if (LoOverflow == +1)   // Low bound is greater than input range.
940      return ReplaceInstUsesWith(ICI, Builder->getTrue());
941    if (LoOverflow == -1)   // Low bound is less than input range.
942      return ReplaceInstUsesWith(ICI, Builder->getFalse());
943    return new ICmpInst(Pred, X, LoBound);
944  case ICmpInst::ICMP_UGT:
945  case ICmpInst::ICMP_SGT:
946    if (HiOverflow == +1)       // High bound greater than input range.
947      return ReplaceInstUsesWith(ICI, Builder->getFalse());
948    if (HiOverflow == -1)       // High bound less than input range.
949      return ReplaceInstUsesWith(ICI, Builder->getTrue());
950    if (Pred == ICmpInst::ICMP_UGT)
951      return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
952    return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
953  }
954}
955
956/// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
957Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
958                                          ConstantInt *ShAmt) {
959  const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
960
961  // Check that the shift amount is in range.  If not, don't perform
962  // undefined shifts.  When the shift is visited it will be
963  // simplified.
964  uint32_t TypeBits = CmpRHSV.getBitWidth();
965  uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
966  if (ShAmtVal >= TypeBits || ShAmtVal == 0)
967    return 0;
968
969  if (!ICI.isEquality()) {
970    // If we have an unsigned comparison and an ashr, we can't simplify this.
971    // Similarly for signed comparisons with lshr.
972    if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
973      return 0;
974
975    // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
976    // by a power of 2.  Since we already have logic to simplify these,
977    // transform to div and then simplify the resultant comparison.
978    if (Shr->getOpcode() == Instruction::AShr &&
979        (!Shr->isExact() || ShAmtVal == TypeBits - 1))
980      return 0;
981
982    // Revisit the shift (to delete it).
983    Worklist.Add(Shr);
984
985    Constant *DivCst =
986      ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
987
988    Value *Tmp =
989      Shr->getOpcode() == Instruction::AShr ?
990      Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
991      Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
992
993    ICI.setOperand(0, Tmp);
994
995    // If the builder folded the binop, just return it.
996    BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
997    if (TheDiv == 0)
998      return &ICI;
999
1000    // Otherwise, fold this div/compare.
1001    assert(TheDiv->getOpcode() == Instruction::SDiv ||
1002           TheDiv->getOpcode() == Instruction::UDiv);
1003
1004    Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
1005    assert(Res && "This div/cst should have folded!");
1006    return Res;
1007  }
1008
1009
1010  // If we are comparing against bits always shifted out, the
1011  // comparison cannot succeed.
1012  APInt Comp = CmpRHSV << ShAmtVal;
1013  ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
1014  if (Shr->getOpcode() == Instruction::LShr)
1015    Comp = Comp.lshr(ShAmtVal);
1016  else
1017    Comp = Comp.ashr(ShAmtVal);
1018
1019  if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
1020    bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1021    Constant *Cst = Builder->getInt1(IsICMP_NE);
1022    return ReplaceInstUsesWith(ICI, Cst);
1023  }
1024
1025  // Otherwise, check to see if the bits shifted out are known to be zero.
1026  // If so, we can compare against the unshifted value:
1027  //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
1028  if (Shr->hasOneUse() && Shr->isExact())
1029    return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
1030
1031  if (Shr->hasOneUse()) {
1032    // Otherwise strength reduce the shift into an and.
1033    APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
1034    Constant *Mask = Builder->getInt(Val);
1035
1036    Value *And = Builder->CreateAnd(Shr->getOperand(0),
1037                                    Mask, Shr->getName()+".mask");
1038    return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
1039  }
1040  return 0;
1041}
1042
1043
1044/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
1045///
1046Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
1047                                                          Instruction *LHSI,
1048                                                          ConstantInt *RHS) {
1049  const APInt &RHSV = RHS->getValue();
1050
1051  switch (LHSI->getOpcode()) {
1052  case Instruction::Trunc:
1053    if (ICI.isEquality() && LHSI->hasOneUse()) {
1054      // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1055      // of the high bits truncated out of x are known.
1056      unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
1057             SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
1058      APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
1059      ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
1060
1061      // If all the high bits are known, we can do this xform.
1062      if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
1063        // Pull in the high bits from known-ones set.
1064        APInt NewRHS = RHS->getValue().zext(SrcBits);
1065        NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
1066        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1067                            Builder->getInt(NewRHS));
1068      }
1069    }
1070    break;
1071
1072  case Instruction::Xor:         // (icmp pred (xor X, XorCst), CI)
1073    if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1074      // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1075      // fold the xor.
1076      if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
1077          (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
1078        Value *CompareVal = LHSI->getOperand(0);
1079
1080        // If the sign bit of the XorCst is not set, there is no change to
1081        // the operation, just stop using the Xor.
1082        if (!XorCst->isNegative()) {
1083          ICI.setOperand(0, CompareVal);
1084          Worklist.Add(LHSI);
1085          return &ICI;
1086        }
1087
1088        // Was the old condition true if the operand is positive?
1089        bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
1090
1091        // If so, the new one isn't.
1092        isTrueIfPositive ^= true;
1093
1094        if (isTrueIfPositive)
1095          return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
1096                              SubOne(RHS));
1097        else
1098          return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
1099                              AddOne(RHS));
1100      }
1101
1102      if (LHSI->hasOneUse()) {
1103        // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
1104        if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
1105          const APInt &SignBit = XorCst->getValue();
1106          ICmpInst::Predicate Pred = ICI.isSigned()
1107                                         ? ICI.getUnsignedPredicate()
1108                                         : ICI.getSignedPredicate();
1109          return new ICmpInst(Pred, LHSI->getOperand(0),
1110                              Builder->getInt(RHSV ^ SignBit));
1111        }
1112
1113        // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
1114        if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
1115          const APInt &NotSignBit = XorCst->getValue();
1116          ICmpInst::Predicate Pred = ICI.isSigned()
1117                                         ? ICI.getUnsignedPredicate()
1118                                         : ICI.getSignedPredicate();
1119          Pred = ICI.getSwappedPredicate(Pred);
1120          return new ICmpInst(Pred, LHSI->getOperand(0),
1121                              Builder->getInt(RHSV ^ NotSignBit));
1122        }
1123      }
1124
1125      // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
1126      //   iff -C is a power of 2
1127      if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
1128          XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
1129        return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
1130
1131      // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
1132      //   iff -C is a power of 2
1133      if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
1134          XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
1135        return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
1136    }
1137    break;
1138  case Instruction::And:         // (icmp pred (and X, AndCst), RHS)
1139    if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1140        LHSI->getOperand(0)->hasOneUse()) {
1141      ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
1142
1143      // If the LHS is an AND of a truncating cast, we can widen the
1144      // and/compare to be the input width without changing the value
1145      // produced, eliminating a cast.
1146      if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
1147        // We can do this transformation if either the AND constant does not
1148        // have its sign bit set or if it is an equality comparison.
1149        // Extending a relational comparison when we're checking the sign
1150        // bit would not work.
1151        if (ICI.isEquality() ||
1152            (!AndCst->isNegative() && RHSV.isNonNegative())) {
1153          Value *NewAnd =
1154            Builder->CreateAnd(Cast->getOperand(0),
1155                               ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
1156          NewAnd->takeName(LHSI);
1157          return new ICmpInst(ICI.getPredicate(), NewAnd,
1158                              ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
1159        }
1160      }
1161
1162      // If the LHS is an AND of a zext, and we have an equality compare, we can
1163      // shrink the and/compare to the smaller type, eliminating the cast.
1164      if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
1165        IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
1166        // Make sure we don't compare the upper bits, SimplifyDemandedBits
1167        // should fold the icmp to true/false in that case.
1168        if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
1169          Value *NewAnd =
1170            Builder->CreateAnd(Cast->getOperand(0),
1171                               ConstantExpr::getTrunc(AndCst, Ty));
1172          NewAnd->takeName(LHSI);
1173          return new ICmpInst(ICI.getPredicate(), NewAnd,
1174                              ConstantExpr::getTrunc(RHS, Ty));
1175        }
1176      }
1177
1178      // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1179      // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1180      // happens a LOT in code produced by the C front-end, for bitfield
1181      // access.
1182      BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
1183      if (Shift && !Shift->isShift())
1184        Shift = 0;
1185
1186      ConstantInt *ShAmt;
1187      ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
1188
1189      // This seemingly simple opportunity to fold away a shift turns out to
1190      // be rather complicated. See PR17827
1191      // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
1192      if (ShAmt) {
1193        bool CanFold = false;
1194        unsigned ShiftOpcode = Shift->getOpcode();
1195        if (ShiftOpcode == Instruction::AShr) {
1196          // There may be some constraints that make this possible,
1197          // but nothing simple has been discovered yet.
1198          CanFold = false;
1199        } else if (ShiftOpcode == Instruction::Shl) {
1200          // For a left shift, we can fold if the comparison is not signed.
1201          // We can also fold a signed comparison if the mask value and
1202          // comparison value are not negative. These constraints may not be
1203          // obvious, but we can prove that they are correct using an SMT
1204          // solver.
1205          if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
1206            CanFold = true;
1207        } else if (ShiftOpcode == Instruction::LShr) {
1208          // For a logical right shift, we can fold if the comparison is not
1209          // signed. We can also fold a signed comparison if the shifted mask
1210          // value and the shifted comparison value are not negative.
1211          // These constraints may not be obvious, but we can prove that they
1212          // are correct using an SMT solver.
1213          if (!ICI.isSigned())
1214            CanFold = true;
1215          else {
1216            ConstantInt *ShiftedAndCst =
1217              cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
1218            ConstantInt *ShiftedRHSCst =
1219              cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
1220
1221            if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
1222              CanFold = true;
1223          }
1224        }
1225
1226        if (CanFold) {
1227          Constant *NewCst;
1228          if (ShiftOpcode == Instruction::Shl)
1229            NewCst = ConstantExpr::getLShr(RHS, ShAmt);
1230          else
1231            NewCst = ConstantExpr::getShl(RHS, ShAmt);
1232
1233          // Check to see if we are shifting out any of the bits being
1234          // compared.
1235          if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
1236            // If we shifted bits out, the fold is not going to work out.
1237            // As a special case, check to see if this means that the
1238            // result is always true or false now.
1239            if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1240              return ReplaceInstUsesWith(ICI, Builder->getFalse());
1241            if (ICI.getPredicate() == ICmpInst::ICMP_NE)
1242              return ReplaceInstUsesWith(ICI, Builder->getTrue());
1243          } else {
1244            ICI.setOperand(1, NewCst);
1245            Constant *NewAndCst;
1246            if (ShiftOpcode == Instruction::Shl)
1247              NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
1248            else
1249              NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
1250            LHSI->setOperand(1, NewAndCst);
1251            LHSI->setOperand(0, Shift->getOperand(0));
1252            Worklist.Add(Shift); // Shift is dead.
1253            return &ICI;
1254          }
1255        }
1256      }
1257
1258      // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
1259      // preferable because it allows the C<<Y expression to be hoisted out
1260      // of a loop if Y is invariant and X is not.
1261      if (Shift && Shift->hasOneUse() && RHSV == 0 &&
1262          ICI.isEquality() && !Shift->isArithmeticShift() &&
1263          !isa<Constant>(Shift->getOperand(0))) {
1264        // Compute C << Y.
1265        Value *NS;
1266        if (Shift->getOpcode() == Instruction::LShr) {
1267          NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
1268        } else {
1269          // Insert a logical shift.
1270          NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
1271        }
1272
1273        // Compute X & (C << Y).
1274        Value *NewAnd =
1275          Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
1276
1277        ICI.setOperand(0, NewAnd);
1278        return &ICI;
1279      }
1280
1281      // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
1282      // bit set in (X & AndCst) will produce a result greater than RHSV.
1283      if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
1284        unsigned NTZ = AndCst->getValue().countTrailingZeros();
1285        if ((NTZ < AndCst->getBitWidth()) &&
1286            APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
1287          return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
1288                              Constant::getNullValue(RHS->getType()));
1289      }
1290    }
1291
1292    // Try to optimize things like "A[i]&42 == 0" to index computations.
1293    if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
1294      if (GetElementPtrInst *GEP =
1295          dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1296        if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1297          if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
1298              !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
1299            ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
1300            if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
1301              return Res;
1302          }
1303    }
1304
1305    // X & -C == -C -> X >  u ~C
1306    // X & -C != -C -> X <= u ~C
1307    //   iff C is a power of 2
1308    if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
1309      return new ICmpInst(
1310          ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
1311                                                  : ICmpInst::ICMP_ULE,
1312          LHSI->getOperand(0), SubOne(RHS));
1313    break;
1314
1315  case Instruction::Or: {
1316    if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
1317      break;
1318    Value *P, *Q;
1319    if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1320      // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1321      // -> and (icmp eq P, null), (icmp eq Q, null).
1322      Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
1323                                        Constant::getNullValue(P->getType()));
1324      Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
1325                                        Constant::getNullValue(Q->getType()));
1326      Instruction *Op;
1327      if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
1328        Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
1329      else
1330        Op = BinaryOperator::CreateOr(ICIP, ICIQ);
1331      return Op;
1332    }
1333    break;
1334  }
1335
1336  case Instruction::Mul: {       // (icmp pred (mul X, Val), CI)
1337    ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1338    if (!Val) break;
1339
1340    // If this is a signed comparison to 0 and the mul is sign preserving,
1341    // use the mul LHS operand instead.
1342    ICmpInst::Predicate pred = ICI.getPredicate();
1343    if (isSignTest(pred, RHS) && !Val->isZero() &&
1344        cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1345      return new ICmpInst(Val->isNegative() ?
1346                          ICmpInst::getSwappedPredicate(pred) : pred,
1347                          LHSI->getOperand(0),
1348                          Constant::getNullValue(RHS->getType()));
1349
1350    break;
1351  }
1352
1353  case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
1354    uint32_t TypeBits = RHSV.getBitWidth();
1355    ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1356    if (!ShAmt) {
1357      Value *X;
1358      // (1 << X) pred P2 -> X pred Log2(P2)
1359      if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
1360        bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
1361        ICmpInst::Predicate Pred = ICI.getPredicate();
1362        if (ICI.isUnsigned()) {
1363          if (!RHSVIsPowerOf2) {
1364            // (1 << X) <  30 -> X <= 4
1365            // (1 << X) <= 30 -> X <= 4
1366            // (1 << X) >= 30 -> X >  4
1367            // (1 << X) >  30 -> X >  4
1368            if (Pred == ICmpInst::ICMP_ULT)
1369              Pred = ICmpInst::ICMP_ULE;
1370            else if (Pred == ICmpInst::ICMP_UGE)
1371              Pred = ICmpInst::ICMP_UGT;
1372          }
1373          unsigned RHSLog2 = RHSV.logBase2();
1374
1375          // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
1376          // (1 << X) >  2147483648 -> X >  31 -> false
1377          // (1 << X) <= 2147483648 -> X <= 31 -> true
1378          // (1 << X) <  2147483648 -> X <  31 -> X != 31
1379          if (RHSLog2 == TypeBits-1) {
1380            if (Pred == ICmpInst::ICMP_UGE)
1381              Pred = ICmpInst::ICMP_EQ;
1382            else if (Pred == ICmpInst::ICMP_UGT)
1383              return ReplaceInstUsesWith(ICI, Builder->getFalse());
1384            else if (Pred == ICmpInst::ICMP_ULE)
1385              return ReplaceInstUsesWith(ICI, Builder->getTrue());
1386            else if (Pred == ICmpInst::ICMP_ULT)
1387              Pred = ICmpInst::ICMP_NE;
1388          }
1389
1390          return new ICmpInst(Pred, X,
1391                              ConstantInt::get(RHS->getType(), RHSLog2));
1392        } else if (ICI.isSigned()) {
1393          if (RHSV.isAllOnesValue()) {
1394            // (1 << X) <= -1 -> X == 31
1395            if (Pred == ICmpInst::ICMP_SLE)
1396              return new ICmpInst(ICmpInst::ICMP_EQ, X,
1397                                  ConstantInt::get(RHS->getType(), TypeBits-1));
1398
1399            // (1 << X) >  -1 -> X != 31
1400            if (Pred == ICmpInst::ICMP_SGT)
1401              return new ICmpInst(ICmpInst::ICMP_NE, X,
1402                                  ConstantInt::get(RHS->getType(), TypeBits-1));
1403          } else if (!RHSV) {
1404            // (1 << X) <  0 -> X == 31
1405            // (1 << X) <= 0 -> X == 31
1406            if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1407              return new ICmpInst(ICmpInst::ICMP_EQ, X,
1408                                  ConstantInt::get(RHS->getType(), TypeBits-1));
1409
1410            // (1 << X) >= 0 -> X != 31
1411            // (1 << X) >  0 -> X != 31
1412            if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
1413              return new ICmpInst(ICmpInst::ICMP_NE, X,
1414                                  ConstantInt::get(RHS->getType(), TypeBits-1));
1415          }
1416        } else if (ICI.isEquality()) {
1417          if (RHSVIsPowerOf2)
1418            return new ICmpInst(
1419                Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
1420
1421          return ReplaceInstUsesWith(
1422              ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
1423                                             : Builder->getTrue());
1424        }
1425      }
1426      break;
1427    }
1428
1429    // Check that the shift amount is in range.  If not, don't perform
1430    // undefined shifts.  When the shift is visited it will be
1431    // simplified.
1432    if (ShAmt->uge(TypeBits))
1433      break;
1434
1435    if (ICI.isEquality()) {
1436      // If we are comparing against bits always shifted out, the
1437      // comparison cannot succeed.
1438      Constant *Comp =
1439        ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
1440                                                                 ShAmt);
1441      if (Comp != RHS) {// Comparing against a bit that we know is zero.
1442        bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1443        Constant *Cst = Builder->getInt1(IsICMP_NE);
1444        return ReplaceInstUsesWith(ICI, Cst);
1445      }
1446
1447      // If the shift is NUW, then it is just shifting out zeros, no need for an
1448      // AND.
1449      if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
1450        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1451                            ConstantExpr::getLShr(RHS, ShAmt));
1452
1453      // If the shift is NSW and we compare to 0, then it is just shifting out
1454      // sign bits, no need for an AND either.
1455      if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
1456        return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
1457                            ConstantExpr::getLShr(RHS, ShAmt));
1458
1459      if (LHSI->hasOneUse()) {
1460        // Otherwise strength reduce the shift into an and.
1461        uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
1462        Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
1463                                                          TypeBits - ShAmtVal));
1464
1465        Value *And =
1466          Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
1467        return new ICmpInst(ICI.getPredicate(), And,
1468                            ConstantExpr::getLShr(RHS, ShAmt));
1469      }
1470    }
1471
1472    // If this is a signed comparison to 0 and the shift is sign preserving,
1473    // use the shift LHS operand instead.
1474    ICmpInst::Predicate pred = ICI.getPredicate();
1475    if (isSignTest(pred, RHS) &&
1476        cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
1477      return new ICmpInst(pred,
1478                          LHSI->getOperand(0),
1479                          Constant::getNullValue(RHS->getType()));
1480
1481    // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
1482    bool TrueIfSigned = false;
1483    if (LHSI->hasOneUse() &&
1484        isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
1485      // (X << 31) <s 0  --> (X&1) != 0
1486      Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
1487                                        APInt::getOneBitSet(TypeBits,
1488                                            TypeBits-ShAmt->getZExtValue()-1));
1489      Value *And =
1490        Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
1491      return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
1492                          And, Constant::getNullValue(And->getType()));
1493    }
1494
1495    // Transform (icmp pred iM (shl iM %v, N), CI)
1496    // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
1497    // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
1498    // This enables to get rid of the shift in favor of a trunc which can be
1499    // free on the target. It has the additional benefit of comparing to a
1500    // smaller constant, which will be target friendly.
1501    unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
1502    if (LHSI->hasOneUse() &&
1503        Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
1504      Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
1505      Constant *NCI = ConstantExpr::getTrunc(
1506                        ConstantExpr::getAShr(RHS,
1507                          ConstantInt::get(RHS->getType(), Amt)),
1508                        NTy);
1509      return new ICmpInst(ICI.getPredicate(),
1510                          Builder->CreateTrunc(LHSI->getOperand(0), NTy),
1511                          NCI);
1512    }
1513
1514    break;
1515  }
1516
1517  case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
1518  case Instruction::AShr: {
1519    // Handle equality comparisons of shift-by-constant.
1520    BinaryOperator *BO = cast<BinaryOperator>(LHSI);
1521    if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
1522      if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
1523        return Res;
1524    }
1525
1526    // Handle exact shr's.
1527    if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
1528      if (RHSV.isMinValue())
1529        return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
1530    }
1531    break;
1532  }
1533
1534  case Instruction::SDiv:
1535  case Instruction::UDiv:
1536    // Fold: icmp pred ([us]div X, C1), C2 -> range test
1537    // Fold this div into the comparison, producing a range check.
1538    // Determine, based on the divide type, what the range is being
1539    // checked.  If there is an overflow on the low or high side, remember
1540    // it, otherwise compute the range [low, hi) bounding the new value.
1541    // See: InsertRangeTest above for the kinds of replacements possible.
1542    if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
1543      if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
1544                                          DivRHS))
1545        return R;
1546    break;
1547
1548  case Instruction::Sub: {
1549    ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
1550    if (!LHSC) break;
1551    const APInt &LHSV = LHSC->getValue();
1552
1553    // C1-X <u C2 -> (X|(C2-1)) == C1
1554    //   iff C1 & (C2-1) == C2-1
1555    //       C2 is a power of 2
1556    if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1557        RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
1558      return new ICmpInst(ICmpInst::ICMP_EQ,
1559                          Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
1560                          LHSC);
1561
1562    // C1-X >u C2 -> (X|C2) != C1
1563    //   iff C1 & C2 == C2
1564    //       C2+1 is a power of 2
1565    if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1566        (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
1567      return new ICmpInst(ICmpInst::ICMP_NE,
1568                          Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
1569    break;
1570  }
1571
1572  case Instruction::Add:
1573    // Fold: icmp pred (add X, C1), C2
1574    if (!ICI.isEquality()) {
1575      ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
1576      if (!LHSC) break;
1577      const APInt &LHSV = LHSC->getValue();
1578
1579      ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
1580                            .subtract(LHSV);
1581
1582      if (ICI.isSigned()) {
1583        if (CR.getLower().isSignBit()) {
1584          return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
1585                              Builder->getInt(CR.getUpper()));
1586        } else if (CR.getUpper().isSignBit()) {
1587          return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
1588                              Builder->getInt(CR.getLower()));
1589        }
1590      } else {
1591        if (CR.getLower().isMinValue()) {
1592          return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
1593                              Builder->getInt(CR.getUpper()));
1594        } else if (CR.getUpper().isMinValue()) {
1595          return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
1596                              Builder->getInt(CR.getLower()));
1597        }
1598      }
1599
1600      // X-C1 <u C2 -> (X & -C2) == C1
1601      //   iff C1 & (C2-1) == 0
1602      //       C2 is a power of 2
1603      if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
1604          RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
1605        return new ICmpInst(ICmpInst::ICMP_EQ,
1606                            Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
1607                            ConstantExpr::getNeg(LHSC));
1608
1609      // X-C1 >u C2 -> (X & ~C2) != C1
1610      //   iff C1 & C2 == 0
1611      //       C2+1 is a power of 2
1612      if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
1613          (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
1614        return new ICmpInst(ICmpInst::ICMP_NE,
1615                            Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
1616                            ConstantExpr::getNeg(LHSC));
1617    }
1618    break;
1619  }
1620
1621  // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
1622  if (ICI.isEquality()) {
1623    bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
1624
1625    // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
1626    // the second operand is a constant, simplify a bit.
1627    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
1628      switch (BO->getOpcode()) {
1629      case Instruction::SRem:
1630        // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1631        if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
1632          const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
1633          if (V.sgt(1) && V.isPowerOf2()) {
1634            Value *NewRem =
1635              Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
1636                                  BO->getName());
1637            return new ICmpInst(ICI.getPredicate(), NewRem,
1638                                Constant::getNullValue(BO->getType()));
1639          }
1640        }
1641        break;
1642      case Instruction::Add:
1643        // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1644        if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1645          if (BO->hasOneUse())
1646            return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1647                                ConstantExpr::getSub(RHS, BOp1C));
1648        } else if (RHSV == 0) {
1649          // Replace ((add A, B) != 0) with (A != -B) if A or B is
1650          // efficiently invertible, or if the add has just this one use.
1651          Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1652
1653          if (Value *NegVal = dyn_castNegVal(BOp1))
1654            return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
1655          if (Value *NegVal = dyn_castNegVal(BOp0))
1656            return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
1657          if (BO->hasOneUse()) {
1658            Value *Neg = Builder->CreateNeg(BOp1);
1659            Neg->takeName(BO);
1660            return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
1661          }
1662        }
1663        break;
1664      case Instruction::Xor:
1665        // For the xor case, we can xor two constants together, eliminating
1666        // the explicit xor.
1667        if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
1668          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1669                              ConstantExpr::getXor(RHS, BOC));
1670        } else if (RHSV == 0) {
1671          // Replace ((xor A, B) != 0) with (A != B)
1672          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1673                              BO->getOperand(1));
1674        }
1675        break;
1676      case Instruction::Sub:
1677        // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
1678        if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
1679          if (BO->hasOneUse())
1680            return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
1681                                ConstantExpr::getSub(BOp0C, RHS));
1682        } else if (RHSV == 0) {
1683          // Replace ((sub A, B) != 0) with (A != B)
1684          return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1685                              BO->getOperand(1));
1686        }
1687        break;
1688      case Instruction::Or:
1689        // If bits are being or'd in that are not present in the constant we
1690        // are comparing against, then the comparison could never succeed!
1691        if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1692          Constant *NotCI = ConstantExpr::getNot(RHS);
1693          if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
1694            return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1695        }
1696        break;
1697
1698      case Instruction::And:
1699        if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1700          // If bits are being compared against that are and'd out, then the
1701          // comparison can never succeed!
1702          if ((RHSV & ~BOC->getValue()) != 0)
1703            return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
1704
1705          // If we have ((X & C) == C), turn it into ((X & C) != 0).
1706          if (RHS == BOC && RHSV.isPowerOf2())
1707            return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
1708                                ICmpInst::ICMP_NE, LHSI,
1709                                Constant::getNullValue(RHS->getType()));
1710
1711          // Don't perform the following transforms if the AND has multiple uses
1712          if (!BO->hasOneUse())
1713            break;
1714
1715          // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
1716          if (BOC->getValue().isSignBit()) {
1717            Value *X = BO->getOperand(0);
1718            Constant *Zero = Constant::getNullValue(X->getType());
1719            ICmpInst::Predicate pred = isICMP_NE ?
1720              ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1721            return new ICmpInst(pred, X, Zero);
1722          }
1723
1724          // ((X & ~7) == 0) --> X < 8
1725          if (RHSV == 0 && isHighOnes(BOC)) {
1726            Value *X = BO->getOperand(0);
1727            Constant *NegX = ConstantExpr::getNeg(BOC);
1728            ICmpInst::Predicate pred = isICMP_NE ?
1729              ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1730            return new ICmpInst(pred, X, NegX);
1731          }
1732        }
1733        break;
1734      case Instruction::Mul:
1735        if (RHSV == 0 && BO->hasNoSignedWrap()) {
1736          if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1737            // The trivial case (mul X, 0) is handled by InstSimplify
1738            // General case : (mul X, C) != 0 iff X != 0
1739            //                (mul X, C) == 0 iff X == 0
1740            if (!BOC->isZero())
1741              return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
1742                                  Constant::getNullValue(RHS->getType()));
1743          }
1744        }
1745        break;
1746      default: break;
1747      }
1748    } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
1749      // Handle icmp {eq|ne} <intrinsic>, intcst.
1750      switch (II->getIntrinsicID()) {
1751      case Intrinsic::bswap:
1752        Worklist.Add(II);
1753        ICI.setOperand(0, II->getArgOperand(0));
1754        ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
1755        return &ICI;
1756      case Intrinsic::ctlz:
1757      case Intrinsic::cttz:
1758        // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
1759        if (RHSV == RHS->getType()->getBitWidth()) {
1760          Worklist.Add(II);
1761          ICI.setOperand(0, II->getArgOperand(0));
1762          ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
1763          return &ICI;
1764        }
1765        break;
1766      case Intrinsic::ctpop:
1767        // popcount(A) == 0  ->  A == 0 and likewise for !=
1768        if (RHS->isZero()) {
1769          Worklist.Add(II);
1770          ICI.setOperand(0, II->getArgOperand(0));
1771          ICI.setOperand(1, RHS);
1772          return &ICI;
1773        }
1774        break;
1775      default:
1776        break;
1777      }
1778    }
1779  }
1780  return 0;
1781}
1782
1783/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
1784/// We only handle extending casts so far.
1785///
1786Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
1787  const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
1788  Value *LHSCIOp        = LHSCI->getOperand(0);
1789  Type *SrcTy     = LHSCIOp->getType();
1790  Type *DestTy    = LHSCI->getType();
1791  Value *RHSCIOp;
1792
1793  // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
1794  // integer type is the same size as the pointer type.
1795  if (DL && LHSCI->getOpcode() == Instruction::PtrToInt &&
1796      DL->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
1797    Value *RHSOp = 0;
1798    if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
1799      RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
1800    } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
1801      RHSOp = RHSC->getOperand(0);
1802      // If the pointer types don't match, insert a bitcast.
1803      if (LHSCIOp->getType() != RHSOp->getType())
1804        RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
1805    }
1806
1807    if (RHSOp)
1808      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
1809  }
1810
1811  // The code below only handles extension cast instructions, so far.
1812  // Enforce this.
1813  if (LHSCI->getOpcode() != Instruction::ZExt &&
1814      LHSCI->getOpcode() != Instruction::SExt)
1815    return 0;
1816
1817  bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
1818  bool isSignedCmp = ICI.isSigned();
1819
1820  if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
1821    // Not an extension from the same type?
1822    RHSCIOp = CI->getOperand(0);
1823    if (RHSCIOp->getType() != LHSCIOp->getType())
1824      return 0;
1825
1826    // If the signedness of the two casts doesn't agree (i.e. one is a sext
1827    // and the other is a zext), then we can't handle this.
1828    if (CI->getOpcode() != LHSCI->getOpcode())
1829      return 0;
1830
1831    // Deal with equality cases early.
1832    if (ICI.isEquality())
1833      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1834
1835    // A signed comparison of sign extended values simplifies into a
1836    // signed comparison.
1837    if (isSignedCmp && isSignedExt)
1838      return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
1839
1840    // The other three cases all fold into an unsigned comparison.
1841    return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
1842  }
1843
1844  // If we aren't dealing with a constant on the RHS, exit early
1845  ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
1846  if (!CI)
1847    return 0;
1848
1849  // Compute the constant that would happen if we truncated to SrcTy then
1850  // reextended to DestTy.
1851  Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
1852  Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
1853                                                Res1, DestTy);
1854
1855  // If the re-extended constant didn't change...
1856  if (Res2 == CI) {
1857    // Deal with equality cases early.
1858    if (ICI.isEquality())
1859      return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1860
1861    // A signed comparison of sign extended values simplifies into a
1862    // signed comparison.
1863    if (isSignedExt && isSignedCmp)
1864      return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
1865
1866    // The other three cases all fold into an unsigned comparison.
1867    return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
1868  }
1869
1870  // The re-extended constant changed so the constant cannot be represented
1871  // in the shorter type. Consequently, we cannot emit a simple comparison.
1872  // All the cases that fold to true or false will have already been handled
1873  // by SimplifyICmpInst, so only deal with the tricky case.
1874
1875  if (isSignedCmp || !isSignedExt)
1876    return 0;
1877
1878  // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
1879  // should have been folded away previously and not enter in here.
1880
1881  // We're performing an unsigned comp with a sign extended value.
1882  // This is true if the input is >= 0. [aka >s -1]
1883  Constant *NegOne = Constant::getAllOnesValue(SrcTy);
1884  Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
1885
1886  // Finally, return the value computed.
1887  if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
1888    return ReplaceInstUsesWith(ICI, Result);
1889
1890  assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
1891  return BinaryOperator::CreateNot(Result);
1892}
1893
1894/// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
1895///   I = icmp ugt (add (add A, B), CI2), CI1
1896/// If this is of the form:
1897///   sum = a + b
1898///   if (sum+128 >u 255)
1899/// Then replace it with llvm.sadd.with.overflow.i8.
1900///
1901static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1902                                          ConstantInt *CI2, ConstantInt *CI1,
1903                                          InstCombiner &IC) {
1904  // The transformation we're trying to do here is to transform this into an
1905  // llvm.sadd.with.overflow.  To do this, we have to replace the original add
1906  // with a narrower add, and discard the add-with-constant that is part of the
1907  // range check (if we can't eliminate it, this isn't profitable).
1908
1909  // In order to eliminate the add-with-constant, the compare can be its only
1910  // use.
1911  Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1912  if (!AddWithCst->hasOneUse()) return 0;
1913
1914  // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1915  if (!CI2->getValue().isPowerOf2()) return 0;
1916  unsigned NewWidth = CI2->getValue().countTrailingZeros();
1917  if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
1918
1919  // The width of the new add formed is 1 more than the bias.
1920  ++NewWidth;
1921
1922  // Check to see that CI1 is an all-ones value with NewWidth bits.
1923  if (CI1->getBitWidth() == NewWidth ||
1924      CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1925    return 0;
1926
1927  // This is only really a signed overflow check if the inputs have been
1928  // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1929  // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1930  unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
1931  if (IC.ComputeNumSignBits(A) < NeededSignBits ||
1932      IC.ComputeNumSignBits(B) < NeededSignBits)
1933    return 0;
1934
1935  // In order to replace the original add with a narrower
1936  // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1937  // and truncates that discard the high bits of the add.  Verify that this is
1938  // the case.
1939  Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1940  for (User *U : OrigAdd->users()) {
1941    if (U == AddWithCst) continue;
1942
1943    // Only accept truncates for now.  We would really like a nice recursive
1944    // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1945    // chain to see which bits of a value are actually demanded.  If the
1946    // original add had another add which was then immediately truncated, we
1947    // could still do the transformation.
1948    TruncInst *TI = dyn_cast<TruncInst>(U);
1949    if (TI == 0 ||
1950        TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
1951  }
1952
1953  // If the pattern matches, truncate the inputs to the narrower type and
1954  // use the sadd_with_overflow intrinsic to efficiently compute both the
1955  // result and the overflow bit.
1956  Module *M = I.getParent()->getParent()->getParent();
1957
1958  Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1959  Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
1960                                       NewType);
1961
1962  InstCombiner::BuilderTy *Builder = IC.Builder;
1963
1964  // Put the new code above the original add, in case there are any uses of the
1965  // add between the add and the compare.
1966  Builder->SetInsertPoint(OrigAdd);
1967
1968  Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
1969  Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
1970  CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
1971  Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
1972  Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
1973
1974  // The inner add was the result of the narrow add, zero extended to the
1975  // wider type.  Replace it with the result computed by the intrinsic.
1976  IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
1977
1978  // The original icmp gets replaced with the overflow value.
1979  return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1980}
1981
1982static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
1983                                     InstCombiner &IC) {
1984  // Don't bother doing this transformation for pointers, don't do it for
1985  // vectors.
1986  if (!isa<IntegerType>(OrigAddV->getType())) return 0;
1987
1988  // If the add is a constant expr, then we don't bother transforming it.
1989  Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
1990  if (OrigAdd == 0) return 0;
1991
1992  Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
1993
1994  // Put the new code above the original add, in case there are any uses of the
1995  // add between the add and the compare.
1996  InstCombiner::BuilderTy *Builder = IC.Builder;
1997  Builder->SetInsertPoint(OrigAdd);
1998
1999  Module *M = I.getParent()->getParent()->getParent();
2000  Type *Ty = LHS->getType();
2001  Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
2002  CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
2003  Value *Add = Builder->CreateExtractValue(Call, 0);
2004
2005  IC.ReplaceInstUsesWith(*OrigAdd, Add);
2006
2007  // The original icmp gets replaced with the overflow value.
2008  return ExtractValueInst::Create(Call, 1, "uadd.overflow");
2009}
2010
2011// DemandedBitsLHSMask - When performing a comparison against a constant,
2012// it is possible that not all the bits in the LHS are demanded.  This helper
2013// method computes the mask that IS demanded.
2014static APInt DemandedBitsLHSMask(ICmpInst &I,
2015                                 unsigned BitWidth, bool isSignCheck) {
2016  if (isSignCheck)
2017    return APInt::getSignBit(BitWidth);
2018
2019  ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2020  if (!CI) return APInt::getAllOnesValue(BitWidth);
2021  const APInt &RHS = CI->getValue();
2022
2023  switch (I.getPredicate()) {
2024  // For a UGT comparison, we don't care about any bits that
2025  // correspond to the trailing ones of the comparand.  The value of these
2026  // bits doesn't impact the outcome of the comparison, because any value
2027  // greater than the RHS must differ in a bit higher than these due to carry.
2028  case ICmpInst::ICMP_UGT: {
2029    unsigned trailingOnes = RHS.countTrailingOnes();
2030    APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
2031    return ~lowBitsSet;
2032  }
2033
2034  // Similarly, for a ULT comparison, we don't care about the trailing zeros.
2035  // Any value less than the RHS must differ in a higher bit because of carries.
2036  case ICmpInst::ICMP_ULT: {
2037    unsigned trailingZeros = RHS.countTrailingZeros();
2038    APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
2039    return ~lowBitsSet;
2040  }
2041
2042  default:
2043    return APInt::getAllOnesValue(BitWidth);
2044  }
2045
2046}
2047
2048/// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
2049/// should be swapped.
2050/// The decision is based on how many times these two operands are reused
2051/// as subtract operands and their positions in those instructions.
2052/// The rational is that several architectures use the same instruction for
2053/// both subtract and cmp, thus it is better if the order of those operands
2054/// match.
2055/// \return true if Op0 and Op1 should be swapped.
2056static bool swapMayExposeCSEOpportunities(const Value * Op0,
2057                                          const Value * Op1) {
2058  // Filter out pointer value as those cannot appears directly in subtract.
2059  // FIXME: we may want to go through inttoptrs or bitcasts.
2060  if (Op0->getType()->isPointerTy())
2061    return false;
2062  // Count every uses of both Op0 and Op1 in a subtract.
2063  // Each time Op0 is the first operand, count -1: swapping is bad, the
2064  // subtract has already the same layout as the compare.
2065  // Each time Op0 is the second operand, count +1: swapping is good, the
2066  // subtract has a different layout as the compare.
2067  // At the end, if the benefit is greater than 0, Op0 should come second to
2068  // expose more CSE opportunities.
2069  int GlobalSwapBenefits = 0;
2070  for (const User *U : Op0->users()) {
2071    const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
2072    if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
2073      continue;
2074    // If Op0 is the first argument, this is not beneficial to swap the
2075    // arguments.
2076    int LocalSwapBenefits = -1;
2077    unsigned Op1Idx = 1;
2078    if (BinOp->getOperand(Op1Idx) == Op0) {
2079      Op1Idx = 0;
2080      LocalSwapBenefits = 1;
2081    }
2082    if (BinOp->getOperand(Op1Idx) != Op1)
2083      continue;
2084    GlobalSwapBenefits += LocalSwapBenefits;
2085  }
2086  return GlobalSwapBenefits > 0;
2087}
2088
2089Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
2090  bool Changed = false;
2091  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2092  unsigned Op0Cplxity = getComplexity(Op0);
2093  unsigned Op1Cplxity = getComplexity(Op1);
2094
2095  /// Orders the operands of the compare so that they are listed from most
2096  /// complex to least complex.  This puts constants before unary operators,
2097  /// before binary operators.
2098  if (Op0Cplxity < Op1Cplxity ||
2099        (Op0Cplxity == Op1Cplxity &&
2100         swapMayExposeCSEOpportunities(Op0, Op1))) {
2101    I.swapOperands();
2102    std::swap(Op0, Op1);
2103    Changed = true;
2104  }
2105
2106  if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL))
2107    return ReplaceInstUsesWith(I, V);
2108
2109  // comparing -val or val with non-zero is the same as just comparing val
2110  // ie, abs(val) != 0 -> val != 0
2111  if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
2112  {
2113    Value *Cond, *SelectTrue, *SelectFalse;
2114    if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
2115                            m_Value(SelectFalse)))) {
2116      if (Value *V = dyn_castNegVal(SelectTrue)) {
2117        if (V == SelectFalse)
2118          return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2119      }
2120      else if (Value *V = dyn_castNegVal(SelectFalse)) {
2121        if (V == SelectTrue)
2122          return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
2123      }
2124    }
2125  }
2126
2127  Type *Ty = Op0->getType();
2128
2129  // icmp's with boolean values can always be turned into bitwise operations
2130  if (Ty->isIntegerTy(1)) {
2131    switch (I.getPredicate()) {
2132    default: llvm_unreachable("Invalid icmp instruction!");
2133    case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
2134      Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
2135      return BinaryOperator::CreateNot(Xor);
2136    }
2137    case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
2138      return BinaryOperator::CreateXor(Op0, Op1);
2139
2140    case ICmpInst::ICMP_UGT:
2141      std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
2142      // FALL THROUGH
2143    case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
2144      Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2145      return BinaryOperator::CreateAnd(Not, Op1);
2146    }
2147    case ICmpInst::ICMP_SGT:
2148      std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
2149      // FALL THROUGH
2150    case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
2151      Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2152      return BinaryOperator::CreateAnd(Not, Op0);
2153    }
2154    case ICmpInst::ICMP_UGE:
2155      std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
2156      // FALL THROUGH
2157    case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
2158      Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
2159      return BinaryOperator::CreateOr(Not, Op1);
2160    }
2161    case ICmpInst::ICMP_SGE:
2162      std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
2163      // FALL THROUGH
2164    case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
2165      Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
2166      return BinaryOperator::CreateOr(Not, Op0);
2167    }
2168    }
2169  }
2170
2171  unsigned BitWidth = 0;
2172  if (Ty->isIntOrIntVectorTy())
2173    BitWidth = Ty->getScalarSizeInBits();
2174  else if (DL)  // Pointers require DL info to get their size.
2175    BitWidth = DL->getTypeSizeInBits(Ty->getScalarType());
2176
2177  bool isSignBit = false;
2178
2179  // See if we are doing a comparison with a constant.
2180  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2181    Value *A = 0, *B = 0;
2182
2183    // Match the following pattern, which is a common idiom when writing
2184    // overflow-safe integer arithmetic function.  The source performs an
2185    // addition in wider type, and explicitly checks for overflow using
2186    // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
2187    // sadd_with_overflow intrinsic.
2188    //
2189    // TODO: This could probably be generalized to handle other overflow-safe
2190    // operations if we worked out the formulas to compute the appropriate
2191    // magic constants.
2192    //
2193    // sum = a + b
2194    // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
2195    {
2196    ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
2197    if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2198        match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
2199      if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
2200        return Res;
2201    }
2202
2203    // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
2204    if (I.isEquality() && CI->isZero() &&
2205        match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
2206      // (icmp cond A B) if cond is equality
2207      return new ICmpInst(I.getPredicate(), A, B);
2208    }
2209
2210    // If we have an icmp le or icmp ge instruction, turn it into the
2211    // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
2212    // them being folded in the code below.  The SimplifyICmpInst code has
2213    // already handled the edge cases for us, so we just assert on them.
2214    switch (I.getPredicate()) {
2215    default: break;
2216    case ICmpInst::ICMP_ULE:
2217      assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
2218      return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
2219                          Builder->getInt(CI->getValue()+1));
2220    case ICmpInst::ICMP_SLE:
2221      assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
2222      return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2223                          Builder->getInt(CI->getValue()+1));
2224    case ICmpInst::ICMP_UGE:
2225      assert(!CI->isMinValue(false));                 // A >=u MIN -> TRUE
2226      return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
2227                          Builder->getInt(CI->getValue()-1));
2228    case ICmpInst::ICMP_SGE:
2229      assert(!CI->isMinValue(true));                  // A >=s MIN -> TRUE
2230      return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2231                          Builder->getInt(CI->getValue()-1));
2232    }
2233
2234    // If this comparison is a normal comparison, it demands all
2235    // bits, if it is a sign bit comparison, it only demands the sign bit.
2236    bool UnusedBit;
2237    isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
2238  }
2239
2240  // See if we can fold the comparison based on range information we can get
2241  // by checking whether bits are known to be zero or one in the input.
2242  if (BitWidth != 0) {
2243    APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
2244    APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
2245
2246    if (SimplifyDemandedBits(I.getOperandUse(0),
2247                             DemandedBitsLHSMask(I, BitWidth, isSignBit),
2248                             Op0KnownZero, Op0KnownOne, 0))
2249      return &I;
2250    if (SimplifyDemandedBits(I.getOperandUse(1),
2251                             APInt::getAllOnesValue(BitWidth),
2252                             Op1KnownZero, Op1KnownOne, 0))
2253      return &I;
2254
2255    // Given the known and unknown bits, compute a range that the LHS could be
2256    // in.  Compute the Min, Max and RHS values based on the known bits. For the
2257    // EQ and NE we use unsigned values.
2258    APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
2259    APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
2260    if (I.isSigned()) {
2261      ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2262                                             Op0Min, Op0Max);
2263      ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2264                                             Op1Min, Op1Max);
2265    } else {
2266      ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
2267                                               Op0Min, Op0Max);
2268      ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
2269                                               Op1Min, Op1Max);
2270    }
2271
2272    // If Min and Max are known to be the same, then SimplifyDemandedBits
2273    // figured out that the LHS is a constant.  Just constant fold this now so
2274    // that code below can assume that Min != Max.
2275    if (!isa<Constant>(Op0) && Op0Min == Op0Max)
2276      return new ICmpInst(I.getPredicate(),
2277                          ConstantInt::get(Op0->getType(), Op0Min), Op1);
2278    if (!isa<Constant>(Op1) && Op1Min == Op1Max)
2279      return new ICmpInst(I.getPredicate(), Op0,
2280                          ConstantInt::get(Op1->getType(), Op1Min));
2281
2282    // Based on the range information we know about the LHS, see if we can
2283    // simplify this comparison.  For example, (x&4) < 8 is always true.
2284    switch (I.getPredicate()) {
2285    default: llvm_unreachable("Unknown icmp opcode!");
2286    case ICmpInst::ICMP_EQ: {
2287      if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2288        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2289
2290      // If all bits are known zero except for one, then we know at most one
2291      // bit is set.   If the comparison is against zero, then this is a check
2292      // to see if *that* bit is set.
2293      APInt Op0KnownZeroInverted = ~Op0KnownZero;
2294      if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2295        // If the LHS is an AND with the same constant, look through it.
2296        Value *LHS = 0;
2297        ConstantInt *LHSC = 0;
2298        if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2299            LHSC->getValue() != Op0KnownZeroInverted)
2300          LHS = Op0;
2301
2302        // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2303        // then turn "((1 << x)&8) == 0" into "x != 3".
2304        Value *X = 0;
2305        if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2306          unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2307          return new ICmpInst(ICmpInst::ICMP_NE, X,
2308                              ConstantInt::get(X->getType(), CmpVal));
2309        }
2310
2311        // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2312        // then turn "((8 >>u x)&1) == 0" into "x != 3".
2313        const APInt *CI;
2314        if (Op0KnownZeroInverted == 1 &&
2315            match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2316          return new ICmpInst(ICmpInst::ICMP_NE, X,
2317                              ConstantInt::get(X->getType(),
2318                                               CI->countTrailingZeros()));
2319      }
2320
2321      break;
2322    }
2323    case ICmpInst::ICMP_NE: {
2324      if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
2325        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2326
2327      // If all bits are known zero except for one, then we know at most one
2328      // bit is set.   If the comparison is against zero, then this is a check
2329      // to see if *that* bit is set.
2330      APInt Op0KnownZeroInverted = ~Op0KnownZero;
2331      if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
2332        // If the LHS is an AND with the same constant, look through it.
2333        Value *LHS = 0;
2334        ConstantInt *LHSC = 0;
2335        if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
2336            LHSC->getValue() != Op0KnownZeroInverted)
2337          LHS = Op0;
2338
2339        // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
2340        // then turn "((1 << x)&8) != 0" into "x == 3".
2341        Value *X = 0;
2342        if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
2343          unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
2344          return new ICmpInst(ICmpInst::ICMP_EQ, X,
2345                              ConstantInt::get(X->getType(), CmpVal));
2346        }
2347
2348        // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
2349        // then turn "((8 >>u x)&1) != 0" into "x == 3".
2350        const APInt *CI;
2351        if (Op0KnownZeroInverted == 1 &&
2352            match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
2353          return new ICmpInst(ICmpInst::ICMP_EQ, X,
2354                              ConstantInt::get(X->getType(),
2355                                               CI->countTrailingZeros()));
2356      }
2357
2358      break;
2359    }
2360    case ICmpInst::ICMP_ULT:
2361      if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
2362        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2363      if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
2364        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2365      if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
2366        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2367      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2368        if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
2369          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2370                              Builder->getInt(CI->getValue()-1));
2371
2372        // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
2373        if (CI->isMinValue(true))
2374          return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
2375                           Constant::getAllOnesValue(Op0->getType()));
2376      }
2377      break;
2378    case ICmpInst::ICMP_UGT:
2379      if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
2380        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2381      if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
2382        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2383
2384      if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
2385        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2386      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2387        if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
2388          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2389                              Builder->getInt(CI->getValue()+1));
2390
2391        // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
2392        if (CI->isMaxValue(true))
2393          return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
2394                              Constant::getNullValue(Op0->getType()));
2395      }
2396      break;
2397    case ICmpInst::ICMP_SLT:
2398      if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
2399        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2400      if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
2401        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2402      if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
2403        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2404      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2405        if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
2406          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2407                              Builder->getInt(CI->getValue()-1));
2408      }
2409      break;
2410    case ICmpInst::ICMP_SGT:
2411      if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
2412        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2413      if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
2414        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2415
2416      if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
2417        return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
2418      if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2419        if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
2420          return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
2421                              Builder->getInt(CI->getValue()+1));
2422      }
2423      break;
2424    case ICmpInst::ICMP_SGE:
2425      assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
2426      if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
2427        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2428      if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
2429        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2430      break;
2431    case ICmpInst::ICMP_SLE:
2432      assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
2433      if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
2434        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2435      if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
2436        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2437      break;
2438    case ICmpInst::ICMP_UGE:
2439      assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
2440      if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
2441        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2442      if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
2443        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2444      break;
2445    case ICmpInst::ICMP_ULE:
2446      assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
2447      if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
2448        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2449      if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
2450        return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2451      break;
2452    }
2453
2454    // Turn a signed comparison into an unsigned one if both operands
2455    // are known to have the same sign.
2456    if (I.isSigned() &&
2457        ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
2458         (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
2459      return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
2460  }
2461
2462  // Test if the ICmpInst instruction is used exclusively by a select as
2463  // part of a minimum or maximum operation. If so, refrain from doing
2464  // any other folding. This helps out other analyses which understand
2465  // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
2466  // and CodeGen. And in this case, at least one of the comparison
2467  // operands has at least one user besides the compare (the select),
2468  // which would often largely negate the benefit of folding anyway.
2469  if (I.hasOneUse())
2470    if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
2471      if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
2472          (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
2473        return 0;
2474
2475  // See if we are doing a comparison between a constant and an instruction that
2476  // can be folded into the comparison.
2477  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2478    // Since the RHS is a ConstantInt (CI), if the left hand side is an
2479    // instruction, see if that instruction also has constants so that the
2480    // instruction can be folded into the icmp
2481    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2482      if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
2483        return Res;
2484  }
2485
2486  // Handle icmp with constant (but not simple integer constant) RHS
2487  if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2488    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2489      switch (LHSI->getOpcode()) {
2490      case Instruction::GetElementPtr:
2491          // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
2492        if (RHSC->isNullValue() &&
2493            cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2494          return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2495                  Constant::getNullValue(LHSI->getOperand(0)->getType()));
2496        break;
2497      case Instruction::PHI:
2498        // Only fold icmp into the PHI if the phi and icmp are in the same
2499        // block.  If in the same block, we're encouraging jump threading.  If
2500        // not, we are just pessimizing the code by making an i1 phi.
2501        if (LHSI->getParent() == I.getParent())
2502          if (Instruction *NV = FoldOpIntoPhi(I))
2503            return NV;
2504        break;
2505      case Instruction::Select: {
2506        // If either operand of the select is a constant, we can fold the
2507        // comparison into the select arms, which will cause one to be
2508        // constant folded and the select turned into a bitwise or.
2509        Value *Op1 = 0, *Op2 = 0;
2510        if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
2511          Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2512        if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
2513          Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
2514
2515        // We only want to perform this transformation if it will not lead to
2516        // additional code. This is true if either both sides of the select
2517        // fold to a constant (in which case the icmp is replaced with a select
2518        // which will usually simplify) or this is the only user of the
2519        // select (in which case we are trading a select+icmp for a simpler
2520        // select+icmp).
2521        if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
2522          if (!Op1)
2523            Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
2524                                      RHSC, I.getName());
2525          if (!Op2)
2526            Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
2527                                      RHSC, I.getName());
2528          return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
2529        }
2530        break;
2531      }
2532      case Instruction::IntToPtr:
2533        // icmp pred inttoptr(X), null -> icmp pred X, 0
2534        if (RHSC->isNullValue() && DL &&
2535            DL->getIntPtrType(RHSC->getType()) ==
2536               LHSI->getOperand(0)->getType())
2537          return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
2538                        Constant::getNullValue(LHSI->getOperand(0)->getType()));
2539        break;
2540
2541      case Instruction::Load:
2542        // Try to optimize things like "A[i] > 4" to index computations.
2543        if (GetElementPtrInst *GEP =
2544              dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2545          if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
2546            if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
2547                !cast<LoadInst>(LHSI)->isVolatile())
2548              if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
2549                return Res;
2550        }
2551        break;
2552      }
2553  }
2554
2555  // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
2556  if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
2557    if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
2558      return NI;
2559  if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
2560    if (Instruction *NI = FoldGEPICmp(GEP, Op0,
2561                           ICmpInst::getSwappedPredicate(I.getPredicate()), I))
2562      return NI;
2563
2564  // Test to see if the operands of the icmp are casted versions of other
2565  // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
2566  // now.
2567  if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
2568    if (Op0->getType()->isPointerTy() &&
2569        (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2570      // We keep moving the cast from the left operand over to the right
2571      // operand, where it can often be eliminated completely.
2572      Op0 = CI->getOperand(0);
2573
2574      // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2575      // so eliminate it as well.
2576      if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
2577        Op1 = CI2->getOperand(0);
2578
2579      // If Op1 is a constant, we can fold the cast into the constant.
2580      if (Op0->getType() != Op1->getType()) {
2581        if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2582          Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
2583        } else {
2584          // Otherwise, cast the RHS right before the icmp
2585          Op1 = Builder->CreateBitCast(Op1, Op0->getType());
2586        }
2587      }
2588      return new ICmpInst(I.getPredicate(), Op0, Op1);
2589    }
2590  }
2591
2592  if (isa<CastInst>(Op0)) {
2593    // Handle the special case of: icmp (cast bool to X), <cst>
2594    // This comes up when you have code like
2595    //   int X = A < B;
2596    //   if (X) ...
2597    // For generality, we handle any zero-extension of any operand comparison
2598    // with a constant or another cast from the same type.
2599    if (isa<Constant>(Op1) || isa<CastInst>(Op1))
2600      if (Instruction *R = visitICmpInstWithCastAndCast(I))
2601        return R;
2602  }
2603
2604  // Special logic for binary operators.
2605  BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
2606  BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
2607  if (BO0 || BO1) {
2608    CmpInst::Predicate Pred = I.getPredicate();
2609    bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
2610    if (BO0 && isa<OverflowingBinaryOperator>(BO0))
2611      NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
2612        (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
2613        (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
2614    if (BO1 && isa<OverflowingBinaryOperator>(BO1))
2615      NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
2616        (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
2617        (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
2618
2619    // Analyze the case when either Op0 or Op1 is an add instruction.
2620    // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
2621    Value *A = 0, *B = 0, *C = 0, *D = 0;
2622    if (BO0 && BO0->getOpcode() == Instruction::Add)
2623      A = BO0->getOperand(0), B = BO0->getOperand(1);
2624    if (BO1 && BO1->getOpcode() == Instruction::Add)
2625      C = BO1->getOperand(0), D = BO1->getOperand(1);
2626
2627    // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2628    if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
2629      return new ICmpInst(Pred, A == Op1 ? B : A,
2630                          Constant::getNullValue(Op1->getType()));
2631
2632    // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2633    if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
2634      return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
2635                          C == Op0 ? D : C);
2636
2637    // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
2638    if (A && C && (A == C || A == D || B == C || B == D) &&
2639        NoOp0WrapProblem && NoOp1WrapProblem &&
2640        // Try not to increase register pressure.
2641        BO0->hasOneUse() && BO1->hasOneUse()) {
2642      // Determine Y and Z in the form icmp (X+Y), (X+Z).
2643      Value *Y, *Z;
2644      if (A == C) {
2645        // C + B == C + D  ->  B == D
2646        Y = B;
2647        Z = D;
2648      } else if (A == D) {
2649        // D + B == C + D  ->  B == C
2650        Y = B;
2651        Z = C;
2652      } else if (B == C) {
2653        // A + C == C + D  ->  A == D
2654        Y = A;
2655        Z = D;
2656      } else {
2657        assert(B == D);
2658        // A + D == C + D  ->  A == C
2659        Y = A;
2660        Z = C;
2661      }
2662      return new ICmpInst(Pred, Y, Z);
2663    }
2664
2665    // icmp slt (X + -1), Y -> icmp sle X, Y
2666    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
2667        match(B, m_AllOnes()))
2668      return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
2669
2670    // icmp sge (X + -1), Y -> icmp sgt X, Y
2671    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
2672        match(B, m_AllOnes()))
2673      return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
2674
2675    // icmp sle (X + 1), Y -> icmp slt X, Y
2676    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
2677        match(B, m_One()))
2678      return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
2679
2680    // icmp sgt (X + 1), Y -> icmp sge X, Y
2681    if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
2682        match(B, m_One()))
2683      return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
2684
2685    // if C1 has greater magnitude than C2:
2686    //  icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
2687    //  s.t. C3 = C1 - C2
2688    //
2689    // if C2 has greater magnitude than C1:
2690    //  icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
2691    //  s.t. C3 = C2 - C1
2692    if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
2693        (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
2694      if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
2695        if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
2696          const APInt &AP1 = C1->getValue();
2697          const APInt &AP2 = C2->getValue();
2698          if (AP1.isNegative() == AP2.isNegative()) {
2699            APInt AP1Abs = C1->getValue().abs();
2700            APInt AP2Abs = C2->getValue().abs();
2701            if (AP1Abs.uge(AP2Abs)) {
2702              ConstantInt *C3 = Builder->getInt(AP1 - AP2);
2703              Value *NewAdd = Builder->CreateNSWAdd(A, C3);
2704              return new ICmpInst(Pred, NewAdd, C);
2705            } else {
2706              ConstantInt *C3 = Builder->getInt(AP2 - AP1);
2707              Value *NewAdd = Builder->CreateNSWAdd(C, C3);
2708              return new ICmpInst(Pred, A, NewAdd);
2709            }
2710          }
2711        }
2712
2713
2714    // Analyze the case when either Op0 or Op1 is a sub instruction.
2715    // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
2716    A = 0; B = 0; C = 0; D = 0;
2717    if (BO0 && BO0->getOpcode() == Instruction::Sub)
2718      A = BO0->getOperand(0), B = BO0->getOperand(1);
2719    if (BO1 && BO1->getOpcode() == Instruction::Sub)
2720      C = BO1->getOperand(0), D = BO1->getOperand(1);
2721
2722    // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
2723    if (A == Op1 && NoOp0WrapProblem)
2724      return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
2725
2726    // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
2727    if (C == Op0 && NoOp1WrapProblem)
2728      return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
2729
2730    // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
2731    if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
2732        // Try not to increase register pressure.
2733        BO0->hasOneUse() && BO1->hasOneUse())
2734      return new ICmpInst(Pred, A, C);
2735
2736    // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
2737    if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
2738        // Try not to increase register pressure.
2739        BO0->hasOneUse() && BO1->hasOneUse())
2740      return new ICmpInst(Pred, D, B);
2741
2742    BinaryOperator *SRem = NULL;
2743    // icmp (srem X, Y), Y
2744    if (BO0 && BO0->getOpcode() == Instruction::SRem &&
2745        Op1 == BO0->getOperand(1))
2746      SRem = BO0;
2747    // icmp Y, (srem X, Y)
2748    else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
2749             Op0 == BO1->getOperand(1))
2750      SRem = BO1;
2751    if (SRem) {
2752      // We don't check hasOneUse to avoid increasing register pressure because
2753      // the value we use is the same value this instruction was already using.
2754      switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
2755        default: break;
2756        case ICmpInst::ICMP_EQ:
2757          return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
2758        case ICmpInst::ICMP_NE:
2759          return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
2760        case ICmpInst::ICMP_SGT:
2761        case ICmpInst::ICMP_SGE:
2762          return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
2763                              Constant::getAllOnesValue(SRem->getType()));
2764        case ICmpInst::ICMP_SLT:
2765        case ICmpInst::ICMP_SLE:
2766          return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
2767                              Constant::getNullValue(SRem->getType()));
2768      }
2769    }
2770
2771    if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
2772        BO0->hasOneUse() && BO1->hasOneUse() &&
2773        BO0->getOperand(1) == BO1->getOperand(1)) {
2774      switch (BO0->getOpcode()) {
2775      default: break;
2776      case Instruction::Add:
2777      case Instruction::Sub:
2778      case Instruction::Xor:
2779        if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
2780          return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2781                              BO1->getOperand(0));
2782        // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
2783        if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2784          if (CI->getValue().isSignBit()) {
2785            ICmpInst::Predicate Pred = I.isSigned()
2786                                           ? I.getUnsignedPredicate()
2787                                           : I.getSignedPredicate();
2788            return new ICmpInst(Pred, BO0->getOperand(0),
2789                                BO1->getOperand(0));
2790          }
2791
2792          if (CI->isMaxValue(true)) {
2793            ICmpInst::Predicate Pred = I.isSigned()
2794                                           ? I.getUnsignedPredicate()
2795                                           : I.getSignedPredicate();
2796            Pred = I.getSwappedPredicate(Pred);
2797            return new ICmpInst(Pred, BO0->getOperand(0),
2798                                BO1->getOperand(0));
2799          }
2800        }
2801        break;
2802      case Instruction::Mul:
2803        if (!I.isEquality())
2804          break;
2805
2806        if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
2807          // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
2808          // Mask = -1 >> count-trailing-zeros(Cst).
2809          if (!CI->isZero() && !CI->isOne()) {
2810            const APInt &AP = CI->getValue();
2811            ConstantInt *Mask = ConstantInt::get(I.getContext(),
2812                                    APInt::getLowBitsSet(AP.getBitWidth(),
2813                                                         AP.getBitWidth() -
2814                                                    AP.countTrailingZeros()));
2815            Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
2816            Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
2817            return new ICmpInst(I.getPredicate(), And1, And2);
2818          }
2819        }
2820        break;
2821      case Instruction::UDiv:
2822      case Instruction::LShr:
2823        if (I.isSigned())
2824          break;
2825        // fall-through
2826      case Instruction::SDiv:
2827      case Instruction::AShr:
2828        if (!BO0->isExact() || !BO1->isExact())
2829          break;
2830        return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2831                            BO1->getOperand(0));
2832      case Instruction::Shl: {
2833        bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
2834        bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
2835        if (!NUW && !NSW)
2836          break;
2837        if (!NSW && I.isSigned())
2838          break;
2839        return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
2840                            BO1->getOperand(0));
2841      }
2842      }
2843    }
2844  }
2845
2846  { Value *A, *B;
2847    // Transform (A & ~B) == 0 --> (A & B) != 0
2848    // and       (A & ~B) != 0 --> (A & B) == 0
2849    // if A is a power of 2.
2850    if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2851        match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
2852      return new ICmpInst(I.getInversePredicate(),
2853                          Builder->CreateAnd(A, B),
2854                          Op1);
2855
2856    // ~x < ~y --> y < x
2857    // ~x < cst --> ~cst < x
2858    if (match(Op0, m_Not(m_Value(A)))) {
2859      if (match(Op1, m_Not(m_Value(B))))
2860        return new ICmpInst(I.getPredicate(), B, A);
2861      if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
2862        return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
2863    }
2864
2865    // (a+b) <u a  --> llvm.uadd.with.overflow.
2866    // (a+b) <u b  --> llvm.uadd.with.overflow.
2867    if (I.getPredicate() == ICmpInst::ICMP_ULT &&
2868        match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2869        (Op1 == A || Op1 == B))
2870      if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
2871        return R;
2872
2873    // a >u (a+b)  --> llvm.uadd.with.overflow.
2874    // b >u (a+b)  --> llvm.uadd.with.overflow.
2875    if (I.getPredicate() == ICmpInst::ICMP_UGT &&
2876        match(Op1, m_Add(m_Value(A), m_Value(B))) &&
2877        (Op0 == A || Op0 == B))
2878      if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
2879        return R;
2880  }
2881
2882  if (I.isEquality()) {
2883    Value *A, *B, *C, *D;
2884
2885    if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2886      if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
2887        Value *OtherVal = A == Op1 ? B : A;
2888        return new ICmpInst(I.getPredicate(), OtherVal,
2889                            Constant::getNullValue(A->getType()));
2890      }
2891
2892      if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
2893        // A^c1 == C^c2 --> A == C^(c1^c2)
2894        ConstantInt *C1, *C2;
2895        if (match(B, m_ConstantInt(C1)) &&
2896            match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
2897          Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
2898          Value *Xor = Builder->CreateXor(C, NC);
2899          return new ICmpInst(I.getPredicate(), A, Xor);
2900        }
2901
2902        // A^B == A^D -> B == D
2903        if (A == C) return new ICmpInst(I.getPredicate(), B, D);
2904        if (A == D) return new ICmpInst(I.getPredicate(), B, C);
2905        if (B == C) return new ICmpInst(I.getPredicate(), A, D);
2906        if (B == D) return new ICmpInst(I.getPredicate(), A, C);
2907      }
2908    }
2909
2910    if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2911        (A == Op0 || B == Op0)) {
2912      // A == (A^B)  ->  B == 0
2913      Value *OtherVal = A == Op0 ? B : A;
2914      return new ICmpInst(I.getPredicate(), OtherVal,
2915                          Constant::getNullValue(A->getType()));
2916    }
2917
2918    // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
2919    if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
2920        match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
2921      Value *X = 0, *Y = 0, *Z = 0;
2922
2923      if (A == C) {
2924        X = B; Y = D; Z = A;
2925      } else if (A == D) {
2926        X = B; Y = C; Z = A;
2927      } else if (B == C) {
2928        X = A; Y = D; Z = B;
2929      } else if (B == D) {
2930        X = A; Y = C; Z = B;
2931      }
2932
2933      if (X) {   // Build (X^Y) & Z
2934        Op1 = Builder->CreateXor(X, Y);
2935        Op1 = Builder->CreateAnd(Op1, Z);
2936        I.setOperand(0, Op1);
2937        I.setOperand(1, Constant::getNullValue(Op1->getType()));
2938        return &I;
2939      }
2940    }
2941
2942    // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
2943    // and       (B & (1<<X)-1) == (zext A) --> A == (trunc B)
2944    ConstantInt *Cst1;
2945    if ((Op0->hasOneUse() &&
2946         match(Op0, m_ZExt(m_Value(A))) &&
2947         match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
2948        (Op1->hasOneUse() &&
2949         match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
2950         match(Op1, m_ZExt(m_Value(A))))) {
2951      APInt Pow2 = Cst1->getValue() + 1;
2952      if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
2953          Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
2954        return new ICmpInst(I.getPredicate(), A,
2955                            Builder->CreateTrunc(B, A->getType()));
2956    }
2957
2958    // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
2959    // For lshr and ashr pairs.
2960    if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2961         match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
2962        (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
2963         match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
2964      unsigned TypeBits = Cst1->getBitWidth();
2965      unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
2966      if (ShAmt < TypeBits && ShAmt != 0) {
2967        ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
2968                                       ? ICmpInst::ICMP_UGE
2969                                       : ICmpInst::ICMP_ULT;
2970        Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
2971        APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
2972        return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
2973      }
2974    }
2975
2976    // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
2977    // "icmp (and X, mask), cst"
2978    uint64_t ShAmt = 0;
2979    if (Op0->hasOneUse() &&
2980        match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
2981                                           m_ConstantInt(ShAmt))))) &&
2982        match(Op1, m_ConstantInt(Cst1)) &&
2983        // Only do this when A has multiple uses.  This is most important to do
2984        // when it exposes other optimizations.
2985        !A->hasOneUse()) {
2986      unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
2987
2988      if (ShAmt < ASize) {
2989        APInt MaskV =
2990          APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
2991        MaskV <<= ShAmt;
2992
2993        APInt CmpV = Cst1->getValue().zext(ASize);
2994        CmpV <<= ShAmt;
2995
2996        Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
2997        return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
2998      }
2999    }
3000  }
3001
3002  {
3003    Value *X; ConstantInt *Cst;
3004    // icmp X+Cst, X
3005    if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
3006      return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
3007
3008    // icmp X, X+Cst
3009    if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
3010      return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
3011  }
3012  return Changed ? &I : 0;
3013}
3014
3015/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
3016///
3017Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
3018                                                Instruction *LHSI,
3019                                                Constant *RHSC) {
3020  if (!isa<ConstantFP>(RHSC)) return 0;
3021  const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
3022
3023  // Get the width of the mantissa.  We don't want to hack on conversions that
3024  // might lose information from the integer, e.g. "i64 -> float"
3025  int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
3026  if (MantissaWidth == -1) return 0;  // Unknown.
3027
3028  // Check to see that the input is converted from an integer type that is small
3029  // enough that preserves all bits.  TODO: check here for "known" sign bits.
3030  // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
3031  unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
3032
3033  // If this is a uitofp instruction, we need an extra bit to hold the sign.
3034  bool LHSUnsigned = isa<UIToFPInst>(LHSI);
3035  if (LHSUnsigned)
3036    ++InputSize;
3037
3038  // If the conversion would lose info, don't hack on this.
3039  if ((int)InputSize > MantissaWidth)
3040    return 0;
3041
3042  // Otherwise, we can potentially simplify the comparison.  We know that it
3043  // will always come through as an integer value and we know the constant is
3044  // not a NAN (it would have been previously simplified).
3045  assert(!RHS.isNaN() && "NaN comparison not already folded!");
3046
3047  ICmpInst::Predicate Pred;
3048  switch (I.getPredicate()) {
3049  default: llvm_unreachable("Unexpected predicate!");
3050  case FCmpInst::FCMP_UEQ:
3051  case FCmpInst::FCMP_OEQ:
3052    Pred = ICmpInst::ICMP_EQ;
3053    break;
3054  case FCmpInst::FCMP_UGT:
3055  case FCmpInst::FCMP_OGT:
3056    Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
3057    break;
3058  case FCmpInst::FCMP_UGE:
3059  case FCmpInst::FCMP_OGE:
3060    Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
3061    break;
3062  case FCmpInst::FCMP_ULT:
3063  case FCmpInst::FCMP_OLT:
3064    Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
3065    break;
3066  case FCmpInst::FCMP_ULE:
3067  case FCmpInst::FCMP_OLE:
3068    Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
3069    break;
3070  case FCmpInst::FCMP_UNE:
3071  case FCmpInst::FCMP_ONE:
3072    Pred = ICmpInst::ICMP_NE;
3073    break;
3074  case FCmpInst::FCMP_ORD:
3075    return ReplaceInstUsesWith(I, Builder->getTrue());
3076  case FCmpInst::FCMP_UNO:
3077    return ReplaceInstUsesWith(I, Builder->getFalse());
3078  }
3079
3080  IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
3081
3082  // Now we know that the APFloat is a normal number, zero or inf.
3083
3084  // See if the FP constant is too large for the integer.  For example,
3085  // comparing an i8 to 300.0.
3086  unsigned IntWidth = IntTy->getScalarSizeInBits();
3087
3088  if (!LHSUnsigned) {
3089    // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
3090    // and large values.
3091    APFloat SMax(RHS.getSemantics());
3092    SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
3093                          APFloat::rmNearestTiesToEven);
3094    if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
3095      if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
3096          Pred == ICmpInst::ICMP_SLE)
3097        return ReplaceInstUsesWith(I, Builder->getTrue());
3098      return ReplaceInstUsesWith(I, Builder->getFalse());
3099    }
3100  } else {
3101    // If the RHS value is > UnsignedMax, fold the comparison. This handles
3102    // +INF and large values.
3103    APFloat UMax(RHS.getSemantics());
3104    UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
3105                          APFloat::rmNearestTiesToEven);
3106    if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
3107      if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
3108          Pred == ICmpInst::ICMP_ULE)
3109        return ReplaceInstUsesWith(I, Builder->getTrue());
3110      return ReplaceInstUsesWith(I, Builder->getFalse());
3111    }
3112  }
3113
3114  if (!LHSUnsigned) {
3115    // See if the RHS value is < SignedMin.
3116    APFloat SMin(RHS.getSemantics());
3117    SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
3118                          APFloat::rmNearestTiesToEven);
3119    if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
3120      if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
3121          Pred == ICmpInst::ICMP_SGE)
3122        return ReplaceInstUsesWith(I, Builder->getTrue());
3123      return ReplaceInstUsesWith(I, Builder->getFalse());
3124    }
3125  } else {
3126    // See if the RHS value is < UnsignedMin.
3127    APFloat SMin(RHS.getSemantics());
3128    SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
3129                          APFloat::rmNearestTiesToEven);
3130    if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
3131      if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
3132          Pred == ICmpInst::ICMP_UGE)
3133        return ReplaceInstUsesWith(I, Builder->getTrue());
3134      return ReplaceInstUsesWith(I, Builder->getFalse());
3135    }
3136  }
3137
3138  // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
3139  // [0, UMAX], but it may still be fractional.  See if it is fractional by
3140  // casting the FP value to the integer value and back, checking for equality.
3141  // Don't do this for zero, because -0.0 is not fractional.
3142  Constant *RHSInt = LHSUnsigned
3143    ? ConstantExpr::getFPToUI(RHSC, IntTy)
3144    : ConstantExpr::getFPToSI(RHSC, IntTy);
3145  if (!RHS.isZero()) {
3146    bool Equal = LHSUnsigned
3147      ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
3148      : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
3149    if (!Equal) {
3150      // If we had a comparison against a fractional value, we have to adjust
3151      // the compare predicate and sometimes the value.  RHSC is rounded towards
3152      // zero at this point.
3153      switch (Pred) {
3154      default: llvm_unreachable("Unexpected integer comparison!");
3155      case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
3156        return ReplaceInstUsesWith(I, Builder->getTrue());
3157      case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
3158        return ReplaceInstUsesWith(I, Builder->getFalse());
3159      case ICmpInst::ICMP_ULE:
3160        // (float)int <= 4.4   --> int <= 4
3161        // (float)int <= -4.4  --> false
3162        if (RHS.isNegative())
3163          return ReplaceInstUsesWith(I, Builder->getFalse());
3164        break;
3165      case ICmpInst::ICMP_SLE:
3166        // (float)int <= 4.4   --> int <= 4
3167        // (float)int <= -4.4  --> int < -4
3168        if (RHS.isNegative())
3169          Pred = ICmpInst::ICMP_SLT;
3170        break;
3171      case ICmpInst::ICMP_ULT:
3172        // (float)int < -4.4   --> false
3173        // (float)int < 4.4    --> int <= 4
3174        if (RHS.isNegative())
3175          return ReplaceInstUsesWith(I, Builder->getFalse());
3176        Pred = ICmpInst::ICMP_ULE;
3177        break;
3178      case ICmpInst::ICMP_SLT:
3179        // (float)int < -4.4   --> int < -4
3180        // (float)int < 4.4    --> int <= 4
3181        if (!RHS.isNegative())
3182          Pred = ICmpInst::ICMP_SLE;
3183        break;
3184      case ICmpInst::ICMP_UGT:
3185        // (float)int > 4.4    --> int > 4
3186        // (float)int > -4.4   --> true
3187        if (RHS.isNegative())
3188          return ReplaceInstUsesWith(I, Builder->getTrue());
3189        break;
3190      case ICmpInst::ICMP_SGT:
3191        // (float)int > 4.4    --> int > 4
3192        // (float)int > -4.4   --> int >= -4
3193        if (RHS.isNegative())
3194          Pred = ICmpInst::ICMP_SGE;
3195        break;
3196      case ICmpInst::ICMP_UGE:
3197        // (float)int >= -4.4   --> true
3198        // (float)int >= 4.4    --> int > 4
3199        if (RHS.isNegative())
3200          return ReplaceInstUsesWith(I, Builder->getTrue());
3201        Pred = ICmpInst::ICMP_UGT;
3202        break;
3203      case ICmpInst::ICMP_SGE:
3204        // (float)int >= -4.4   --> int >= -4
3205        // (float)int >= 4.4    --> int > 4
3206        if (!RHS.isNegative())
3207          Pred = ICmpInst::ICMP_SGT;
3208        break;
3209      }
3210    }
3211  }
3212
3213  // Lower this FP comparison into an appropriate integer version of the
3214  // comparison.
3215  return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
3216}
3217
3218Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
3219  bool Changed = false;
3220
3221  /// Orders the operands of the compare so that they are listed from most
3222  /// complex to least complex.  This puts constants before unary operators,
3223  /// before binary operators.
3224  if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
3225    I.swapOperands();
3226    Changed = true;
3227  }
3228
3229  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3230
3231  if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, DL))
3232    return ReplaceInstUsesWith(I, V);
3233
3234  // Simplify 'fcmp pred X, X'
3235  if (Op0 == Op1) {
3236    switch (I.getPredicate()) {
3237    default: llvm_unreachable("Unknown predicate!");
3238    case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
3239    case FCmpInst::FCMP_ULT:    // True if unordered or less than
3240    case FCmpInst::FCMP_UGT:    // True if unordered or greater than
3241    case FCmpInst::FCMP_UNE:    // True if unordered or not equal
3242      // Canonicalize these to be 'fcmp uno %X, 0.0'.
3243      I.setPredicate(FCmpInst::FCMP_UNO);
3244      I.setOperand(1, Constant::getNullValue(Op0->getType()));
3245      return &I;
3246
3247    case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
3248    case FCmpInst::FCMP_OEQ:    // True if ordered and equal
3249    case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
3250    case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
3251      // Canonicalize these to be 'fcmp ord %X, 0.0'.
3252      I.setPredicate(FCmpInst::FCMP_ORD);
3253      I.setOperand(1, Constant::getNullValue(Op0->getType()));
3254      return &I;
3255    }
3256  }
3257
3258  // Handle fcmp with constant RHS
3259  if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3260    if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3261      switch (LHSI->getOpcode()) {
3262      case Instruction::FPExt: {
3263        // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
3264        FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
3265        ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
3266        if (!RHSF)
3267          break;
3268
3269        const fltSemantics *Sem;
3270        // FIXME: This shouldn't be here.
3271        if (LHSExt->getSrcTy()->isHalfTy())
3272          Sem = &APFloat::IEEEhalf;
3273        else if (LHSExt->getSrcTy()->isFloatTy())
3274          Sem = &APFloat::IEEEsingle;
3275        else if (LHSExt->getSrcTy()->isDoubleTy())
3276          Sem = &APFloat::IEEEdouble;
3277        else if (LHSExt->getSrcTy()->isFP128Ty())
3278          Sem = &APFloat::IEEEquad;
3279        else if (LHSExt->getSrcTy()->isX86_FP80Ty())
3280          Sem = &APFloat::x87DoubleExtended;
3281        else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
3282          Sem = &APFloat::PPCDoubleDouble;
3283        else
3284          break;
3285
3286        bool Lossy;
3287        APFloat F = RHSF->getValueAPF();
3288        F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
3289
3290        // Avoid lossy conversions and denormals. Zero is a special case
3291        // that's OK to convert.
3292        APFloat Fabs = F;
3293        Fabs.clearSign();
3294        if (!Lossy &&
3295            ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
3296                 APFloat::cmpLessThan) || Fabs.isZero()))
3297
3298          return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3299                              ConstantFP::get(RHSC->getContext(), F));
3300        break;
3301      }
3302      case Instruction::PHI:
3303        // Only fold fcmp into the PHI if the phi and fcmp are in the same
3304        // block.  If in the same block, we're encouraging jump threading.  If
3305        // not, we are just pessimizing the code by making an i1 phi.
3306        if (LHSI->getParent() == I.getParent())
3307          if (Instruction *NV = FoldOpIntoPhi(I))
3308            return NV;
3309        break;
3310      case Instruction::SIToFP:
3311      case Instruction::UIToFP:
3312        if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
3313          return NV;
3314        break;
3315      case Instruction::FSub: {
3316        // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
3317        Value *Op;
3318        if (match(LHSI, m_FNeg(m_Value(Op))))
3319          return new FCmpInst(I.getSwappedPredicate(), Op,
3320                              ConstantExpr::getFNeg(RHSC));
3321        break;
3322      }
3323      case Instruction::Load:
3324        if (GetElementPtrInst *GEP =
3325            dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
3326          if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3327            if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
3328                !cast<LoadInst>(LHSI)->isVolatile())
3329              if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
3330                return Res;
3331        }
3332        break;
3333      case Instruction::Call: {
3334        CallInst *CI = cast<CallInst>(LHSI);
3335        LibFunc::Func Func;
3336        // Various optimization for fabs compared with zero.
3337        if (RHSC->isNullValue() && CI->getCalledFunction() &&
3338            TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
3339            TLI->has(Func)) {
3340          if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
3341              Func == LibFunc::fabsl) {
3342            switch (I.getPredicate()) {
3343            default: break;
3344            // fabs(x) < 0 --> false
3345            case FCmpInst::FCMP_OLT:
3346              return ReplaceInstUsesWith(I, Builder->getFalse());
3347            // fabs(x) > 0 --> x != 0
3348            case FCmpInst::FCMP_OGT:
3349              return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
3350                                  RHSC);
3351            // fabs(x) <= 0 --> x == 0
3352            case FCmpInst::FCMP_OLE:
3353              return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
3354                                  RHSC);
3355            // fabs(x) >= 0 --> !isnan(x)
3356            case FCmpInst::FCMP_OGE:
3357              return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
3358                                  RHSC);
3359            // fabs(x) == 0 --> x == 0
3360            // fabs(x) != 0 --> x != 0
3361            case FCmpInst::FCMP_OEQ:
3362            case FCmpInst::FCMP_UEQ:
3363            case FCmpInst::FCMP_ONE:
3364            case FCmpInst::FCMP_UNE:
3365              return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
3366                                  RHSC);
3367            }
3368          }
3369        }
3370      }
3371      }
3372  }
3373
3374  // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
3375  Value *X, *Y;
3376  if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
3377    return new FCmpInst(I.getSwappedPredicate(), X, Y);
3378
3379  // fcmp (fpext x), (fpext y) -> fcmp x, y
3380  if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
3381    if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
3382      if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
3383        return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
3384                            RHSExt->getOperand(0));
3385
3386  return Changed ? &I : 0;
3387}
3388