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