LLVM API Documentation

InstCombineCompares.cpp
Go to the documentation of this file.
00001 //===- InstCombineCompares.cpp --------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visitICmp and visitFCmp functions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombine.h"
00015 #include "llvm/Analysis/ConstantFolding.h"
00016 #include "llvm/Analysis/InstructionSimplify.h"
00017 #include "llvm/Analysis/MemoryBuiltins.h"
00018 #include "llvm/IR/ConstantRange.h"
00019 #include "llvm/IR/DataLayout.h"
00020 #include "llvm/IR/GetElementPtrTypeIterator.h"
00021 #include "llvm/IR/IntrinsicInst.h"
00022 #include "llvm/IR/PatternMatch.h"
00023 #include "llvm/Target/TargetLibraryInfo.h"
00024 using namespace llvm;
00025 using namespace PatternMatch;
00026 
00027 #define DEBUG_TYPE "instcombine"
00028 
00029 static ConstantInt *getOne(Constant *C) {
00030   return ConstantInt::get(cast<IntegerType>(C->getType()), 1);
00031 }
00032 
00033 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
00034   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
00035 }
00036 
00037 static bool HasAddOverflow(ConstantInt *Result,
00038                            ConstantInt *In1, ConstantInt *In2,
00039                            bool IsSigned) {
00040   if (!IsSigned)
00041     return Result->getValue().ult(In1->getValue());
00042 
00043   if (In2->isNegative())
00044     return Result->getValue().sgt(In1->getValue());
00045   return Result->getValue().slt(In1->getValue());
00046 }
00047 
00048 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
00049 /// overflowed for this type.
00050 static bool AddWithOverflow(Constant *&Result, Constant *In1,
00051                             Constant *In2, bool IsSigned = false) {
00052   Result = ConstantExpr::getAdd(In1, In2);
00053 
00054   if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
00055     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
00056       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
00057       if (HasAddOverflow(ExtractElement(Result, Idx),
00058                          ExtractElement(In1, Idx),
00059                          ExtractElement(In2, Idx),
00060                          IsSigned))
00061         return true;
00062     }
00063     return false;
00064   }
00065 
00066   return HasAddOverflow(cast<ConstantInt>(Result),
00067                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
00068                         IsSigned);
00069 }
00070 
00071 static bool HasSubOverflow(ConstantInt *Result,
00072                            ConstantInt *In1, ConstantInt *In2,
00073                            bool IsSigned) {
00074   if (!IsSigned)
00075     return Result->getValue().ugt(In1->getValue());
00076 
00077   if (In2->isNegative())
00078     return Result->getValue().slt(In1->getValue());
00079 
00080   return Result->getValue().sgt(In1->getValue());
00081 }
00082 
00083 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
00084 /// overflowed for this type.
00085 static bool SubWithOverflow(Constant *&Result, Constant *In1,
00086                             Constant *In2, bool IsSigned = false) {
00087   Result = ConstantExpr::getSub(In1, In2);
00088 
00089   if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
00090     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
00091       Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
00092       if (HasSubOverflow(ExtractElement(Result, Idx),
00093                          ExtractElement(In1, Idx),
00094                          ExtractElement(In2, Idx),
00095                          IsSigned))
00096         return true;
00097     }
00098     return false;
00099   }
00100 
00101   return HasSubOverflow(cast<ConstantInt>(Result),
00102                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
00103                         IsSigned);
00104 }
00105 
00106 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
00107 /// comparison only checks the sign bit.  If it only checks the sign bit, set
00108 /// TrueIfSigned if the result of the comparison is true when the input value is
00109 /// signed.
00110 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
00111                            bool &TrueIfSigned) {
00112   switch (pred) {
00113   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
00114     TrueIfSigned = true;
00115     return RHS->isZero();
00116   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
00117     TrueIfSigned = true;
00118     return RHS->isAllOnesValue();
00119   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
00120     TrueIfSigned = false;
00121     return RHS->isAllOnesValue();
00122   case ICmpInst::ICMP_UGT:
00123     // True if LHS u> RHS and RHS == high-bit-mask - 1
00124     TrueIfSigned = true;
00125     return RHS->isMaxValue(true);
00126   case ICmpInst::ICMP_UGE:
00127     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
00128     TrueIfSigned = true;
00129     return RHS->getValue().isSignBit();
00130   default:
00131     return false;
00132   }
00133 }
00134 
00135 /// Returns true if the exploded icmp can be expressed as a signed comparison
00136 /// to zero and updates the predicate accordingly.
00137 /// The signedness of the comparison is preserved.
00138 static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) {
00139   if (!ICmpInst::isSigned(pred))
00140     return false;
00141 
00142   if (RHS->isZero())
00143     return ICmpInst::isRelational(pred);
00144 
00145   if (RHS->isOne()) {
00146     if (pred == ICmpInst::ICMP_SLT) {
00147       pred = ICmpInst::ICMP_SLE;
00148       return true;
00149     }
00150   } else if (RHS->isAllOnesValue()) {
00151     if (pred == ICmpInst::ICMP_SGT) {
00152       pred = ICmpInst::ICMP_SGE;
00153       return true;
00154     }
00155   }
00156 
00157   return false;
00158 }
00159 
00160 // isHighOnes - Return true if the constant is of the form 1+0+.
00161 // This is the same as lowones(~X).
00162 static bool isHighOnes(const ConstantInt *CI) {
00163   return (~CI->getValue() + 1).isPowerOf2();
00164 }
00165 
00166 /// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
00167 /// set of known zero and one bits, compute the maximum and minimum values that
00168 /// could have the specified known zero and known one bits, returning them in
00169 /// min/max.
00170 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
00171                                                    const APInt& KnownOne,
00172                                                    APInt& Min, APInt& Max) {
00173   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
00174          KnownZero.getBitWidth() == Min.getBitWidth() &&
00175          KnownZero.getBitWidth() == Max.getBitWidth() &&
00176          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
00177   APInt UnknownBits = ~(KnownZero|KnownOne);
00178 
00179   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
00180   // bit if it is unknown.
00181   Min = KnownOne;
00182   Max = KnownOne|UnknownBits;
00183 
00184   if (UnknownBits.isNegative()) { // Sign bit is unknown
00185     Min.setBit(Min.getBitWidth()-1);
00186     Max.clearBit(Max.getBitWidth()-1);
00187   }
00188 }
00189 
00190 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
00191 // a set of known zero and one bits, compute the maximum and minimum values that
00192 // could have the specified known zero and known one bits, returning them in
00193 // min/max.
00194 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
00195                                                      const APInt &KnownOne,
00196                                                      APInt &Min, APInt &Max) {
00197   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
00198          KnownZero.getBitWidth() == Min.getBitWidth() &&
00199          KnownZero.getBitWidth() == Max.getBitWidth() &&
00200          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
00201   APInt UnknownBits = ~(KnownZero|KnownOne);
00202 
00203   // The minimum value is when the unknown bits are all zeros.
00204   Min = KnownOne;
00205   // The maximum value is when the unknown bits are all ones.
00206   Max = KnownOne|UnknownBits;
00207 }
00208 
00209 
00210 
00211 /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
00212 ///   cmp pred (load (gep GV, ...)), cmpcst
00213 /// where GV is a global variable with a constant initializer.  Try to simplify
00214 /// this into some simple computation that does not need the load.  For example
00215 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
00216 ///
00217 /// If AndCst is non-null, then the loaded value is masked with that constant
00218 /// before doing the comparison.  This handles cases like "A[i]&4 == 0".
00219 Instruction *InstCombiner::
00220 FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
00221                              CmpInst &ICI, ConstantInt *AndCst) {
00222   // We need TD information to know the pointer size unless this is inbounds.
00223   if (!GEP->isInBounds() && DL == 0)
00224     return 0;
00225 
00226   Constant *Init = GV->getInitializer();
00227   if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
00228     return 0;
00229 
00230   uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
00231   if (ArrayElementCount > 1024) return 0;  // Don't blow up on huge arrays.
00232 
00233   // There are many forms of this optimization we can handle, for now, just do
00234   // the simple index into a single-dimensional array.
00235   //
00236   // Require: GEP GV, 0, i {{, constant indices}}
00237   if (GEP->getNumOperands() < 3 ||
00238       !isa<ConstantInt>(GEP->getOperand(1)) ||
00239       !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
00240       isa<Constant>(GEP->getOperand(2)))
00241     return 0;
00242 
00243   // Check that indices after the variable are constants and in-range for the
00244   // type they index.  Collect the indices.  This is typically for arrays of
00245   // structs.
00246   SmallVector<unsigned, 4> LaterIndices;
00247 
00248   Type *EltTy = Init->getType()->getArrayElementType();
00249   for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
00250     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
00251     if (Idx == 0) return 0;  // Variable index.
00252 
00253     uint64_t IdxVal = Idx->getZExtValue();
00254     if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
00255 
00256     if (StructType *STy = dyn_cast<StructType>(EltTy))
00257       EltTy = STy->getElementType(IdxVal);
00258     else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
00259       if (IdxVal >= ATy->getNumElements()) return 0;
00260       EltTy = ATy->getElementType();
00261     } else {
00262       return 0; // Unknown type.
00263     }
00264 
00265     LaterIndices.push_back(IdxVal);
00266   }
00267 
00268   enum { Overdefined = -3, Undefined = -2 };
00269 
00270   // Variables for our state machines.
00271 
00272   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
00273   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
00274   // and 87 is the second (and last) index.  FirstTrueElement is -2 when
00275   // undefined, otherwise set to the first true element.  SecondTrueElement is
00276   // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
00277   int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
00278 
00279   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
00280   // form "i != 47 & i != 87".  Same state transitions as for true elements.
00281   int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
00282 
00283   /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
00284   /// define a state machine that triggers for ranges of values that the index
00285   /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
00286   /// This is -2 when undefined, -3 when overdefined, and otherwise the last
00287   /// index in the range (inclusive).  We use -2 for undefined here because we
00288   /// use relative comparisons and don't want 0-1 to match -1.
00289   int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
00290 
00291   // MagicBitvector - This is a magic bitvector where we set a bit if the
00292   // comparison is true for element 'i'.  If there are 64 elements or less in
00293   // the array, this will fully represent all the comparison results.
00294   uint64_t MagicBitvector = 0;
00295 
00296 
00297   // Scan the array and see if one of our patterns matches.
00298   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
00299   for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
00300     Constant *Elt = Init->getAggregateElement(i);
00301     if (Elt == 0) return 0;
00302 
00303     // If this is indexing an array of structures, get the structure element.
00304     if (!LaterIndices.empty())
00305       Elt = ConstantExpr::getExtractValue(Elt, LaterIndices);
00306 
00307     // If the element is masked, handle it.
00308     if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
00309 
00310     // Find out if the comparison would be true or false for the i'th element.
00311     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
00312                                                   CompareRHS, DL, TLI);
00313     // If the result is undef for this element, ignore it.
00314     if (isa<UndefValue>(C)) {
00315       // Extend range state machines to cover this element in case there is an
00316       // undef in the middle of the range.
00317       if (TrueRangeEnd == (int)i-1)
00318         TrueRangeEnd = i;
00319       if (FalseRangeEnd == (int)i-1)
00320         FalseRangeEnd = i;
00321       continue;
00322     }
00323 
00324     // If we can't compute the result for any of the elements, we have to give
00325     // up evaluating the entire conditional.
00326     if (!isa<ConstantInt>(C)) return 0;
00327 
00328     // Otherwise, we know if the comparison is true or false for this element,
00329     // update our state machines.
00330     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
00331 
00332     // State machine for single/double/range index comparison.
00333     if (IsTrueForElt) {
00334       // Update the TrueElement state machine.
00335       if (FirstTrueElement == Undefined)
00336         FirstTrueElement = TrueRangeEnd = i;  // First true element.
00337       else {
00338         // Update double-compare state machine.
00339         if (SecondTrueElement == Undefined)
00340           SecondTrueElement = i;
00341         else
00342           SecondTrueElement = Overdefined;
00343 
00344         // Update range state machine.
00345         if (TrueRangeEnd == (int)i-1)
00346           TrueRangeEnd = i;
00347         else
00348           TrueRangeEnd = Overdefined;
00349       }
00350     } else {
00351       // Update the FalseElement state machine.
00352       if (FirstFalseElement == Undefined)
00353         FirstFalseElement = FalseRangeEnd = i; // First false element.
00354       else {
00355         // Update double-compare state machine.
00356         if (SecondFalseElement == Undefined)
00357           SecondFalseElement = i;
00358         else
00359           SecondFalseElement = Overdefined;
00360 
00361         // Update range state machine.
00362         if (FalseRangeEnd == (int)i-1)
00363           FalseRangeEnd = i;
00364         else
00365           FalseRangeEnd = Overdefined;
00366       }
00367     }
00368 
00369 
00370     // If this element is in range, update our magic bitvector.
00371     if (i < 64 && IsTrueForElt)
00372       MagicBitvector |= 1ULL << i;
00373 
00374     // If all of our states become overdefined, bail out early.  Since the
00375     // predicate is expensive, only check it every 8 elements.  This is only
00376     // really useful for really huge arrays.
00377     if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
00378         SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
00379         FalseRangeEnd == Overdefined)
00380       return 0;
00381   }
00382 
00383   // Now that we've scanned the entire array, emit our new comparison(s).  We
00384   // order the state machines in complexity of the generated code.
00385   Value *Idx = GEP->getOperand(2);
00386 
00387   // If the index is larger than the pointer size of the target, truncate the
00388   // index down like the GEP would do implicitly.  We don't have to do this for
00389   // an inbounds GEP because the index can't be out of range.
00390   if (!GEP->isInBounds()) {
00391     Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
00392     unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
00393     if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize)
00394       Idx = Builder->CreateTrunc(Idx, IntPtrTy);
00395   }
00396 
00397   // If the comparison is only true for one or two elements, emit direct
00398   // comparisons.
00399   if (SecondTrueElement != Overdefined) {
00400     // None true -> false.
00401     if (FirstTrueElement == Undefined)
00402       return ReplaceInstUsesWith(ICI, Builder->getFalse());
00403 
00404     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
00405 
00406     // True for one element -> 'i == 47'.
00407     if (SecondTrueElement == Undefined)
00408       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
00409 
00410     // True for two elements -> 'i == 47 | i == 72'.
00411     Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
00412     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
00413     Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
00414     return BinaryOperator::CreateOr(C1, C2);
00415   }
00416 
00417   // If the comparison is only false for one or two elements, emit direct
00418   // comparisons.
00419   if (SecondFalseElement != Overdefined) {
00420     // None false -> true.
00421     if (FirstFalseElement == Undefined)
00422       return ReplaceInstUsesWith(ICI, Builder->getTrue());
00423 
00424     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
00425 
00426     // False for one element -> 'i != 47'.
00427     if (SecondFalseElement == Undefined)
00428       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
00429 
00430     // False for two elements -> 'i != 47 & i != 72'.
00431     Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
00432     Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
00433     Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
00434     return BinaryOperator::CreateAnd(C1, C2);
00435   }
00436 
00437   // If the comparison can be replaced with a range comparison for the elements
00438   // where it is true, emit the range check.
00439   if (TrueRangeEnd != Overdefined) {
00440     assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
00441 
00442     // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
00443     if (FirstTrueElement) {
00444       Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
00445       Idx = Builder->CreateAdd(Idx, Offs);
00446     }
00447 
00448     Value *End = ConstantInt::get(Idx->getType(),
00449                                   TrueRangeEnd-FirstTrueElement+1);
00450     return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
00451   }
00452 
00453   // False range check.
00454   if (FalseRangeEnd != Overdefined) {
00455     assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
00456     // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
00457     if (FirstFalseElement) {
00458       Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
00459       Idx = Builder->CreateAdd(Idx, Offs);
00460     }
00461 
00462     Value *End = ConstantInt::get(Idx->getType(),
00463                                   FalseRangeEnd-FirstFalseElement);
00464     return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
00465   }
00466 
00467 
00468   // If a magic bitvector captures the entire comparison state
00469   // of this load, replace it with computation that does:
00470   //   ((magic_cst >> i) & 1) != 0
00471   {
00472     Type *Ty = 0;
00473 
00474     // Look for an appropriate type:
00475     // - The type of Idx if the magic fits
00476     // - The smallest fitting legal type if we have a DataLayout
00477     // - Default to i32
00478     if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
00479       Ty = Idx->getType();
00480     else if (DL)
00481       Ty = DL->getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
00482     else if (ArrayElementCount <= 32)
00483       Ty = Type::getInt32Ty(Init->getContext());
00484 
00485     if (Ty != 0) {
00486       Value *V = Builder->CreateIntCast(Idx, Ty, false);
00487       V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
00488       V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
00489       return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
00490     }
00491   }
00492 
00493   return 0;
00494 }
00495 
00496 
00497 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
00498 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
00499 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
00500 /// be complex, and scales are involved.  The above expression would also be
00501 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
00502 /// This later form is less amenable to optimization though, and we are allowed
00503 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
00504 ///
00505 /// If we can't emit an optimized form for this expression, this returns null.
00506 ///
00507 static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) {
00508   const DataLayout &DL = *IC.getDataLayout();
00509   gep_type_iterator GTI = gep_type_begin(GEP);
00510 
00511   // Check to see if this gep only has a single variable index.  If so, and if
00512   // any constant indices are a multiple of its scale, then we can compute this
00513   // in terms of the scale of the variable index.  For example, if the GEP
00514   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
00515   // because the expression will cross zero at the same point.
00516   unsigned i, e = GEP->getNumOperands();
00517   int64_t Offset = 0;
00518   for (i = 1; i != e; ++i, ++GTI) {
00519     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
00520       // Compute the aggregate offset of constant indices.
00521       if (CI->isZero()) continue;
00522 
00523       // Handle a struct index, which adds its field offset to the pointer.
00524       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00525         Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
00526       } else {
00527         uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
00528         Offset += Size*CI->getSExtValue();
00529       }
00530     } else {
00531       // Found our variable index.
00532       break;
00533     }
00534   }
00535 
00536   // If there are no variable indices, we must have a constant offset, just
00537   // evaluate it the general way.
00538   if (i == e) return 0;
00539 
00540   Value *VariableIdx = GEP->getOperand(i);
00541   // Determine the scale factor of the variable element.  For example, this is
00542   // 4 if the variable index is into an array of i32.
00543   uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
00544 
00545   // Verify that there are no other variable indices.  If so, emit the hard way.
00546   for (++i, ++GTI; i != e; ++i, ++GTI) {
00547     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
00548     if (!CI) return 0;
00549 
00550     // Compute the aggregate offset of constant indices.
00551     if (CI->isZero()) continue;
00552 
00553     // Handle a struct index, which adds its field offset to the pointer.
00554     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00555       Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
00556     } else {
00557       uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
00558       Offset += Size*CI->getSExtValue();
00559     }
00560   }
00561 
00562 
00563 
00564   // Okay, we know we have a single variable index, which must be a
00565   // pointer/array/vector index.  If there is no offset, life is simple, return
00566   // the index.
00567   Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
00568   unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
00569   if (Offset == 0) {
00570     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
00571     // we don't need to bother extending: the extension won't affect where the
00572     // computation crosses zero.
00573     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) {
00574       VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy);
00575     }
00576     return VariableIdx;
00577   }
00578 
00579   // Otherwise, there is an index.  The computation we will do will be modulo
00580   // the pointer size, so get it.
00581   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
00582 
00583   Offset &= PtrSizeMask;
00584   VariableScale &= PtrSizeMask;
00585 
00586   // To do this transformation, any constant index must be a multiple of the
00587   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
00588   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
00589   // multiple of the variable scale.
00590   int64_t NewOffs = Offset / (int64_t)VariableScale;
00591   if (Offset != NewOffs*(int64_t)VariableScale)
00592     return 0;
00593 
00594   // Okay, we can do this evaluation.  Start by converting the index to intptr.
00595   if (VariableIdx->getType() != IntPtrTy)
00596     VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy,
00597                                             true /*Signed*/);
00598   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
00599   return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset");
00600 }
00601 
00602 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
00603 /// else.  At this point we know that the GEP is on the LHS of the comparison.
00604 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
00605                                        ICmpInst::Predicate Cond,
00606                                        Instruction &I) {
00607   // Don't transform signed compares of GEPs into index compares. Even if the
00608   // GEP is inbounds, the final add of the base pointer can have signed overflow
00609   // and would change the result of the icmp.
00610   // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
00611   // the maximum signed value for the pointer type.
00612   if (ICmpInst::isSigned(Cond))
00613     return 0;
00614 
00615   // Look through bitcasts.
00616   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
00617     RHS = BCI->getOperand(0);
00618 
00619   Value *PtrBase = GEPLHS->getOperand(0);
00620   if (DL && PtrBase == RHS && GEPLHS->isInBounds()) {
00621     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
00622     // This transformation (ignoring the base and scales) is valid because we
00623     // know pointers can't overflow since the gep is inbounds.  See if we can
00624     // output an optimized form.
00625     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this);
00626 
00627     // If not, synthesize the offset the hard way.
00628     if (Offset == 0)
00629       Offset = EmitGEPOffset(GEPLHS);
00630     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
00631                         Constant::getNullValue(Offset->getType()));
00632   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
00633     // If the base pointers are different, but the indices are the same, just
00634     // compare the base pointer.
00635     if (PtrBase != GEPRHS->getOperand(0)) {
00636       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
00637       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
00638                         GEPRHS->getOperand(0)->getType();
00639       if (IndicesTheSame)
00640         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
00641           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
00642             IndicesTheSame = false;
00643             break;
00644           }
00645 
00646       // If all indices are the same, just compare the base pointers.
00647       if (IndicesTheSame)
00648         return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
00649 
00650       // If we're comparing GEPs with two base pointers that only differ in type
00651       // and both GEPs have only constant indices or just one use, then fold
00652       // the compare with the adjusted indices.
00653       if (DL && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
00654           (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
00655           (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
00656           PtrBase->stripPointerCasts() ==
00657             GEPRHS->getOperand(0)->stripPointerCasts()) {
00658         Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond),
00659                                          EmitGEPOffset(GEPLHS),
00660                                          EmitGEPOffset(GEPRHS));
00661         return ReplaceInstUsesWith(I, Cmp);
00662       }
00663 
00664       // Otherwise, the base pointers are different and the indices are
00665       // different, bail out.
00666       return 0;
00667     }
00668 
00669     // If one of the GEPs has all zero indices, recurse.
00670     bool AllZeros = true;
00671     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
00672       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
00673           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
00674         AllZeros = false;
00675         break;
00676       }
00677     if (AllZeros)
00678       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
00679                          ICmpInst::getSwappedPredicate(Cond), I);
00680 
00681     // If the other GEP has all zero indices, recurse.
00682     AllZeros = true;
00683     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
00684       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
00685           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
00686         AllZeros = false;
00687         break;
00688       }
00689     if (AllZeros)
00690       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
00691 
00692     bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
00693     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
00694       // If the GEPs only differ by one index, compare it.
00695       unsigned NumDifferences = 0;  // Keep track of # differences.
00696       unsigned DiffOperand = 0;     // The operand that differs.
00697       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
00698         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
00699           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
00700                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
00701             // Irreconcilable differences.
00702             NumDifferences = 2;
00703             break;
00704           } else {
00705             if (NumDifferences++) break;
00706             DiffOperand = i;
00707           }
00708         }
00709 
00710       if (NumDifferences == 0)   // SAME GEP?
00711         return ReplaceInstUsesWith(I, // No comparison is needed here.
00712                              Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond)));
00713 
00714       else if (NumDifferences == 1 && GEPsInBounds) {
00715         Value *LHSV = GEPLHS->getOperand(DiffOperand);
00716         Value *RHSV = GEPRHS->getOperand(DiffOperand);
00717         // Make sure we do a signed comparison here.
00718         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
00719       }
00720     }
00721 
00722     // Only lower this if the icmp is the only user of the GEP or if we expect
00723     // the result to fold to a constant!
00724     if (DL &&
00725         GEPsInBounds &&
00726         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
00727         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
00728       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
00729       Value *L = EmitGEPOffset(GEPLHS);
00730       Value *R = EmitGEPOffset(GEPRHS);
00731       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
00732     }
00733   }
00734   return 0;
00735 }
00736 
00737 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
00738 Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI,
00739                                             Value *X, ConstantInt *CI,
00740                                             ICmpInst::Predicate Pred) {
00741   // If we have X+0, exit early (simplifying logic below) and let it get folded
00742   // elsewhere.   icmp X+0, X  -> icmp X, X
00743   if (CI->isZero()) {
00744     bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
00745     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
00746   }
00747 
00748   // (X+4) == X -> false.
00749   if (Pred == ICmpInst::ICMP_EQ)
00750     return ReplaceInstUsesWith(ICI, Builder->getFalse());
00751 
00752   // (X+4) != X -> true.
00753   if (Pred == ICmpInst::ICMP_NE)
00754     return ReplaceInstUsesWith(ICI, Builder->getTrue());
00755 
00756   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
00757   // so the values can never be equal.  Similarly for all other "or equals"
00758   // operators.
00759 
00760   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X == 255
00761   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
00762   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
00763   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
00764     Value *R =
00765       ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI);
00766     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
00767   }
00768 
00769   // (X+1) >u X        --> X <u (0-1)        --> X != 255
00770   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
00771   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
00772   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
00773     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
00774 
00775   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
00776   ConstantInt *SMax = ConstantInt::get(X->getContext(),
00777                                        APInt::getSignedMaxValue(BitWidth));
00778 
00779   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
00780   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
00781   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
00782   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
00783   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
00784   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
00785   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
00786     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
00787 
00788   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
00789   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
00790   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
00791   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
00792   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
00793   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
00794 
00795   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
00796   Constant *C = Builder->getInt(CI->getValue()-1);
00797   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
00798 }
00799 
00800 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
00801 /// and CmpRHS are both known to be integer constants.
00802 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
00803                                           ConstantInt *DivRHS) {
00804   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
00805   const APInt &CmpRHSV = CmpRHS->getValue();
00806 
00807   // FIXME: If the operand types don't match the type of the divide
00808   // then don't attempt this transform. The code below doesn't have the
00809   // logic to deal with a signed divide and an unsigned compare (and
00810   // vice versa). This is because (x /s C1) <s C2  produces different
00811   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
00812   // (x /u C1) <u C2.  Simply casting the operands and result won't
00813   // work. :(  The if statement below tests that condition and bails
00814   // if it finds it.
00815   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
00816   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
00817     return 0;
00818   if (DivRHS->isZero())
00819     return 0; // The ProdOV computation fails on divide by zero.
00820   if (DivIsSigned && DivRHS->isAllOnesValue())
00821     return 0; // The overflow computation also screws up here
00822   if (DivRHS->isOne()) {
00823     // This eliminates some funny cases with INT_MIN.
00824     ICI.setOperand(0, DivI->getOperand(0));   // X/1 == X.
00825     return &ICI;
00826   }
00827 
00828   // Compute Prod = CI * DivRHS. We are essentially solving an equation
00829   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
00830   // C2 (CI). By solving for X we can turn this into a range check
00831   // instead of computing a divide.
00832   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
00833 
00834   // Determine if the product overflows by seeing if the product is
00835   // not equal to the divide. Make sure we do the same kind of divide
00836   // as in the LHS instruction that we're folding.
00837   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
00838                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
00839 
00840   // Get the ICmp opcode
00841   ICmpInst::Predicate Pred = ICI.getPredicate();
00842 
00843   /// If the division is known to be exact, then there is no remainder from the
00844   /// divide, so the covered range size is unit, otherwise it is the divisor.
00845   ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS;
00846 
00847   // Figure out the interval that is being checked.  For example, a comparison
00848   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
00849   // Compute this interval based on the constants involved and the signedness of
00850   // the compare/divide.  This computes a half-open interval, keeping track of
00851   // whether either value in the interval overflows.  After analysis each
00852   // overflow variable is set to 0 if it's corresponding bound variable is valid
00853   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
00854   int LoOverflow = 0, HiOverflow = 0;
00855   Constant *LoBound = 0, *HiBound = 0;
00856 
00857   if (!DivIsSigned) {  // udiv
00858     // e.g. X/5 op 3  --> [15, 20)
00859     LoBound = Prod;
00860     HiOverflow = LoOverflow = ProdOV;
00861     if (!HiOverflow) {
00862       // If this is not an exact divide, then many values in the range collapse
00863       // to the same result value.
00864       HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false);
00865     }
00866 
00867   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
00868     if (CmpRHSV == 0) {       // (X / pos) op 0
00869       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
00870       LoBound = ConstantExpr::getNeg(SubOne(RangeSize));
00871       HiBound = RangeSize;
00872     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
00873       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
00874       HiOverflow = LoOverflow = ProdOV;
00875       if (!HiOverflow)
00876         HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true);
00877     } else {                       // (X / pos) op neg
00878       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
00879       HiBound = AddOne(Prod);
00880       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
00881       if (!LoOverflow) {
00882         ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
00883         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
00884       }
00885     }
00886   } else if (DivRHS->isNegative()) { // Divisor is < 0.
00887     if (DivI->isExact())
00888       RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
00889     if (CmpRHSV == 0) {       // (X / neg) op 0
00890       // e.g. X/-5 op 0  --> [-4, 5)
00891       LoBound = AddOne(RangeSize);
00892       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize));
00893       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
00894         HiOverflow = 1;            // [INTMIN+1, overflow)
00895         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
00896       }
00897     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
00898       // e.g. X/-5 op 3  --> [-19, -14)
00899       HiBound = AddOne(Prod);
00900       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
00901       if (!LoOverflow)
00902         LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0;
00903     } else {                       // (X / neg) op neg
00904       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
00905       LoOverflow = HiOverflow = ProdOV;
00906       if (!HiOverflow)
00907         HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true);
00908     }
00909 
00910     // Dividing by a negative swaps the condition.  LT <-> GT
00911     Pred = ICmpInst::getSwappedPredicate(Pred);
00912   }
00913 
00914   Value *X = DivI->getOperand(0);
00915   switch (Pred) {
00916   default: llvm_unreachable("Unhandled icmp opcode!");
00917   case ICmpInst::ICMP_EQ:
00918     if (LoOverflow && HiOverflow)
00919       return ReplaceInstUsesWith(ICI, Builder->getFalse());
00920     if (HiOverflow)
00921       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
00922                           ICmpInst::ICMP_UGE, X, LoBound);
00923     if (LoOverflow)
00924       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
00925                           ICmpInst::ICMP_ULT, X, HiBound);
00926     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
00927                                                     DivIsSigned, true));
00928   case ICmpInst::ICMP_NE:
00929     if (LoOverflow && HiOverflow)
00930       return ReplaceInstUsesWith(ICI, Builder->getTrue());
00931     if (HiOverflow)
00932       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
00933                           ICmpInst::ICMP_ULT, X, LoBound);
00934     if (LoOverflow)
00935       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
00936                           ICmpInst::ICMP_UGE, X, HiBound);
00937     return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound,
00938                                                     DivIsSigned, false));
00939   case ICmpInst::ICMP_ULT:
00940   case ICmpInst::ICMP_SLT:
00941     if (LoOverflow == +1)   // Low bound is greater than input range.
00942       return ReplaceInstUsesWith(ICI, Builder->getTrue());
00943     if (LoOverflow == -1)   // Low bound is less than input range.
00944       return ReplaceInstUsesWith(ICI, Builder->getFalse());
00945     return new ICmpInst(Pred, X, LoBound);
00946   case ICmpInst::ICMP_UGT:
00947   case ICmpInst::ICMP_SGT:
00948     if (HiOverflow == +1)       // High bound greater than input range.
00949       return ReplaceInstUsesWith(ICI, Builder->getFalse());
00950     if (HiOverflow == -1)       // High bound less than input range.
00951       return ReplaceInstUsesWith(ICI, Builder->getTrue());
00952     if (Pred == ICmpInst::ICMP_UGT)
00953       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
00954     return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
00955   }
00956 }
00957 
00958 /// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)".
00959 Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr,
00960                                           ConstantInt *ShAmt) {
00961   const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue();
00962 
00963   // Check that the shift amount is in range.  If not, don't perform
00964   // undefined shifts.  When the shift is visited it will be
00965   // simplified.
00966   uint32_t TypeBits = CmpRHSV.getBitWidth();
00967   uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
00968   if (ShAmtVal >= TypeBits || ShAmtVal == 0)
00969     return 0;
00970 
00971   if (!ICI.isEquality()) {
00972     // If we have an unsigned comparison and an ashr, we can't simplify this.
00973     // Similarly for signed comparisons with lshr.
00974     if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr))
00975       return 0;
00976 
00977     // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv
00978     // by a power of 2.  Since we already have logic to simplify these,
00979     // transform to div and then simplify the resultant comparison.
00980     if (Shr->getOpcode() == Instruction::AShr &&
00981         (!Shr->isExact() || ShAmtVal == TypeBits - 1))
00982       return 0;
00983 
00984     // Revisit the shift (to delete it).
00985     Worklist.Add(Shr);
00986 
00987     Constant *DivCst =
00988       ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal));
00989 
00990     Value *Tmp =
00991       Shr->getOpcode() == Instruction::AShr ?
00992       Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) :
00993       Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact());
00994 
00995     ICI.setOperand(0, Tmp);
00996 
00997     // If the builder folded the binop, just return it.
00998     BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp);
00999     if (TheDiv == 0)
01000       return &ICI;
01001 
01002     // Otherwise, fold this div/compare.
01003     assert(TheDiv->getOpcode() == Instruction::SDiv ||
01004            TheDiv->getOpcode() == Instruction::UDiv);
01005 
01006     Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst));
01007     assert(Res && "This div/cst should have folded!");
01008     return Res;
01009   }
01010 
01011 
01012   // If we are comparing against bits always shifted out, the
01013   // comparison cannot succeed.
01014   APInt Comp = CmpRHSV << ShAmtVal;
01015   ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp);
01016   if (Shr->getOpcode() == Instruction::LShr)
01017     Comp = Comp.lshr(ShAmtVal);
01018   else
01019     Comp = Comp.ashr(ShAmtVal);
01020 
01021   if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero.
01022     bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
01023     Constant *Cst = Builder->getInt1(IsICMP_NE);
01024     return ReplaceInstUsesWith(ICI, Cst);
01025   }
01026 
01027   // Otherwise, check to see if the bits shifted out are known to be zero.
01028   // If so, we can compare against the unshifted value:
01029   //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
01030   if (Shr->hasOneUse() && Shr->isExact())
01031     return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS);
01032 
01033   if (Shr->hasOneUse()) {
01034     // Otherwise strength reduce the shift into an and.
01035     APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
01036     Constant *Mask = Builder->getInt(Val);
01037 
01038     Value *And = Builder->CreateAnd(Shr->getOperand(0),
01039                                     Mask, Shr->getName()+".mask");
01040     return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS);
01041   }
01042   return 0;
01043 }
01044 
01045 
01046 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
01047 ///
01048 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
01049                                                           Instruction *LHSI,
01050                                                           ConstantInt *RHS) {
01051   const APInt &RHSV = RHS->getValue();
01052 
01053   switch (LHSI->getOpcode()) {
01054   case Instruction::Trunc:
01055     if (ICI.isEquality() && LHSI->hasOneUse()) {
01056       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
01057       // of the high bits truncated out of x are known.
01058       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
01059              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
01060       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
01061       ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
01062 
01063       // If all the high bits are known, we can do this xform.
01064       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
01065         // Pull in the high bits from known-ones set.
01066         APInt NewRHS = RHS->getValue().zext(SrcBits);
01067         NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits);
01068         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
01069                             Builder->getInt(NewRHS));
01070       }
01071     }
01072     break;
01073 
01074   case Instruction::Xor:         // (icmp pred (xor X, XorCst), CI)
01075     if (ConstantInt *XorCst = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
01076       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
01077       // fold the xor.
01078       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
01079           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
01080         Value *CompareVal = LHSI->getOperand(0);
01081 
01082         // If the sign bit of the XorCst is not set, there is no change to
01083         // the operation, just stop using the Xor.
01084         if (!XorCst->isNegative()) {
01085           ICI.setOperand(0, CompareVal);
01086           Worklist.Add(LHSI);
01087           return &ICI;
01088         }
01089 
01090         // Was the old condition true if the operand is positive?
01091         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
01092 
01093         // If so, the new one isn't.
01094         isTrueIfPositive ^= true;
01095 
01096         if (isTrueIfPositive)
01097           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
01098                               SubOne(RHS));
01099         else
01100           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
01101                               AddOne(RHS));
01102       }
01103 
01104       if (LHSI->hasOneUse()) {
01105         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
01106         if (!ICI.isEquality() && XorCst->getValue().isSignBit()) {
01107           const APInt &SignBit = XorCst->getValue();
01108           ICmpInst::Predicate Pred = ICI.isSigned()
01109                                          ? ICI.getUnsignedPredicate()
01110                                          : ICI.getSignedPredicate();
01111           return new ICmpInst(Pred, LHSI->getOperand(0),
01112                               Builder->getInt(RHSV ^ SignBit));
01113         }
01114 
01115         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
01116         if (!ICI.isEquality() && XorCst->isMaxValue(true)) {
01117           const APInt &NotSignBit = XorCst->getValue();
01118           ICmpInst::Predicate Pred = ICI.isSigned()
01119                                          ? ICI.getUnsignedPredicate()
01120                                          : ICI.getSignedPredicate();
01121           Pred = ICI.getSwappedPredicate(Pred);
01122           return new ICmpInst(Pred, LHSI->getOperand(0),
01123                               Builder->getInt(RHSV ^ NotSignBit));
01124         }
01125       }
01126 
01127       // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C)
01128       //   iff -C is a power of 2
01129       if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
01130           XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2())
01131         return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst);
01132 
01133       // (icmp ult (xor X, C), -C) -> (icmp uge X, C)
01134       //   iff -C is a power of 2
01135       if (ICI.getPredicate() == ICmpInst::ICMP_ULT &&
01136           XorCst->getValue() == -RHSV && RHSV.isPowerOf2())
01137         return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst);
01138     }
01139     break;
01140   case Instruction::And:         // (icmp pred (and X, AndCst), RHS)
01141     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
01142         LHSI->getOperand(0)->hasOneUse()) {
01143       ConstantInt *AndCst = cast<ConstantInt>(LHSI->getOperand(1));
01144 
01145       // If the LHS is an AND of a truncating cast, we can widen the
01146       // and/compare to be the input width without changing the value
01147       // produced, eliminating a cast.
01148       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
01149         // We can do this transformation if either the AND constant does not
01150         // have its sign bit set or if it is an equality comparison.
01151         // Extending a relational comparison when we're checking the sign
01152         // bit would not work.
01153         if (ICI.isEquality() ||
01154             (!AndCst->isNegative() && RHSV.isNonNegative())) {
01155           Value *NewAnd =
01156             Builder->CreateAnd(Cast->getOperand(0),
01157                                ConstantExpr::getZExt(AndCst, Cast->getSrcTy()));
01158           NewAnd->takeName(LHSI);
01159           return new ICmpInst(ICI.getPredicate(), NewAnd,
01160                               ConstantExpr::getZExt(RHS, Cast->getSrcTy()));
01161         }
01162       }
01163 
01164       // If the LHS is an AND of a zext, and we have an equality compare, we can
01165       // shrink the and/compare to the smaller type, eliminating the cast.
01166       if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) {
01167         IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy());
01168         // Make sure we don't compare the upper bits, SimplifyDemandedBits
01169         // should fold the icmp to true/false in that case.
01170         if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) {
01171           Value *NewAnd =
01172             Builder->CreateAnd(Cast->getOperand(0),
01173                                ConstantExpr::getTrunc(AndCst, Ty));
01174           NewAnd->takeName(LHSI);
01175           return new ICmpInst(ICI.getPredicate(), NewAnd,
01176                               ConstantExpr::getTrunc(RHS, Ty));
01177         }
01178       }
01179 
01180       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
01181       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
01182       // happens a LOT in code produced by the C front-end, for bitfield
01183       // access.
01184       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
01185       if (Shift && !Shift->isShift())
01186         Shift = 0;
01187 
01188       ConstantInt *ShAmt;
01189       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
01190 
01191       // This seemingly simple opportunity to fold away a shift turns out to
01192       // be rather complicated. See PR17827
01193       // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details.
01194       if (ShAmt) {
01195         bool CanFold = false;
01196         unsigned ShiftOpcode = Shift->getOpcode();
01197         if (ShiftOpcode == Instruction::AShr) {
01198           // There may be some constraints that make this possible,
01199           // but nothing simple has been discovered yet.
01200           CanFold = false;
01201         } else if (ShiftOpcode == Instruction::Shl) {
01202           // For a left shift, we can fold if the comparison is not signed.
01203           // We can also fold a signed comparison if the mask value and
01204           // comparison value are not negative. These constraints may not be
01205           // obvious, but we can prove that they are correct using an SMT
01206           // solver.
01207           if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative()))
01208             CanFold = true;
01209         } else if (ShiftOpcode == Instruction::LShr) {
01210           // For a logical right shift, we can fold if the comparison is not
01211           // signed. We can also fold a signed comparison if the shifted mask
01212           // value and the shifted comparison value are not negative.
01213           // These constraints may not be obvious, but we can prove that they
01214           // are correct using an SMT solver.
01215           if (!ICI.isSigned())
01216             CanFold = true;
01217           else {
01218             ConstantInt *ShiftedAndCst =
01219               cast<ConstantInt>(ConstantExpr::getShl(AndCst, ShAmt));
01220             ConstantInt *ShiftedRHSCst =
01221               cast<ConstantInt>(ConstantExpr::getShl(RHS, ShAmt));
01222             
01223             if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative())
01224               CanFold = true;
01225           }
01226         }
01227 
01228         if (CanFold) {
01229           Constant *NewCst;
01230           if (ShiftOpcode == Instruction::Shl)
01231             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
01232           else
01233             NewCst = ConstantExpr::getShl(RHS, ShAmt);
01234 
01235           // Check to see if we are shifting out any of the bits being
01236           // compared.
01237           if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) {
01238             // If we shifted bits out, the fold is not going to work out.
01239             // As a special case, check to see if this means that the
01240             // result is always true or false now.
01241             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
01242               return ReplaceInstUsesWith(ICI, Builder->getFalse());
01243             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
01244               return ReplaceInstUsesWith(ICI, Builder->getTrue());
01245           } else {
01246             ICI.setOperand(1, NewCst);
01247             Constant *NewAndCst;
01248             if (ShiftOpcode == Instruction::Shl)
01249               NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt);
01250             else
01251               NewAndCst = ConstantExpr::getShl(AndCst, ShAmt);
01252             LHSI->setOperand(1, NewAndCst);
01253             LHSI->setOperand(0, Shift->getOperand(0));
01254             Worklist.Add(Shift); // Shift is dead.
01255             return &ICI;
01256           }
01257         }
01258       }
01259 
01260       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
01261       // preferable because it allows the C<<Y expression to be hoisted out
01262       // of a loop if Y is invariant and X is not.
01263       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
01264           ICI.isEquality() && !Shift->isArithmeticShift() &&
01265           !isa<Constant>(Shift->getOperand(0))) {
01266         // Compute C << Y.
01267         Value *NS;
01268         if (Shift->getOpcode() == Instruction::LShr) {
01269           NS = Builder->CreateShl(AndCst, Shift->getOperand(1));
01270         } else {
01271           // Insert a logical shift.
01272           NS = Builder->CreateLShr(AndCst, Shift->getOperand(1));
01273         }
01274 
01275         // Compute X & (C << Y).
01276         Value *NewAnd =
01277           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
01278 
01279         ICI.setOperand(0, NewAnd);
01280         return &ICI;
01281       }
01282 
01283       // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any
01284       // bit set in (X & AndCst) will produce a result greater than RHSV.
01285       if (ICI.getPredicate() == ICmpInst::ICMP_UGT) {
01286         unsigned NTZ = AndCst->getValue().countTrailingZeros();
01287         if ((NTZ < AndCst->getBitWidth()) &&
01288             APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV))
01289           return new ICmpInst(ICmpInst::ICMP_NE, LHSI,
01290                               Constant::getNullValue(RHS->getType()));
01291       }
01292     }
01293 
01294     // Try to optimize things like "A[i]&42 == 0" to index computations.
01295     if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
01296       if (GetElementPtrInst *GEP =
01297           dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
01298         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
01299           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
01300               !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
01301             ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
01302             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
01303               return Res;
01304           }
01305     }
01306 
01307     // X & -C == -C -> X >  u ~C
01308     // X & -C != -C -> X <= u ~C
01309     //   iff C is a power of 2
01310     if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2())
01311       return new ICmpInst(
01312           ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT
01313                                                   : ICmpInst::ICMP_ULE,
01314           LHSI->getOperand(0), SubOne(RHS));
01315     break;
01316 
01317   case Instruction::Or: {
01318     if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
01319       break;
01320     Value *P, *Q;
01321     if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
01322       // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
01323       // -> and (icmp eq P, null), (icmp eq Q, null).
01324       Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
01325                                         Constant::getNullValue(P->getType()));
01326       Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
01327                                         Constant::getNullValue(Q->getType()));
01328       Instruction *Op;
01329       if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
01330         Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
01331       else
01332         Op = BinaryOperator::CreateOr(ICIP, ICIQ);
01333       return Op;
01334     }
01335     break;
01336   }
01337 
01338   case Instruction::Mul: {       // (icmp pred (mul X, Val), CI)
01339     ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1));
01340     if (!Val) break;
01341 
01342     // If this is a signed comparison to 0 and the mul is sign preserving,
01343     // use the mul LHS operand instead.
01344     ICmpInst::Predicate pred = ICI.getPredicate();
01345     if (isSignTest(pred, RHS) && !Val->isZero() &&
01346         cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
01347       return new ICmpInst(Val->isNegative() ?
01348                           ICmpInst::getSwappedPredicate(pred) : pred,
01349                           LHSI->getOperand(0),
01350                           Constant::getNullValue(RHS->getType()));
01351 
01352     break;
01353   }
01354 
01355   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
01356     uint32_t TypeBits = RHSV.getBitWidth();
01357     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
01358     if (!ShAmt) {
01359       Value *X;
01360       // (1 << X) pred P2 -> X pred Log2(P2)
01361       if (match(LHSI, m_Shl(m_One(), m_Value(X)))) {
01362         bool RHSVIsPowerOf2 = RHSV.isPowerOf2();
01363         ICmpInst::Predicate Pred = ICI.getPredicate();
01364         if (ICI.isUnsigned()) {
01365           if (!RHSVIsPowerOf2) {
01366             // (1 << X) <  30 -> X <= 4
01367             // (1 << X) <= 30 -> X <= 4
01368             // (1 << X) >= 30 -> X >  4
01369             // (1 << X) >  30 -> X >  4
01370             if (Pred == ICmpInst::ICMP_ULT)
01371               Pred = ICmpInst::ICMP_ULE;
01372             else if (Pred == ICmpInst::ICMP_UGE)
01373               Pred = ICmpInst::ICMP_UGT;
01374           }
01375           unsigned RHSLog2 = RHSV.logBase2();
01376 
01377           // (1 << X) >= 2147483648 -> X >= 31 -> X == 31
01378           // (1 << X) >  2147483648 -> X >  31 -> false
01379           // (1 << X) <= 2147483648 -> X <= 31 -> true
01380           // (1 << X) <  2147483648 -> X <  31 -> X != 31
01381           if (RHSLog2 == TypeBits-1) {
01382             if (Pred == ICmpInst::ICMP_UGE)
01383               Pred = ICmpInst::ICMP_EQ;
01384             else if (Pred == ICmpInst::ICMP_UGT)
01385               return ReplaceInstUsesWith(ICI, Builder->getFalse());
01386             else if (Pred == ICmpInst::ICMP_ULE)
01387               return ReplaceInstUsesWith(ICI, Builder->getTrue());
01388             else if (Pred == ICmpInst::ICMP_ULT)
01389               Pred = ICmpInst::ICMP_NE;
01390           }
01391 
01392           return new ICmpInst(Pred, X,
01393                               ConstantInt::get(RHS->getType(), RHSLog2));
01394         } else if (ICI.isSigned()) {
01395           if (RHSV.isAllOnesValue()) {
01396             // (1 << X) <= -1 -> X == 31
01397             if (Pred == ICmpInst::ICMP_SLE)
01398               return new ICmpInst(ICmpInst::ICMP_EQ, X,
01399                                   ConstantInt::get(RHS->getType(), TypeBits-1));
01400 
01401             // (1 << X) >  -1 -> X != 31
01402             if (Pred == ICmpInst::ICMP_SGT)
01403               return new ICmpInst(ICmpInst::ICMP_NE, X,
01404                                   ConstantInt::get(RHS->getType(), TypeBits-1));
01405           } else if (!RHSV) {
01406             // (1 << X) <  0 -> X == 31
01407             // (1 << X) <= 0 -> X == 31
01408             if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
01409               return new ICmpInst(ICmpInst::ICMP_EQ, X,
01410                                   ConstantInt::get(RHS->getType(), TypeBits-1));
01411 
01412             // (1 << X) >= 0 -> X != 31
01413             // (1 << X) >  0 -> X != 31
01414             if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
01415               return new ICmpInst(ICmpInst::ICMP_NE, X,
01416                                   ConstantInt::get(RHS->getType(), TypeBits-1));
01417           }
01418         } else if (ICI.isEquality()) {
01419           if (RHSVIsPowerOf2)
01420             return new ICmpInst(
01421                 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2()));
01422 
01423           return ReplaceInstUsesWith(
01424               ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse()
01425                                              : Builder->getTrue());
01426         }
01427       }
01428       break;
01429     }
01430 
01431     // Check that the shift amount is in range.  If not, don't perform
01432     // undefined shifts.  When the shift is visited it will be
01433     // simplified.
01434     if (ShAmt->uge(TypeBits))
01435       break;
01436 
01437     if (ICI.isEquality()) {
01438       // If we are comparing against bits always shifted out, the
01439       // comparison cannot succeed.
01440       Constant *Comp =
01441         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
01442                                                                  ShAmt);
01443       if (Comp != RHS) {// Comparing against a bit that we know is zero.
01444         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
01445         Constant *Cst = Builder->getInt1(IsICMP_NE);
01446         return ReplaceInstUsesWith(ICI, Cst);
01447       }
01448 
01449       // If the shift is NUW, then it is just shifting out zeros, no need for an
01450       // AND.
01451       if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap())
01452         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
01453                             ConstantExpr::getLShr(RHS, ShAmt));
01454 
01455       // If the shift is NSW and we compare to 0, then it is just shifting out
01456       // sign bits, no need for an AND either.
01457       if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0)
01458         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
01459                             ConstantExpr::getLShr(RHS, ShAmt));
01460 
01461       if (LHSI->hasOneUse()) {
01462         // Otherwise strength reduce the shift into an and.
01463         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
01464         Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits,
01465                                                           TypeBits - ShAmtVal));
01466 
01467         Value *And =
01468           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
01469         return new ICmpInst(ICI.getPredicate(), And,
01470                             ConstantExpr::getLShr(RHS, ShAmt));
01471       }
01472     }
01473 
01474     // If this is a signed comparison to 0 and the shift is sign preserving,
01475     // use the shift LHS operand instead.
01476     ICmpInst::Predicate pred = ICI.getPredicate();
01477     if (isSignTest(pred, RHS) &&
01478         cast<BinaryOperator>(LHSI)->hasNoSignedWrap())
01479       return new ICmpInst(pred,
01480                           LHSI->getOperand(0),
01481                           Constant::getNullValue(RHS->getType()));
01482 
01483     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
01484     bool TrueIfSigned = false;
01485     if (LHSI->hasOneUse() &&
01486         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
01487       // (X << 31) <s 0  --> (X&1) != 0
01488       Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(),
01489                                         APInt::getOneBitSet(TypeBits,
01490                                             TypeBits-ShAmt->getZExtValue()-1));
01491       Value *And =
01492         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
01493       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
01494                           And, Constant::getNullValue(And->getType()));
01495     }
01496 
01497     // Transform (icmp pred iM (shl iM %v, N), CI)
01498     // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N))
01499     // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N.
01500     // This enables to get rid of the shift in favor of a trunc which can be
01501     // free on the target. It has the additional benefit of comparing to a
01502     // smaller constant, which will be target friendly.
01503     unsigned Amt = ShAmt->getLimitedValue(TypeBits-1);
01504     if (LHSI->hasOneUse() &&
01505         Amt != 0 && RHSV.countTrailingZeros() >= Amt) {
01506       Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt);
01507       Constant *NCI = ConstantExpr::getTrunc(
01508                         ConstantExpr::getAShr(RHS,
01509                           ConstantInt::get(RHS->getType(), Amt)),
01510                         NTy);
01511       return new ICmpInst(ICI.getPredicate(),
01512                           Builder->CreateTrunc(LHSI->getOperand(0), NTy),
01513                           NCI);
01514     }
01515 
01516     break;
01517   }
01518 
01519   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
01520   case Instruction::AShr: {
01521     // Handle equality comparisons of shift-by-constant.
01522     BinaryOperator *BO = cast<BinaryOperator>(LHSI);
01523     if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
01524       if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt))
01525         return Res;
01526     }
01527 
01528     // Handle exact shr's.
01529     if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) {
01530       if (RHSV.isMinValue())
01531         return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS);
01532     }
01533     break;
01534   }
01535 
01536   case Instruction::SDiv:
01537   case Instruction::UDiv:
01538     // Fold: icmp pred ([us]div X, C1), C2 -> range test
01539     // Fold this div into the comparison, producing a range check.
01540     // Determine, based on the divide type, what the range is being
01541     // checked.  If there is an overflow on the low or high side, remember
01542     // it, otherwise compute the range [low, hi) bounding the new value.
01543     // See: InsertRangeTest above for the kinds of replacements possible.
01544     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
01545       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
01546                                           DivRHS))
01547         return R;
01548     break;
01549 
01550   case Instruction::Sub: {
01551     ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0));
01552     if (!LHSC) break;
01553     const APInt &LHSV = LHSC->getValue();
01554 
01555     // C1-X <u C2 -> (X|(C2-1)) == C1
01556     //   iff C1 & (C2-1) == C2-1
01557     //       C2 is a power of 2
01558     if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
01559         RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1))
01560       return new ICmpInst(ICmpInst::ICMP_EQ,
01561                           Builder->CreateOr(LHSI->getOperand(1), RHSV - 1),
01562                           LHSC);
01563 
01564     // C1-X >u C2 -> (X|C2) != C1
01565     //   iff C1 & C2 == C2
01566     //       C2+1 is a power of 2
01567     if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
01568         (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV)
01569       return new ICmpInst(ICmpInst::ICMP_NE,
01570                           Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC);
01571     break;
01572   }
01573 
01574   case Instruction::Add:
01575     // Fold: icmp pred (add X, C1), C2
01576     if (!ICI.isEquality()) {
01577       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
01578       if (!LHSC) break;
01579       const APInt &LHSV = LHSC->getValue();
01580 
01581       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
01582                             .subtract(LHSV);
01583 
01584       if (ICI.isSigned()) {
01585         if (CR.getLower().isSignBit()) {
01586           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
01587                               Builder->getInt(CR.getUpper()));
01588         } else if (CR.getUpper().isSignBit()) {
01589           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
01590                               Builder->getInt(CR.getLower()));
01591         }
01592       } else {
01593         if (CR.getLower().isMinValue()) {
01594           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
01595                               Builder->getInt(CR.getUpper()));
01596         } else if (CR.getUpper().isMinValue()) {
01597           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
01598                               Builder->getInt(CR.getLower()));
01599         }
01600       }
01601 
01602       // X-C1 <u C2 -> (X & -C2) == C1
01603       //   iff C1 & (C2-1) == 0
01604       //       C2 is a power of 2
01605       if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() &&
01606           RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0)
01607         return new ICmpInst(ICmpInst::ICMP_EQ,
01608                             Builder->CreateAnd(LHSI->getOperand(0), -RHSV),
01609                             ConstantExpr::getNeg(LHSC));
01610 
01611       // X-C1 >u C2 -> (X & ~C2) != C1
01612       //   iff C1 & C2 == 0
01613       //       C2+1 is a power of 2
01614       if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() &&
01615           (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0)
01616         return new ICmpInst(ICmpInst::ICMP_NE,
01617                             Builder->CreateAnd(LHSI->getOperand(0), ~RHSV),
01618                             ConstantExpr::getNeg(LHSC));
01619     }
01620     break;
01621   }
01622 
01623   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
01624   if (ICI.isEquality()) {
01625     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
01626 
01627     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
01628     // the second operand is a constant, simplify a bit.
01629     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
01630       switch (BO->getOpcode()) {
01631       case Instruction::SRem:
01632         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
01633         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
01634           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
01635           if (V.sgt(1) && V.isPowerOf2()) {
01636             Value *NewRem =
01637               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
01638                                   BO->getName());
01639             return new ICmpInst(ICI.getPredicate(), NewRem,
01640                                 Constant::getNullValue(BO->getType()));
01641           }
01642         }
01643         break;
01644       case Instruction::Add:
01645         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
01646         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
01647           if (BO->hasOneUse())
01648             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
01649                                 ConstantExpr::getSub(RHS, BOp1C));
01650         } else if (RHSV == 0) {
01651           // Replace ((add A, B) != 0) with (A != -B) if A or B is
01652           // efficiently invertible, or if the add has just this one use.
01653           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
01654 
01655           if (Value *NegVal = dyn_castNegVal(BOp1))
01656             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
01657           if (Value *NegVal = dyn_castNegVal(BOp0))
01658             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
01659           if (BO->hasOneUse()) {
01660             Value *Neg = Builder->CreateNeg(BOp1);
01661             Neg->takeName(BO);
01662             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
01663           }
01664         }
01665         break;
01666       case Instruction::Xor:
01667         // For the xor case, we can xor two constants together, eliminating
01668         // the explicit xor.
01669         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
01670           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
01671                               ConstantExpr::getXor(RHS, BOC));
01672         } else if (RHSV == 0) {
01673           // Replace ((xor A, B) != 0) with (A != B)
01674           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
01675                               BO->getOperand(1));
01676         }
01677         break;
01678       case Instruction::Sub:
01679         // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants.
01680         if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) {
01681           if (BO->hasOneUse())
01682             return new ICmpInst(ICI.getPredicate(), BO->getOperand(1),
01683                                 ConstantExpr::getSub(BOp0C, RHS));
01684         } else if (RHSV == 0) {
01685           // Replace ((sub A, B) != 0) with (A != B)
01686           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
01687                               BO->getOperand(1));
01688         }
01689         break;
01690       case Instruction::Or:
01691         // If bits are being or'd in that are not present in the constant we
01692         // are comparing against, then the comparison could never succeed!
01693         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
01694           Constant *NotCI = ConstantExpr::getNot(RHS);
01695           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
01696             return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
01697         }
01698         break;
01699 
01700       case Instruction::And:
01701         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
01702           // If bits are being compared against that are and'd out, then the
01703           // comparison can never succeed!
01704           if ((RHSV & ~BOC->getValue()) != 0)
01705             return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE));
01706 
01707           // If we have ((X & C) == C), turn it into ((X & C) != 0).
01708           if (RHS == BOC && RHSV.isPowerOf2())
01709             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
01710                                 ICmpInst::ICMP_NE, LHSI,
01711                                 Constant::getNullValue(RHS->getType()));
01712 
01713           // Don't perform the following transforms if the AND has multiple uses
01714           if (!BO->hasOneUse())
01715             break;
01716 
01717           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
01718           if (BOC->getValue().isSignBit()) {
01719             Value *X = BO->getOperand(0);
01720             Constant *Zero = Constant::getNullValue(X->getType());
01721             ICmpInst::Predicate pred = isICMP_NE ?
01722               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
01723             return new ICmpInst(pred, X, Zero);
01724           }
01725 
01726           // ((X & ~7) == 0) --> X < 8
01727           if (RHSV == 0 && isHighOnes(BOC)) {
01728             Value *X = BO->getOperand(0);
01729             Constant *NegX = ConstantExpr::getNeg(BOC);
01730             ICmpInst::Predicate pred = isICMP_NE ?
01731               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
01732             return new ICmpInst(pred, X, NegX);
01733           }
01734         }
01735         break;
01736       case Instruction::Mul:
01737         if (RHSV == 0 && BO->hasNoSignedWrap()) {
01738           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
01739             // The trivial case (mul X, 0) is handled by InstSimplify
01740             // General case : (mul X, C) != 0 iff X != 0
01741             //                (mul X, C) == 0 iff X == 0
01742             if (!BOC->isZero())
01743               return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
01744                                   Constant::getNullValue(RHS->getType()));
01745           }
01746         }
01747         break;
01748       default: break;
01749       }
01750     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
01751       // Handle icmp {eq|ne} <intrinsic>, intcst.
01752       switch (II->getIntrinsicID()) {
01753       case Intrinsic::bswap:
01754         Worklist.Add(II);
01755         ICI.setOperand(0, II->getArgOperand(0));
01756         ICI.setOperand(1, Builder->getInt(RHSV.byteSwap()));
01757         return &ICI;
01758       case Intrinsic::ctlz:
01759       case Intrinsic::cttz:
01760         // ctz(A) == bitwidth(a)  ->  A == 0 and likewise for !=
01761         if (RHSV == RHS->getType()->getBitWidth()) {
01762           Worklist.Add(II);
01763           ICI.setOperand(0, II->getArgOperand(0));
01764           ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0));
01765           return &ICI;
01766         }
01767         break;
01768       case Intrinsic::ctpop:
01769         // popcount(A) == 0  ->  A == 0 and likewise for !=
01770         if (RHS->isZero()) {
01771           Worklist.Add(II);
01772           ICI.setOperand(0, II->getArgOperand(0));
01773           ICI.setOperand(1, RHS);
01774           return &ICI;
01775         }
01776         break;
01777       default:
01778         break;
01779       }
01780     }
01781   }
01782   return 0;
01783 }
01784 
01785 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
01786 /// We only handle extending casts so far.
01787 ///
01788 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
01789   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
01790   Value *LHSCIOp        = LHSCI->getOperand(0);
01791   Type *SrcTy     = LHSCIOp->getType();
01792   Type *DestTy    = LHSCI->getType();
01793   Value *RHSCIOp;
01794 
01795   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
01796   // integer type is the same size as the pointer type.
01797   if (DL && LHSCI->getOpcode() == Instruction::PtrToInt &&
01798       DL->getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) {
01799     Value *RHSOp = 0;
01800     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
01801       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
01802     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
01803       RHSOp = RHSC->getOperand(0);
01804       // If the pointer types don't match, insert a bitcast.
01805       if (LHSCIOp->getType() != RHSOp->getType())
01806         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
01807     }
01808 
01809     if (RHSOp)
01810       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
01811   }
01812 
01813   // The code below only handles extension cast instructions, so far.
01814   // Enforce this.
01815   if (LHSCI->getOpcode() != Instruction::ZExt &&
01816       LHSCI->getOpcode() != Instruction::SExt)
01817     return 0;
01818 
01819   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
01820   bool isSignedCmp = ICI.isSigned();
01821 
01822   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
01823     // Not an extension from the same type?
01824     RHSCIOp = CI->getOperand(0);
01825     if (RHSCIOp->getType() != LHSCIOp->getType())
01826       return 0;
01827 
01828     // If the signedness of the two casts doesn't agree (i.e. one is a sext
01829     // and the other is a zext), then we can't handle this.
01830     if (CI->getOpcode() != LHSCI->getOpcode())
01831       return 0;
01832 
01833     // Deal with equality cases early.
01834     if (ICI.isEquality())
01835       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
01836 
01837     // A signed comparison of sign extended values simplifies into a
01838     // signed comparison.
01839     if (isSignedCmp && isSignedExt)
01840       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
01841 
01842     // The other three cases all fold into an unsigned comparison.
01843     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
01844   }
01845 
01846   // If we aren't dealing with a constant on the RHS, exit early
01847   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
01848   if (!CI)
01849     return 0;
01850 
01851   // Compute the constant that would happen if we truncated to SrcTy then
01852   // reextended to DestTy.
01853   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
01854   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
01855                                                 Res1, DestTy);
01856 
01857   // If the re-extended constant didn't change...
01858   if (Res2 == CI) {
01859     // Deal with equality cases early.
01860     if (ICI.isEquality())
01861       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
01862 
01863     // A signed comparison of sign extended values simplifies into a
01864     // signed comparison.
01865     if (isSignedExt && isSignedCmp)
01866       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
01867 
01868     // The other three cases all fold into an unsigned comparison.
01869     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
01870   }
01871 
01872   // The re-extended constant changed so the constant cannot be represented
01873   // in the shorter type. Consequently, we cannot emit a simple comparison.
01874   // All the cases that fold to true or false will have already been handled
01875   // by SimplifyICmpInst, so only deal with the tricky case.
01876 
01877   if (isSignedCmp || !isSignedExt)
01878     return 0;
01879 
01880   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
01881   // should have been folded away previously and not enter in here.
01882 
01883   // We're performing an unsigned comp with a sign extended value.
01884   // This is true if the input is >= 0. [aka >s -1]
01885   Constant *NegOne = Constant::getAllOnesValue(SrcTy);
01886   Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
01887 
01888   // Finally, return the value computed.
01889   if (ICI.getPredicate() == ICmpInst::ICMP_ULT)
01890     return ReplaceInstUsesWith(ICI, Result);
01891 
01892   assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
01893   return BinaryOperator::CreateNot(Result);
01894 }
01895 
01896 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form:
01897 ///   I = icmp ugt (add (add A, B), CI2), CI1
01898 /// If this is of the form:
01899 ///   sum = a + b
01900 ///   if (sum+128 >u 255)
01901 /// Then replace it with llvm.sadd.with.overflow.i8.
01902 ///
01903 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
01904                                           ConstantInt *CI2, ConstantInt *CI1,
01905                                           InstCombiner &IC) {
01906   // The transformation we're trying to do here is to transform this into an
01907   // llvm.sadd.with.overflow.  To do this, we have to replace the original add
01908   // with a narrower add, and discard the add-with-constant that is part of the
01909   // range check (if we can't eliminate it, this isn't profitable).
01910 
01911   // In order to eliminate the add-with-constant, the compare can be its only
01912   // use.
01913   Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
01914   if (!AddWithCst->hasOneUse()) return 0;
01915 
01916   // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
01917   if (!CI2->getValue().isPowerOf2()) return 0;
01918   unsigned NewWidth = CI2->getValue().countTrailingZeros();
01919   if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0;
01920 
01921   // The width of the new add formed is 1 more than the bias.
01922   ++NewWidth;
01923 
01924   // Check to see that CI1 is an all-ones value with NewWidth bits.
01925   if (CI1->getBitWidth() == NewWidth ||
01926       CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
01927     return 0;
01928 
01929   // This is only really a signed overflow check if the inputs have been
01930   // sign-extended; check for that condition. For example, if CI2 is 2^31 and
01931   // the operands of the add are 64 bits wide, we need at least 33 sign bits.
01932   unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1;
01933   if (IC.ComputeNumSignBits(A) < NeededSignBits ||
01934       IC.ComputeNumSignBits(B) < NeededSignBits)
01935     return 0;
01936 
01937   // In order to replace the original add with a narrower
01938   // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
01939   // and truncates that discard the high bits of the add.  Verify that this is
01940   // the case.
01941   Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
01942   for (User *U : OrigAdd->users()) {
01943     if (U == AddWithCst) continue;
01944 
01945     // Only accept truncates for now.  We would really like a nice recursive
01946     // predicate like SimplifyDemandedBits, but which goes downwards the use-def
01947     // chain to see which bits of a value are actually demanded.  If the
01948     // original add had another add which was then immediately truncated, we
01949     // could still do the transformation.
01950     TruncInst *TI = dyn_cast<TruncInst>(U);
01951     if (TI == 0 ||
01952         TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0;
01953   }
01954 
01955   // If the pattern matches, truncate the inputs to the narrower type and
01956   // use the sadd_with_overflow intrinsic to efficiently compute both the
01957   // result and the overflow bit.
01958   Module *M = I.getParent()->getParent()->getParent();
01959 
01960   Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
01961   Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
01962                                        NewType);
01963 
01964   InstCombiner::BuilderTy *Builder = IC.Builder;
01965 
01966   // Put the new code above the original add, in case there are any uses of the
01967   // add between the add and the compare.
01968   Builder->SetInsertPoint(OrigAdd);
01969 
01970   Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc");
01971   Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc");
01972   CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd");
01973   Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result");
01974   Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType());
01975 
01976   // The inner add was the result of the narrow add, zero extended to the
01977   // wider type.  Replace it with the result computed by the intrinsic.
01978   IC.ReplaceInstUsesWith(*OrigAdd, ZExt);
01979 
01980   // The original icmp gets replaced with the overflow value.
01981   return ExtractValueInst::Create(Call, 1, "sadd.overflow");
01982 }
01983 
01984 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV,
01985                                      InstCombiner &IC) {
01986   // Don't bother doing this transformation for pointers, don't do it for
01987   // vectors.
01988   if (!isa<IntegerType>(OrigAddV->getType())) return 0;
01989 
01990   // If the add is a constant expr, then we don't bother transforming it.
01991   Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV);
01992   if (OrigAdd == 0) return 0;
01993 
01994   Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1);
01995 
01996   // Put the new code above the original add, in case there are any uses of the
01997   // add between the add and the compare.
01998   InstCombiner::BuilderTy *Builder = IC.Builder;
01999   Builder->SetInsertPoint(OrigAdd);
02000 
02001   Module *M = I.getParent()->getParent()->getParent();
02002   Type *Ty = LHS->getType();
02003   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
02004   CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd");
02005   Value *Add = Builder->CreateExtractValue(Call, 0);
02006 
02007   IC.ReplaceInstUsesWith(*OrigAdd, Add);
02008 
02009   // The original icmp gets replaced with the overflow value.
02010   return ExtractValueInst::Create(Call, 1, "uadd.overflow");
02011 }
02012 
02013 /// \brief Recognize and process idiom involving test for multiplication
02014 /// overflow.
02015 ///
02016 /// The caller has matched a pattern of the form:
02017 ///   I = cmp u (mul(zext A, zext B), V
02018 /// The function checks if this is a test for overflow and if so replaces
02019 /// multiplication with call to 'mul.with.overflow' intrinsic.
02020 ///
02021 /// \param I Compare instruction.
02022 /// \param MulVal Result of 'mult' instruction.  It is one of the arguments of
02023 ///               the compare instruction.  Must be of integer type.
02024 /// \param OtherVal The other argument of compare instruction.
02025 /// \returns Instruction which must replace the compare instruction, NULL if no
02026 ///          replacement required.
02027 static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
02028                                          Value *OtherVal, InstCombiner &IC) {
02029   assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
02030   assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
02031   assert(isa<IntegerType>(MulVal->getType()));
02032   Instruction *MulInstr = cast<Instruction>(MulVal);
02033   assert(MulInstr->getOpcode() == Instruction::Mul);
02034 
02035   Instruction *LHS = cast<Instruction>(MulInstr->getOperand(0)),
02036               *RHS = cast<Instruction>(MulInstr->getOperand(1));
02037   assert(LHS->getOpcode() == Instruction::ZExt);
02038   assert(RHS->getOpcode() == Instruction::ZExt);
02039   Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
02040 
02041   // Calculate type and width of the result produced by mul.with.overflow.
02042   Type *TyA = A->getType(), *TyB = B->getType();
02043   unsigned WidthA = TyA->getPrimitiveSizeInBits(),
02044            WidthB = TyB->getPrimitiveSizeInBits();
02045   unsigned MulWidth;
02046   Type *MulType;
02047   if (WidthB > WidthA) {
02048     MulWidth = WidthB;
02049     MulType = TyB;
02050   } else {
02051     MulWidth = WidthA;
02052     MulType = TyA;
02053   }
02054 
02055   // In order to replace the original mul with a narrower mul.with.overflow,
02056   // all uses must ignore upper bits of the product.  The number of used low
02057   // bits must be not greater than the width of mul.with.overflow.
02058   if (MulVal->hasNUsesOrMore(2))
02059     for (User *U : MulVal->users()) {
02060       if (U == &I)
02061         continue;
02062       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
02063         // Check if truncation ignores bits above MulWidth.
02064         unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
02065         if (TruncWidth > MulWidth)
02066           return 0;
02067       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
02068         // Check if AND ignores bits above MulWidth.
02069         if (BO->getOpcode() != Instruction::And)
02070           return 0;
02071         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
02072           const APInt &CVal = CI->getValue();
02073           if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
02074             return 0;
02075         }
02076       } else {
02077         // Other uses prohibit this transformation.
02078         return 0;
02079       }
02080     }
02081 
02082   // Recognize patterns
02083   switch (I.getPredicate()) {
02084   case ICmpInst::ICMP_EQ:
02085   case ICmpInst::ICMP_NE:
02086     // Recognize pattern:
02087     //   mulval = mul(zext A, zext B)
02088     //   cmp eq/neq mulval, zext trunc mulval
02089     if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
02090       if (Zext->hasOneUse()) {
02091         Value *ZextArg = Zext->getOperand(0);
02092         if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
02093           if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
02094             break; //Recognized
02095       }
02096 
02097     // Recognize pattern:
02098     //   mulval = mul(zext A, zext B)
02099     //   cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
02100     ConstantInt *CI;
02101     Value *ValToMask;
02102     if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
02103       if (ValToMask != MulVal)
02104         return 0;
02105       const APInt &CVal = CI->getValue() + 1;
02106       if (CVal.isPowerOf2()) {
02107         unsigned MaskWidth = CVal.logBase2();
02108         if (MaskWidth == MulWidth)
02109           break; // Recognized
02110       }
02111     }
02112     return 0;
02113 
02114   case ICmpInst::ICMP_UGT:
02115     // Recognize pattern:
02116     //   mulval = mul(zext A, zext B)
02117     //   cmp ugt mulval, max
02118     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02119       APInt MaxVal = APInt::getMaxValue(MulWidth);
02120       MaxVal = MaxVal.zext(CI->getBitWidth());
02121       if (MaxVal.eq(CI->getValue()))
02122         break; // Recognized
02123     }
02124     return 0;
02125 
02126   case ICmpInst::ICMP_UGE:
02127     // Recognize pattern:
02128     //   mulval = mul(zext A, zext B)
02129     //   cmp uge mulval, max+1
02130     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02131       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
02132       if (MaxVal.eq(CI->getValue()))
02133         break; // Recognized
02134     }
02135     return 0;
02136 
02137   case ICmpInst::ICMP_ULE:
02138     // Recognize pattern:
02139     //   mulval = mul(zext A, zext B)
02140     //   cmp ule mulval, max
02141     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02142       APInt MaxVal = APInt::getMaxValue(MulWidth);
02143       MaxVal = MaxVal.zext(CI->getBitWidth());
02144       if (MaxVal.eq(CI->getValue()))
02145         break; // Recognized
02146     }
02147     return 0;
02148 
02149   case ICmpInst::ICMP_ULT:
02150     // Recognize pattern:
02151     //   mulval = mul(zext A, zext B)
02152     //   cmp ule mulval, max + 1
02153     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02154       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
02155       if (MaxVal.eq(CI->getValue()))
02156         break; // Recognized
02157     }
02158     return 0;
02159 
02160   default:
02161     return 0;
02162   }
02163 
02164   InstCombiner::BuilderTy *Builder = IC.Builder;
02165   Builder->SetInsertPoint(MulInstr);
02166   Module *M = I.getParent()->getParent()->getParent();
02167 
02168   // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
02169   Value *MulA = A, *MulB = B;
02170   if (WidthA < MulWidth)
02171     MulA = Builder->CreateZExt(A, MulType);
02172   if (WidthB < MulWidth)
02173     MulB = Builder->CreateZExt(B, MulType);
02174   Value *F =
02175       Intrinsic::getDeclaration(M, Intrinsic::umul_with_overflow, MulType);
02176   CallInst *Call = Builder->CreateCall2(F, MulA, MulB, "umul");
02177   IC.Worklist.Add(MulInstr);
02178 
02179   // If there are uses of mul result other than the comparison, we know that
02180   // they are truncation or binary AND. Change them to use result of
02181   // mul.with.overflow and adjust properly mask/size.
02182   if (MulVal->hasNUsesOrMore(2)) {
02183     Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
02184     for (User *U : MulVal->users()) {
02185       if (U == &I || U == OtherVal)
02186         continue;
02187       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
02188         if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
02189           IC.ReplaceInstUsesWith(*TI, Mul);
02190         else
02191           TI->setOperand(0, Mul);
02192       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
02193         assert(BO->getOpcode() == Instruction::And);
02194         // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
02195         ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
02196         APInt ShortMask = CI->getValue().trunc(MulWidth);
02197         Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
02198         Instruction *Zext =
02199             cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
02200         IC.Worklist.Add(Zext);
02201         IC.ReplaceInstUsesWith(*BO, Zext);
02202       } else {
02203         llvm_unreachable("Unexpected Binary operation");
02204       }
02205       IC.Worklist.Add(cast<Instruction>(U));
02206     }
02207   }
02208   if (isa<Instruction>(OtherVal))
02209     IC.Worklist.Add(cast<Instruction>(OtherVal));
02210 
02211   // The original icmp gets replaced with the overflow value, maybe inverted
02212   // depending on predicate.
02213   bool Inverse = false;
02214   switch (I.getPredicate()) {
02215   case ICmpInst::ICMP_NE:
02216     break;
02217   case ICmpInst::ICMP_EQ:
02218     Inverse = true;
02219     break;
02220   case ICmpInst::ICMP_UGT:
02221   case ICmpInst::ICMP_UGE:
02222     if (I.getOperand(0) == MulVal)
02223       break;
02224     Inverse = true;
02225     break;
02226   case ICmpInst::ICMP_ULT:
02227   case ICmpInst::ICMP_ULE:
02228     if (I.getOperand(1) == MulVal)
02229       break;
02230     Inverse = true;
02231     break;
02232   default:
02233     llvm_unreachable("Unexpected predicate");
02234   }
02235   if (Inverse) {
02236     Value *Res = Builder->CreateExtractValue(Call, 1);
02237     return BinaryOperator::CreateNot(Res);
02238   }
02239 
02240   return ExtractValueInst::Create(Call, 1);
02241 }
02242 
02243 // DemandedBitsLHSMask - When performing a comparison against a constant,
02244 // it is possible that not all the bits in the LHS are demanded.  This helper
02245 // method computes the mask that IS demanded.
02246 static APInt DemandedBitsLHSMask(ICmpInst &I,
02247                                  unsigned BitWidth, bool isSignCheck) {
02248   if (isSignCheck)
02249     return APInt::getSignBit(BitWidth);
02250 
02251   ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
02252   if (!CI) return APInt::getAllOnesValue(BitWidth);
02253   const APInt &RHS = CI->getValue();
02254 
02255   switch (I.getPredicate()) {
02256   // For a UGT comparison, we don't care about any bits that
02257   // correspond to the trailing ones of the comparand.  The value of these
02258   // bits doesn't impact the outcome of the comparison, because any value
02259   // greater than the RHS must differ in a bit higher than these due to carry.
02260   case ICmpInst::ICMP_UGT: {
02261     unsigned trailingOnes = RHS.countTrailingOnes();
02262     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
02263     return ~lowBitsSet;
02264   }
02265 
02266   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
02267   // Any value less than the RHS must differ in a higher bit because of carries.
02268   case ICmpInst::ICMP_ULT: {
02269     unsigned trailingZeros = RHS.countTrailingZeros();
02270     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
02271     return ~lowBitsSet;
02272   }
02273 
02274   default:
02275     return APInt::getAllOnesValue(BitWidth);
02276   }
02277 
02278 }
02279 
02280 /// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
02281 /// should be swapped.
02282 /// The decision is based on how many times these two operands are reused
02283 /// as subtract operands and their positions in those instructions.
02284 /// The rational is that several architectures use the same instruction for
02285 /// both subtract and cmp, thus it is better if the order of those operands
02286 /// match.
02287 /// \return true if Op0 and Op1 should be swapped.
02288 static bool swapMayExposeCSEOpportunities(const Value * Op0,
02289                                           const Value * Op1) {
02290   // Filter out pointer value as those cannot appears directly in subtract.
02291   // FIXME: we may want to go through inttoptrs or bitcasts.
02292   if (Op0->getType()->isPointerTy())
02293     return false;
02294   // Count every uses of both Op0 and Op1 in a subtract.
02295   // Each time Op0 is the first operand, count -1: swapping is bad, the
02296   // subtract has already the same layout as the compare.
02297   // Each time Op0 is the second operand, count +1: swapping is good, the
02298   // subtract has a different layout as the compare.
02299   // At the end, if the benefit is greater than 0, Op0 should come second to
02300   // expose more CSE opportunities.
02301   int GlobalSwapBenefits = 0;
02302   for (const User *U : Op0->users()) {
02303     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
02304     if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
02305       continue;
02306     // If Op0 is the first argument, this is not beneficial to swap the
02307     // arguments.
02308     int LocalSwapBenefits = -1;
02309     unsigned Op1Idx = 1;
02310     if (BinOp->getOperand(Op1Idx) == Op0) {
02311       Op1Idx = 0;
02312       LocalSwapBenefits = 1;
02313     }
02314     if (BinOp->getOperand(Op1Idx) != Op1)
02315       continue;
02316     GlobalSwapBenefits += LocalSwapBenefits;
02317   }
02318   return GlobalSwapBenefits > 0;
02319 }
02320 
02321 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
02322   bool Changed = false;
02323   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02324   unsigned Op0Cplxity = getComplexity(Op0);
02325   unsigned Op1Cplxity = getComplexity(Op1);
02326 
02327   /// Orders the operands of the compare so that they are listed from most
02328   /// complex to least complex.  This puts constants before unary operators,
02329   /// before binary operators.
02330   if (Op0Cplxity < Op1Cplxity ||
02331         (Op0Cplxity == Op1Cplxity &&
02332          swapMayExposeCSEOpportunities(Op0, Op1))) {
02333     I.swapOperands();
02334     std::swap(Op0, Op1);
02335     Changed = true;
02336   }
02337 
02338   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL))
02339     return ReplaceInstUsesWith(I, V);
02340 
02341   // comparing -val or val with non-zero is the same as just comparing val
02342   // ie, abs(val) != 0 -> val != 0
02343   if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
02344   {
02345     Value *Cond, *SelectTrue, *SelectFalse;
02346     if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
02347                             m_Value(SelectFalse)))) {
02348       if (Value *V = dyn_castNegVal(SelectTrue)) {
02349         if (V == SelectFalse)
02350           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
02351       }
02352       else if (Value *V = dyn_castNegVal(SelectFalse)) {
02353         if (V == SelectTrue)
02354           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
02355       }
02356     }
02357   }
02358 
02359   Type *Ty = Op0->getType();
02360 
02361   // icmp's with boolean values can always be turned into bitwise operations
02362   if (Ty->isIntegerTy(1)) {
02363     switch (I.getPredicate()) {
02364     default: llvm_unreachable("Invalid icmp instruction!");
02365     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
02366       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
02367       return BinaryOperator::CreateNot(Xor);
02368     }
02369     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
02370       return BinaryOperator::CreateXor(Op0, Op1);
02371 
02372     case ICmpInst::ICMP_UGT:
02373       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
02374       // FALL THROUGH
02375     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
02376       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
02377       return BinaryOperator::CreateAnd(Not, Op1);
02378     }
02379     case ICmpInst::ICMP_SGT:
02380       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
02381       // FALL THROUGH
02382     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
02383       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
02384       return BinaryOperator::CreateAnd(Not, Op0);
02385     }
02386     case ICmpInst::ICMP_UGE:
02387       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
02388       // FALL THROUGH
02389     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
02390       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
02391       return BinaryOperator::CreateOr(Not, Op1);
02392     }
02393     case ICmpInst::ICMP_SGE:
02394       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
02395       // FALL THROUGH
02396     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
02397       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
02398       return BinaryOperator::CreateOr(Not, Op0);
02399     }
02400     }
02401   }
02402 
02403   unsigned BitWidth = 0;
02404   if (Ty->isIntOrIntVectorTy())
02405     BitWidth = Ty->getScalarSizeInBits();
02406   else if (DL)  // Pointers require DL info to get their size.
02407     BitWidth = DL->getTypeSizeInBits(Ty->getScalarType());
02408 
02409   bool isSignBit = false;
02410 
02411   // See if we are doing a comparison with a constant.
02412   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02413     Value *A = 0, *B = 0;
02414 
02415     // Match the following pattern, which is a common idiom when writing
02416     // overflow-safe integer arithmetic function.  The source performs an
02417     // addition in wider type, and explicitly checks for overflow using
02418     // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
02419     // sadd_with_overflow intrinsic.
02420     //
02421     // TODO: This could probably be generalized to handle other overflow-safe
02422     // operations if we worked out the formulas to compute the appropriate
02423     // magic constants.
02424     //
02425     // sum = a + b
02426     // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
02427     {
02428     ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
02429     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
02430         match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
02431       if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
02432         return Res;
02433     }
02434 
02435     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
02436     if (I.isEquality() && CI->isZero() &&
02437         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
02438       // (icmp cond A B) if cond is equality
02439       return new ICmpInst(I.getPredicate(), A, B);
02440     }
02441 
02442     // If we have an icmp le or icmp ge instruction, turn it into the
02443     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
02444     // them being folded in the code below.  The SimplifyICmpInst code has
02445     // already handled the edge cases for us, so we just assert on them.
02446     switch (I.getPredicate()) {
02447     default: break;
02448     case ICmpInst::ICMP_ULE:
02449       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
02450       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
02451                           Builder->getInt(CI->getValue()+1));
02452     case ICmpInst::ICMP_SLE:
02453       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
02454       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
02455                           Builder->getInt(CI->getValue()+1));
02456     case ICmpInst::ICMP_UGE:
02457       assert(!CI->isMinValue(false));                 // A >=u MIN -> TRUE
02458       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
02459                           Builder->getInt(CI->getValue()-1));
02460     case ICmpInst::ICMP_SGE:
02461       assert(!CI->isMinValue(true));                  // A >=s MIN -> TRUE
02462       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
02463                           Builder->getInt(CI->getValue()-1));
02464     }
02465 
02466     // If this comparison is a normal comparison, it demands all
02467     // bits, if it is a sign bit comparison, it only demands the sign bit.
02468     bool UnusedBit;
02469     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
02470   }
02471 
02472   // See if we can fold the comparison based on range information we can get
02473   // by checking whether bits are known to be zero or one in the input.
02474   if (BitWidth != 0) {
02475     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
02476     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
02477 
02478     if (SimplifyDemandedBits(I.getOperandUse(0),
02479                              DemandedBitsLHSMask(I, BitWidth, isSignBit),
02480                              Op0KnownZero, Op0KnownOne, 0))
02481       return &I;
02482     if (SimplifyDemandedBits(I.getOperandUse(1),
02483                              APInt::getAllOnesValue(BitWidth),
02484                              Op1KnownZero, Op1KnownOne, 0))
02485       return &I;
02486 
02487     // Given the known and unknown bits, compute a range that the LHS could be
02488     // in.  Compute the Min, Max and RHS values based on the known bits. For the
02489     // EQ and NE we use unsigned values.
02490     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
02491     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
02492     if (I.isSigned()) {
02493       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
02494                                              Op0Min, Op0Max);
02495       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
02496                                              Op1Min, Op1Max);
02497     } else {
02498       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
02499                                                Op0Min, Op0Max);
02500       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
02501                                                Op1Min, Op1Max);
02502     }
02503 
02504     // If Min and Max are known to be the same, then SimplifyDemandedBits
02505     // figured out that the LHS is a constant.  Just constant fold this now so
02506     // that code below can assume that Min != Max.
02507     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
02508       return new ICmpInst(I.getPredicate(),
02509                           ConstantInt::get(Op0->getType(), Op0Min), Op1);
02510     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
02511       return new ICmpInst(I.getPredicate(), Op0,
02512                           ConstantInt::get(Op1->getType(), Op1Min));
02513 
02514     // Based on the range information we know about the LHS, see if we can
02515     // simplify this comparison.  For example, (x&4) < 8 is always true.
02516     switch (I.getPredicate()) {
02517     default: llvm_unreachable("Unknown icmp opcode!");
02518     case ICmpInst::ICMP_EQ: {
02519       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
02520         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02521 
02522       // If all bits are known zero except for one, then we know at most one
02523       // bit is set.   If the comparison is against zero, then this is a check
02524       // to see if *that* bit is set.
02525       APInt Op0KnownZeroInverted = ~Op0KnownZero;
02526       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
02527         // If the LHS is an AND with the same constant, look through it.
02528         Value *LHS = 0;
02529         ConstantInt *LHSC = 0;
02530         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
02531             LHSC->getValue() != Op0KnownZeroInverted)
02532           LHS = Op0;
02533 
02534         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
02535         // then turn "((1 << x)&8) == 0" into "x != 3".
02536         Value *X = 0;
02537         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
02538           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
02539           return new ICmpInst(ICmpInst::ICMP_NE, X,
02540                               ConstantInt::get(X->getType(), CmpVal));
02541         }
02542 
02543         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
02544         // then turn "((8 >>u x)&1) == 0" into "x != 3".
02545         const APInt *CI;
02546         if (Op0KnownZeroInverted == 1 &&
02547             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
02548           return new ICmpInst(ICmpInst::ICMP_NE, X,
02549                               ConstantInt::get(X->getType(),
02550                                                CI->countTrailingZeros()));
02551       }
02552 
02553       break;
02554     }
02555     case ICmpInst::ICMP_NE: {
02556       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
02557         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02558 
02559       // If all bits are known zero except for one, then we know at most one
02560       // bit is set.   If the comparison is against zero, then this is a check
02561       // to see if *that* bit is set.
02562       APInt Op0KnownZeroInverted = ~Op0KnownZero;
02563       if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) {
02564         // If the LHS is an AND with the same constant, look through it.
02565         Value *LHS = 0;
02566         ConstantInt *LHSC = 0;
02567         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
02568             LHSC->getValue() != Op0KnownZeroInverted)
02569           LHS = Op0;
02570 
02571         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
02572         // then turn "((1 << x)&8) != 0" into "x == 3".
02573         Value *X = 0;
02574         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
02575           unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros();
02576           return new ICmpInst(ICmpInst::ICMP_EQ, X,
02577                               ConstantInt::get(X->getType(), CmpVal));
02578         }
02579 
02580         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
02581         // then turn "((8 >>u x)&1) != 0" into "x == 3".
02582         const APInt *CI;
02583         if (Op0KnownZeroInverted == 1 &&
02584             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
02585           return new ICmpInst(ICmpInst::ICMP_EQ, X,
02586                               ConstantInt::get(X->getType(),
02587                                                CI->countTrailingZeros()));
02588       }
02589 
02590       break;
02591     }
02592     case ICmpInst::ICMP_ULT:
02593       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
02594         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02595       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
02596         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02597       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
02598         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
02599       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02600         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
02601           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
02602                               Builder->getInt(CI->getValue()-1));
02603 
02604         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
02605         if (CI->isMinValue(true))
02606           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
02607                            Constant::getAllOnesValue(Op0->getType()));
02608       }
02609       break;
02610     case ICmpInst::ICMP_UGT:
02611       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
02612         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02613       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
02614         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02615 
02616       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
02617         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
02618       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02619         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
02620           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
02621                               Builder->getInt(CI->getValue()+1));
02622 
02623         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
02624         if (CI->isMaxValue(true))
02625           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
02626                               Constant::getNullValue(Op0->getType()));
02627       }
02628       break;
02629     case ICmpInst::ICMP_SLT:
02630       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
02631         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02632       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
02633         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02634       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
02635         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
02636       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02637         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
02638           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
02639                               Builder->getInt(CI->getValue()-1));
02640       }
02641       break;
02642     case ICmpInst::ICMP_SGT:
02643       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
02644         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02645       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
02646         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02647 
02648       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
02649         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
02650       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02651         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
02652           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
02653                               Builder->getInt(CI->getValue()+1));
02654       }
02655       break;
02656     case ICmpInst::ICMP_SGE:
02657       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
02658       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
02659         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02660       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
02661         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02662       break;
02663     case ICmpInst::ICMP_SLE:
02664       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
02665       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
02666         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02667       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
02668         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02669       break;
02670     case ICmpInst::ICMP_UGE:
02671       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
02672       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
02673         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02674       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
02675         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02676       break;
02677     case ICmpInst::ICMP_ULE:
02678       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
02679       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
02680         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02681       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
02682         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02683       break;
02684     }
02685 
02686     // Turn a signed comparison into an unsigned one if both operands
02687     // are known to have the same sign.
02688     if (I.isSigned() &&
02689         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
02690          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
02691       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
02692   }
02693 
02694   // Test if the ICmpInst instruction is used exclusively by a select as
02695   // part of a minimum or maximum operation. If so, refrain from doing
02696   // any other folding. This helps out other analyses which understand
02697   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
02698   // and CodeGen. And in this case, at least one of the comparison
02699   // operands has at least one user besides the compare (the select),
02700   // which would often largely negate the benefit of folding anyway.
02701   if (I.hasOneUse())
02702     if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
02703       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
02704           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
02705         return 0;
02706 
02707   // See if we are doing a comparison between a constant and an instruction that
02708   // can be folded into the comparison.
02709   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02710     // Since the RHS is a ConstantInt (CI), if the left hand side is an
02711     // instruction, see if that instruction also has constants so that the
02712     // instruction can be folded into the icmp
02713     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
02714       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
02715         return Res;
02716   }
02717 
02718   // Handle icmp with constant (but not simple integer constant) RHS
02719   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
02720     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
02721       switch (LHSI->getOpcode()) {
02722       case Instruction::GetElementPtr:
02723           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
02724         if (RHSC->isNullValue() &&
02725             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
02726           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
02727                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
02728         break;
02729       case Instruction::PHI:
02730         // Only fold icmp into the PHI if the phi and icmp are in the same
02731         // block.  If in the same block, we're encouraging jump threading.  If
02732         // not, we are just pessimizing the code by making an i1 phi.
02733         if (LHSI->getParent() == I.getParent())
02734           if (Instruction *NV = FoldOpIntoPhi(I))
02735             return NV;
02736         break;
02737       case Instruction::Select: {
02738         // If either operand of the select is a constant, we can fold the
02739         // comparison into the select arms, which will cause one to be
02740         // constant folded and the select turned into a bitwise or.
02741         Value *Op1 = 0, *Op2 = 0;
02742         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
02743           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
02744         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
02745           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
02746 
02747         // We only want to perform this transformation if it will not lead to
02748         // additional code. This is true if either both sides of the select
02749         // fold to a constant (in which case the icmp is replaced with a select
02750         // which will usually simplify) or this is the only user of the
02751         // select (in which case we are trading a select+icmp for a simpler
02752         // select+icmp).
02753         if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
02754           if (!Op1)
02755             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
02756                                       RHSC, I.getName());
02757           if (!Op2)
02758             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
02759                                       RHSC, I.getName());
02760           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
02761         }
02762         break;
02763       }
02764       case Instruction::IntToPtr:
02765         // icmp pred inttoptr(X), null -> icmp pred X, 0
02766         if (RHSC->isNullValue() && DL &&
02767             DL->getIntPtrType(RHSC->getType()) ==
02768                LHSI->getOperand(0)->getType())
02769           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
02770                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
02771         break;
02772 
02773       case Instruction::Load:
02774         // Try to optimize things like "A[i] > 4" to index computations.
02775         if (GetElementPtrInst *GEP =
02776               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
02777           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
02778             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
02779                 !cast<LoadInst>(LHSI)->isVolatile())
02780               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
02781                 return Res;
02782         }
02783         break;
02784       }
02785   }
02786 
02787   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
02788   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
02789     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
02790       return NI;
02791   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
02792     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
02793                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
02794       return NI;
02795 
02796   // Test to see if the operands of the icmp are casted versions of other
02797   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
02798   // now.
02799   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
02800     if (Op0->getType()->isPointerTy() &&
02801         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
02802       // We keep moving the cast from the left operand over to the right
02803       // operand, where it can often be eliminated completely.
02804       Op0 = CI->getOperand(0);
02805 
02806       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
02807       // so eliminate it as well.
02808       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
02809         Op1 = CI2->getOperand(0);
02810 
02811       // If Op1 is a constant, we can fold the cast into the constant.
02812       if (Op0->getType() != Op1->getType()) {
02813         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
02814           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
02815         } else {
02816           // Otherwise, cast the RHS right before the icmp
02817           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
02818         }
02819       }
02820       return new ICmpInst(I.getPredicate(), Op0, Op1);
02821     }
02822   }
02823 
02824   if (isa<CastInst>(Op0)) {
02825     // Handle the special case of: icmp (cast bool to X), <cst>
02826     // This comes up when you have code like
02827     //   int X = A < B;
02828     //   if (X) ...
02829     // For generality, we handle any zero-extension of any operand comparison
02830     // with a constant or another cast from the same type.
02831     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
02832       if (Instruction *R = visitICmpInstWithCastAndCast(I))
02833         return R;
02834   }
02835 
02836   // Special logic for binary operators.
02837   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
02838   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
02839   if (BO0 || BO1) {
02840     CmpInst::Predicate Pred = I.getPredicate();
02841     bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
02842     if (BO0 && isa<OverflowingBinaryOperator>(BO0))
02843       NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
02844         (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
02845         (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
02846     if (BO1 && isa<OverflowingBinaryOperator>(BO1))
02847       NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
02848         (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
02849         (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
02850 
02851     // Analyze the case when either Op0 or Op1 is an add instruction.
02852     // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
02853     Value *A = 0, *B = 0, *C = 0, *D = 0;
02854     if (BO0 && BO0->getOpcode() == Instruction::Add)
02855       A = BO0->getOperand(0), B = BO0->getOperand(1);
02856     if (BO1 && BO1->getOpcode() == Instruction::Add)
02857       C = BO1->getOperand(0), D = BO1->getOperand(1);
02858 
02859     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
02860     if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
02861       return new ICmpInst(Pred, A == Op1 ? B : A,
02862                           Constant::getNullValue(Op1->getType()));
02863 
02864     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
02865     if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
02866       return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
02867                           C == Op0 ? D : C);
02868 
02869     // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
02870     if (A && C && (A == C || A == D || B == C || B == D) &&
02871         NoOp0WrapProblem && NoOp1WrapProblem &&
02872         // Try not to increase register pressure.
02873         BO0->hasOneUse() && BO1->hasOneUse()) {
02874       // Determine Y and Z in the form icmp (X+Y), (X+Z).
02875       Value *Y, *Z;
02876       if (A == C) {
02877         // C + B == C + D  ->  B == D
02878         Y = B;
02879         Z = D;
02880       } else if (A == D) {
02881         // D + B == C + D  ->  B == C
02882         Y = B;
02883         Z = C;
02884       } else if (B == C) {
02885         // A + C == C + D  ->  A == D
02886         Y = A;
02887         Z = D;
02888       } else {
02889         assert(B == D);
02890         // A + D == C + D  ->  A == C
02891         Y = A;
02892         Z = C;
02893       }
02894       return new ICmpInst(Pred, Y, Z);
02895     }
02896 
02897     // icmp slt (X + -1), Y -> icmp sle X, Y
02898     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
02899         match(B, m_AllOnes()))
02900       return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
02901 
02902     // icmp sge (X + -1), Y -> icmp sgt X, Y
02903     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
02904         match(B, m_AllOnes()))
02905       return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
02906 
02907     // icmp sle (X + 1), Y -> icmp slt X, Y
02908     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
02909         match(B, m_One()))
02910       return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
02911 
02912     // icmp sgt (X + 1), Y -> icmp sge X, Y
02913     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
02914         match(B, m_One()))
02915       return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
02916 
02917     // if C1 has greater magnitude than C2:
02918     //  icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
02919     //  s.t. C3 = C1 - C2
02920     //
02921     // if C2 has greater magnitude than C1:
02922     //  icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
02923     //  s.t. C3 = C2 - C1
02924     if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
02925         (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
02926       if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
02927         if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
02928           const APInt &AP1 = C1->getValue();
02929           const APInt &AP2 = C2->getValue();
02930           if (AP1.isNegative() == AP2.isNegative()) {
02931             APInt AP1Abs = C1->getValue().abs();
02932             APInt AP2Abs = C2->getValue().abs();
02933             if (AP1Abs.uge(AP2Abs)) {
02934               ConstantInt *C3 = Builder->getInt(AP1 - AP2);
02935               Value *NewAdd = Builder->CreateNSWAdd(A, C3);
02936               return new ICmpInst(Pred, NewAdd, C);
02937             } else {
02938               ConstantInt *C3 = Builder->getInt(AP2 - AP1);
02939               Value *NewAdd = Builder->CreateNSWAdd(C, C3);
02940               return new ICmpInst(Pred, A, NewAdd);
02941             }
02942           }
02943         }
02944 
02945 
02946     // Analyze the case when either Op0 or Op1 is a sub instruction.
02947     // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
02948     A = 0; B = 0; C = 0; D = 0;
02949     if (BO0 && BO0->getOpcode() == Instruction::Sub)
02950       A = BO0->getOperand(0), B = BO0->getOperand(1);
02951     if (BO1 && BO1->getOpcode() == Instruction::Sub)
02952       C = BO1->getOperand(0), D = BO1->getOperand(1);
02953 
02954     // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
02955     if (A == Op1 && NoOp0WrapProblem)
02956       return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
02957 
02958     // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
02959     if (C == Op0 && NoOp1WrapProblem)
02960       return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
02961 
02962     // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
02963     if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
02964         // Try not to increase register pressure.
02965         BO0->hasOneUse() && BO1->hasOneUse())
02966       return new ICmpInst(Pred, A, C);
02967 
02968     // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
02969     if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
02970         // Try not to increase register pressure.
02971         BO0->hasOneUse() && BO1->hasOneUse())
02972       return new ICmpInst(Pred, D, B);
02973 
02974     BinaryOperator *SRem = NULL;
02975     // icmp (srem X, Y), Y
02976     if (BO0 && BO0->getOpcode() == Instruction::SRem &&
02977         Op1 == BO0->getOperand(1))
02978       SRem = BO0;
02979     // icmp Y, (srem X, Y)
02980     else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
02981              Op0 == BO1->getOperand(1))
02982       SRem = BO1;
02983     if (SRem) {
02984       // We don't check hasOneUse to avoid increasing register pressure because
02985       // the value we use is the same value this instruction was already using.
02986       switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
02987         default: break;
02988         case ICmpInst::ICMP_EQ:
02989           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02990         case ICmpInst::ICMP_NE:
02991           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02992         case ICmpInst::ICMP_SGT:
02993         case ICmpInst::ICMP_SGE:
02994           return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
02995                               Constant::getAllOnesValue(SRem->getType()));
02996         case ICmpInst::ICMP_SLT:
02997         case ICmpInst::ICMP_SLE:
02998           return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
02999                               Constant::getNullValue(SRem->getType()));
03000       }
03001     }
03002 
03003     if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
03004         BO0->hasOneUse() && BO1->hasOneUse() &&
03005         BO0->getOperand(1) == BO1->getOperand(1)) {
03006       switch (BO0->getOpcode()) {
03007       default: break;
03008       case Instruction::Add:
03009       case Instruction::Sub:
03010       case Instruction::Xor:
03011         if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
03012           return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
03013                               BO1->getOperand(0));
03014         // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
03015         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
03016           if (CI->getValue().isSignBit()) {
03017             ICmpInst::Predicate Pred = I.isSigned()
03018                                            ? I.getUnsignedPredicate()
03019                                            : I.getSignedPredicate();
03020             return new ICmpInst(Pred, BO0->getOperand(0),
03021                                 BO1->getOperand(0));
03022           }
03023 
03024           if (CI->isMaxValue(true)) {
03025             ICmpInst::Predicate Pred = I.isSigned()
03026                                            ? I.getUnsignedPredicate()
03027                                            : I.getSignedPredicate();
03028             Pred = I.getSwappedPredicate(Pred);
03029             return new ICmpInst(Pred, BO0->getOperand(0),
03030                                 BO1->getOperand(0));
03031           }
03032         }
03033         break;
03034       case Instruction::Mul:
03035         if (!I.isEquality())
03036           break;
03037 
03038         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
03039           // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
03040           // Mask = -1 >> count-trailing-zeros(Cst).
03041           if (!CI->isZero() && !CI->isOne()) {
03042             const APInt &AP = CI->getValue();
03043             ConstantInt *Mask = ConstantInt::get(I.getContext(),
03044                                     APInt::getLowBitsSet(AP.getBitWidth(),
03045                                                          AP.getBitWidth() -
03046                                                     AP.countTrailingZeros()));
03047             Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
03048             Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
03049             return new ICmpInst(I.getPredicate(), And1, And2);
03050           }
03051         }
03052         break;
03053       case Instruction::UDiv:
03054       case Instruction::LShr:
03055         if (I.isSigned())
03056           break;
03057         // fall-through
03058       case Instruction::SDiv:
03059       case Instruction::AShr:
03060         if (!BO0->isExact() || !BO1->isExact())
03061           break;
03062         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
03063                             BO1->getOperand(0));
03064       case Instruction::Shl: {
03065         bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
03066         bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
03067         if (!NUW && !NSW)
03068           break;
03069         if (!NSW && I.isSigned())
03070           break;
03071         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
03072                             BO1->getOperand(0));
03073       }
03074       }
03075     }
03076   }
03077 
03078   { Value *A, *B;
03079     // Transform (A & ~B) == 0 --> (A & B) != 0
03080     // and       (A & ~B) != 0 --> (A & B) == 0
03081     // if A is a power of 2.
03082     if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
03083         match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality())
03084       return new ICmpInst(I.getInversePredicate(),
03085                           Builder->CreateAnd(A, B),
03086                           Op1);
03087 
03088     // ~x < ~y --> y < x
03089     // ~x < cst --> ~cst < x
03090     if (match(Op0, m_Not(m_Value(A)))) {
03091       if (match(Op1, m_Not(m_Value(B))))
03092         return new ICmpInst(I.getPredicate(), B, A);
03093       if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
03094         return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
03095     }
03096 
03097     // (a+b) <u a  --> llvm.uadd.with.overflow.
03098     // (a+b) <u b  --> llvm.uadd.with.overflow.
03099     if (I.getPredicate() == ICmpInst::ICMP_ULT &&
03100         match(Op0, m_Add(m_Value(A), m_Value(B))) &&
03101         (Op1 == A || Op1 == B))
03102       if (Instruction *R = ProcessUAddIdiom(I, Op0, *this))
03103         return R;
03104 
03105     // a >u (a+b)  --> llvm.uadd.with.overflow.
03106     // b >u (a+b)  --> llvm.uadd.with.overflow.
03107     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
03108         match(Op1, m_Add(m_Value(A), m_Value(B))) &&
03109         (Op0 == A || Op0 == B))
03110       if (Instruction *R = ProcessUAddIdiom(I, Op1, *this))
03111         return R;
03112 
03113     // (zext a) * (zext b)  --> llvm.umul.with.overflow.
03114     if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
03115       if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
03116         return R;
03117     }
03118     if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
03119       if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
03120         return R;
03121     }
03122   }
03123 
03124   if (I.isEquality()) {
03125     Value *A, *B, *C, *D;
03126 
03127     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
03128       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
03129         Value *OtherVal = A == Op1 ? B : A;
03130         return new ICmpInst(I.getPredicate(), OtherVal,
03131                             Constant::getNullValue(A->getType()));
03132       }
03133 
03134       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
03135         // A^c1 == C^c2 --> A == C^(c1^c2)
03136         ConstantInt *C1, *C2;
03137         if (match(B, m_ConstantInt(C1)) &&
03138             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
03139           Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
03140           Value *Xor = Builder->CreateXor(C, NC);
03141           return new ICmpInst(I.getPredicate(), A, Xor);
03142         }
03143 
03144         // A^B == A^D -> B == D
03145         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
03146         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
03147         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
03148         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
03149       }
03150     }
03151 
03152     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
03153         (A == Op0 || B == Op0)) {
03154       // A == (A^B)  ->  B == 0
03155       Value *OtherVal = A == Op0 ? B : A;
03156       return new ICmpInst(I.getPredicate(), OtherVal,
03157                           Constant::getNullValue(A->getType()));
03158     }
03159 
03160     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
03161     if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
03162         match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
03163       Value *X = 0, *Y = 0, *Z = 0;
03164 
03165       if (A == C) {
03166         X = B; Y = D; Z = A;
03167       } else if (A == D) {
03168         X = B; Y = C; Z = A;
03169       } else if (B == C) {
03170         X = A; Y = D; Z = B;
03171       } else if (B == D) {
03172         X = A; Y = C; Z = B;
03173       }
03174 
03175       if (X) {   // Build (X^Y) & Z
03176         Op1 = Builder->CreateXor(X, Y);
03177         Op1 = Builder->CreateAnd(Op1, Z);
03178         I.setOperand(0, Op1);
03179         I.setOperand(1, Constant::getNullValue(Op1->getType()));
03180         return &I;
03181       }
03182     }
03183 
03184     // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
03185     // and       (B & (1<<X)-1) == (zext A) --> A == (trunc B)
03186     ConstantInt *Cst1;
03187     if ((Op0->hasOneUse() &&
03188          match(Op0, m_ZExt(m_Value(A))) &&
03189          match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
03190         (Op1->hasOneUse() &&
03191          match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
03192          match(Op1, m_ZExt(m_Value(A))))) {
03193       APInt Pow2 = Cst1->getValue() + 1;
03194       if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
03195           Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
03196         return new ICmpInst(I.getPredicate(), A,
03197                             Builder->CreateTrunc(B, A->getType()));
03198     }
03199 
03200     // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
03201     // For lshr and ashr pairs.
03202     if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
03203          match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
03204         (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
03205          match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
03206       unsigned TypeBits = Cst1->getBitWidth();
03207       unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
03208       if (ShAmt < TypeBits && ShAmt != 0) {
03209         ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
03210                                        ? ICmpInst::ICMP_UGE
03211                                        : ICmpInst::ICMP_ULT;
03212         Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
03213         APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
03214         return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
03215       }
03216     }
03217 
03218     // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
03219     // "icmp (and X, mask), cst"
03220     uint64_t ShAmt = 0;
03221     if (Op0->hasOneUse() &&
03222         match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
03223                                            m_ConstantInt(ShAmt))))) &&
03224         match(Op1, m_ConstantInt(Cst1)) &&
03225         // Only do this when A has multiple uses.  This is most important to do
03226         // when it exposes other optimizations.
03227         !A->hasOneUse()) {
03228       unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
03229 
03230       if (ShAmt < ASize) {
03231         APInt MaskV =
03232           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
03233         MaskV <<= ShAmt;
03234 
03235         APInt CmpV = Cst1->getValue().zext(ASize);
03236         CmpV <<= ShAmt;
03237 
03238         Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
03239         return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
03240       }
03241     }
03242   }
03243 
03244   {
03245     Value *X; ConstantInt *Cst;
03246     // icmp X+Cst, X
03247     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
03248       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
03249 
03250     // icmp X, X+Cst
03251     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
03252       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
03253   }
03254   return Changed ? &I : 0;
03255 }
03256 
03257 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
03258 ///
03259 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
03260                                                 Instruction *LHSI,
03261                                                 Constant *RHSC) {
03262   if (!isa<ConstantFP>(RHSC)) return 0;
03263   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
03264 
03265   // Get the width of the mantissa.  We don't want to hack on conversions that
03266   // might lose information from the integer, e.g. "i64 -> float"
03267   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
03268   if (MantissaWidth == -1) return 0;  // Unknown.
03269 
03270   // Check to see that the input is converted from an integer type that is small
03271   // enough that preserves all bits.  TODO: check here for "known" sign bits.
03272   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
03273   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
03274 
03275   // If this is a uitofp instruction, we need an extra bit to hold the sign.
03276   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
03277   if (LHSUnsigned)
03278     ++InputSize;
03279 
03280   // If the conversion would lose info, don't hack on this.
03281   if ((int)InputSize > MantissaWidth)
03282     return 0;
03283 
03284   // Otherwise, we can potentially simplify the comparison.  We know that it
03285   // will always come through as an integer value and we know the constant is
03286   // not a NAN (it would have been previously simplified).
03287   assert(!RHS.isNaN() && "NaN comparison not already folded!");
03288 
03289   ICmpInst::Predicate Pred;
03290   switch (I.getPredicate()) {
03291   default: llvm_unreachable("Unexpected predicate!");
03292   case FCmpInst::FCMP_UEQ:
03293   case FCmpInst::FCMP_OEQ:
03294     Pred = ICmpInst::ICMP_EQ;
03295     break;
03296   case FCmpInst::FCMP_UGT:
03297   case FCmpInst::FCMP_OGT:
03298     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
03299     break;
03300   case FCmpInst::FCMP_UGE:
03301   case FCmpInst::FCMP_OGE:
03302     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
03303     break;
03304   case FCmpInst::FCMP_ULT:
03305   case FCmpInst::FCMP_OLT:
03306     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
03307     break;
03308   case FCmpInst::FCMP_ULE:
03309   case FCmpInst::FCMP_OLE:
03310     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
03311     break;
03312   case FCmpInst::FCMP_UNE:
03313   case FCmpInst::FCMP_ONE:
03314     Pred = ICmpInst::ICMP_NE;
03315     break;
03316   case FCmpInst::FCMP_ORD:
03317     return ReplaceInstUsesWith(I, Builder->getTrue());
03318   case FCmpInst::FCMP_UNO:
03319     return ReplaceInstUsesWith(I, Builder->getFalse());
03320   }
03321 
03322   IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
03323 
03324   // Now we know that the APFloat is a normal number, zero or inf.
03325 
03326   // See if the FP constant is too large for the integer.  For example,
03327   // comparing an i8 to 300.0.
03328   unsigned IntWidth = IntTy->getScalarSizeInBits();
03329 
03330   if (!LHSUnsigned) {
03331     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
03332     // and large values.
03333     APFloat SMax(RHS.getSemantics());
03334     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
03335                           APFloat::rmNearestTiesToEven);
03336     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
03337       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
03338           Pred == ICmpInst::ICMP_SLE)
03339         return ReplaceInstUsesWith(I, Builder->getTrue());
03340       return ReplaceInstUsesWith(I, Builder->getFalse());
03341     }
03342   } else {
03343     // If the RHS value is > UnsignedMax, fold the comparison. This handles
03344     // +INF and large values.
03345     APFloat UMax(RHS.getSemantics());
03346     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
03347                           APFloat::rmNearestTiesToEven);
03348     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
03349       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
03350           Pred == ICmpInst::ICMP_ULE)
03351         return ReplaceInstUsesWith(I, Builder->getTrue());
03352       return ReplaceInstUsesWith(I, Builder->getFalse());
03353     }
03354   }
03355 
03356   if (!LHSUnsigned) {
03357     // See if the RHS value is < SignedMin.
03358     APFloat SMin(RHS.getSemantics());
03359     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
03360                           APFloat::rmNearestTiesToEven);
03361     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
03362       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
03363           Pred == ICmpInst::ICMP_SGE)
03364         return ReplaceInstUsesWith(I, Builder->getTrue());
03365       return ReplaceInstUsesWith(I, Builder->getFalse());
03366     }
03367   } else {
03368     // See if the RHS value is < UnsignedMin.
03369     APFloat SMin(RHS.getSemantics());
03370     SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
03371                           APFloat::rmNearestTiesToEven);
03372     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
03373       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
03374           Pred == ICmpInst::ICMP_UGE)
03375         return ReplaceInstUsesWith(I, Builder->getTrue());
03376       return ReplaceInstUsesWith(I, Builder->getFalse());
03377     }
03378   }
03379 
03380   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
03381   // [0, UMAX], but it may still be fractional.  See if it is fractional by
03382   // casting the FP value to the integer value and back, checking for equality.
03383   // Don't do this for zero, because -0.0 is not fractional.
03384   Constant *RHSInt = LHSUnsigned
03385     ? ConstantExpr::getFPToUI(RHSC, IntTy)
03386     : ConstantExpr::getFPToSI(RHSC, IntTy);
03387   if (!RHS.isZero()) {
03388     bool Equal = LHSUnsigned
03389       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
03390       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
03391     if (!Equal) {
03392       // If we had a comparison against a fractional value, we have to adjust
03393       // the compare predicate and sometimes the value.  RHSC is rounded towards
03394       // zero at this point.
03395       switch (Pred) {
03396       default: llvm_unreachable("Unexpected integer comparison!");
03397       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
03398         return ReplaceInstUsesWith(I, Builder->getTrue());
03399       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
03400         return ReplaceInstUsesWith(I, Builder->getFalse());
03401       case ICmpInst::ICMP_ULE:
03402         // (float)int <= 4.4   --> int <= 4
03403         // (float)int <= -4.4  --> false
03404         if (RHS.isNegative())
03405           return ReplaceInstUsesWith(I, Builder->getFalse());
03406         break;
03407       case ICmpInst::ICMP_SLE:
03408         // (float)int <= 4.4   --> int <= 4
03409         // (float)int <= -4.4  --> int < -4
03410         if (RHS.isNegative())
03411           Pred = ICmpInst::ICMP_SLT;
03412         break;
03413       case ICmpInst::ICMP_ULT:
03414         // (float)int < -4.4   --> false
03415         // (float)int < 4.4    --> int <= 4
03416         if (RHS.isNegative())
03417           return ReplaceInstUsesWith(I, Builder->getFalse());
03418         Pred = ICmpInst::ICMP_ULE;
03419         break;
03420       case ICmpInst::ICMP_SLT:
03421         // (float)int < -4.4   --> int < -4
03422         // (float)int < 4.4    --> int <= 4
03423         if (!RHS.isNegative())
03424           Pred = ICmpInst::ICMP_SLE;
03425         break;
03426       case ICmpInst::ICMP_UGT:
03427         // (float)int > 4.4    --> int > 4
03428         // (float)int > -4.4   --> true
03429         if (RHS.isNegative())
03430           return ReplaceInstUsesWith(I, Builder->getTrue());
03431         break;
03432       case ICmpInst::ICMP_SGT:
03433         // (float)int > 4.4    --> int > 4
03434         // (float)int > -4.4   --> int >= -4
03435         if (RHS.isNegative())
03436           Pred = ICmpInst::ICMP_SGE;
03437         break;
03438       case ICmpInst::ICMP_UGE:
03439         // (float)int >= -4.4   --> true
03440         // (float)int >= 4.4    --> int > 4
03441         if (RHS.isNegative())
03442           return ReplaceInstUsesWith(I, Builder->getTrue());
03443         Pred = ICmpInst::ICMP_UGT;
03444         break;
03445       case ICmpInst::ICMP_SGE:
03446         // (float)int >= -4.4   --> int >= -4
03447         // (float)int >= 4.4    --> int > 4
03448         if (!RHS.isNegative())
03449           Pred = ICmpInst::ICMP_SGT;
03450         break;
03451       }
03452     }
03453   }
03454 
03455   // Lower this FP comparison into an appropriate integer version of the
03456   // comparison.
03457   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
03458 }
03459 
03460 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
03461   bool Changed = false;
03462 
03463   /// Orders the operands of the compare so that they are listed from most
03464   /// complex to least complex.  This puts constants before unary operators,
03465   /// before binary operators.
03466   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
03467     I.swapOperands();
03468     Changed = true;
03469   }
03470 
03471   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
03472 
03473   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, DL))
03474     return ReplaceInstUsesWith(I, V);
03475 
03476   // Simplify 'fcmp pred X, X'
03477   if (Op0 == Op1) {
03478     switch (I.getPredicate()) {
03479     default: llvm_unreachable("Unknown predicate!");
03480     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
03481     case FCmpInst::FCMP_ULT:    // True if unordered or less than
03482     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
03483     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
03484       // Canonicalize these to be 'fcmp uno %X, 0.0'.
03485       I.setPredicate(FCmpInst::FCMP_UNO);
03486       I.setOperand(1, Constant::getNullValue(Op0->getType()));
03487       return &I;
03488 
03489     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
03490     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
03491     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
03492     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
03493       // Canonicalize these to be 'fcmp ord %X, 0.0'.
03494       I.setPredicate(FCmpInst::FCMP_ORD);
03495       I.setOperand(1, Constant::getNullValue(Op0->getType()));
03496       return &I;
03497     }
03498   }
03499 
03500   // Handle fcmp with constant RHS
03501   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
03502     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
03503       switch (LHSI->getOpcode()) {
03504       case Instruction::FPExt: {
03505         // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
03506         FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
03507         ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
03508         if (!RHSF)
03509           break;
03510 
03511         const fltSemantics *Sem;
03512         // FIXME: This shouldn't be here.
03513         if (LHSExt->getSrcTy()->isHalfTy())
03514           Sem = &APFloat::IEEEhalf;
03515         else if (LHSExt->getSrcTy()->isFloatTy())
03516           Sem = &APFloat::IEEEsingle;
03517         else if (LHSExt->getSrcTy()->isDoubleTy())
03518           Sem = &APFloat::IEEEdouble;
03519         else if (LHSExt->getSrcTy()->isFP128Ty())
03520           Sem = &APFloat::IEEEquad;
03521         else if (LHSExt->getSrcTy()->isX86_FP80Ty())
03522           Sem = &APFloat::x87DoubleExtended;
03523         else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
03524           Sem = &APFloat::PPCDoubleDouble;
03525         else
03526           break;
03527 
03528         bool Lossy;
03529         APFloat F = RHSF->getValueAPF();
03530         F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
03531 
03532         // Avoid lossy conversions and denormals. Zero is a special case
03533         // that's OK to convert.
03534         APFloat Fabs = F;
03535         Fabs.clearSign();
03536         if (!Lossy &&
03537             ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
03538                  APFloat::cmpLessThan) || Fabs.isZero()))
03539 
03540           return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
03541                               ConstantFP::get(RHSC->getContext(), F));
03542         break;
03543       }
03544       case Instruction::PHI:
03545         // Only fold fcmp into the PHI if the phi and fcmp are in the same
03546         // block.  If in the same block, we're encouraging jump threading.  If
03547         // not, we are just pessimizing the code by making an i1 phi.
03548         if (LHSI->getParent() == I.getParent())
03549           if (Instruction *NV = FoldOpIntoPhi(I))
03550             return NV;
03551         break;
03552       case Instruction::SIToFP:
03553       case Instruction::UIToFP:
03554         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
03555           return NV;
03556         break;
03557       case Instruction::FSub: {
03558         // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
03559         Value *Op;
03560         if (match(LHSI, m_FNeg(m_Value(Op))))
03561           return new FCmpInst(I.getSwappedPredicate(), Op,
03562                               ConstantExpr::getFNeg(RHSC));
03563         break;
03564       }
03565       case Instruction::Load:
03566         if (GetElementPtrInst *GEP =
03567             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
03568           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
03569             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
03570                 !cast<LoadInst>(LHSI)->isVolatile())
03571               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
03572                 return Res;
03573         }
03574         break;
03575       case Instruction::Call: {
03576         CallInst *CI = cast<CallInst>(LHSI);
03577         LibFunc::Func Func;
03578         // Various optimization for fabs compared with zero.
03579         if (RHSC->isNullValue() && CI->getCalledFunction() &&
03580             TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) &&
03581             TLI->has(Func)) {
03582           if (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
03583               Func == LibFunc::fabsl) {
03584             switch (I.getPredicate()) {
03585             default: break;
03586             // fabs(x) < 0 --> false
03587             case FCmpInst::FCMP_OLT:
03588               return ReplaceInstUsesWith(I, Builder->getFalse());
03589             // fabs(x) > 0 --> x != 0
03590             case FCmpInst::FCMP_OGT:
03591               return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0),
03592                                   RHSC);
03593             // fabs(x) <= 0 --> x == 0
03594             case FCmpInst::FCMP_OLE:
03595               return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0),
03596                                   RHSC);
03597             // fabs(x) >= 0 --> !isnan(x)
03598             case FCmpInst::FCMP_OGE:
03599               return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0),
03600                                   RHSC);
03601             // fabs(x) == 0 --> x == 0
03602             // fabs(x) != 0 --> x != 0
03603             case FCmpInst::FCMP_OEQ:
03604             case FCmpInst::FCMP_UEQ:
03605             case FCmpInst::FCMP_ONE:
03606             case FCmpInst::FCMP_UNE:
03607               return new FCmpInst(I.getPredicate(), CI->getArgOperand(0),
03608                                   RHSC);
03609             }
03610           }
03611         }
03612       }
03613       }
03614   }
03615 
03616   // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
03617   Value *X, *Y;
03618   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
03619     return new FCmpInst(I.getSwappedPredicate(), X, Y);
03620 
03621   // fcmp (fpext x), (fpext y) -> fcmp x, y
03622   if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
03623     if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
03624       if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
03625         return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
03626                             RHSExt->getOperand(0));
03627 
03628   return Changed ? &I : 0;
03629 }