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     break;
02153   }
02154 
02155   case OCF_UNSIGNED_SUB:
02156   case OCF_SIGNED_SUB: {
02157     // X - 0 -> {X, false}
02158     if (match(RHS, m_Zero()))
02159       return SetResult(LHS, Builder->getFalse(), false);
02160 
02161     if (OCF == OCF_SIGNED_SUB) {
02162       if (WillNotOverflowSignedSub(LHS, RHS, OrigI))
02163         return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(),
02164                          true);
02165     } else {
02166       if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI))
02167         return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(),
02168                          true);
02169     }
02170     break;
02171   }
02172 
02173   case OCF_UNSIGNED_MUL: {
02174     OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI);
02175     if (OR == OverflowResult::NeverOverflows)
02176       return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(),
02177                        true);
02178     if (OR == OverflowResult::AlwaysOverflows)
02179       return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true);
02180   } // FALL THROUGH
02181   case OCF_SIGNED_MUL:
02182     // X * undef -> undef
02183     if (isa<UndefValue>(RHS))
02184       return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false);
02185 
02186     // X * 0 -> {0, false}
02187     if (match(RHS, m_Zero()))
02188       return SetResult(RHS, Builder->getFalse(), false);
02189 
02190     // X * 1 -> {X, false}
02191     if (match(RHS, m_One()))
02192       return SetResult(LHS, Builder->getFalse(), false);
02193 
02194     if (OCF == OCF_SIGNED_MUL)
02195       if (WillNotOverflowSignedMul(LHS, RHS, OrigI))
02196         return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(),
02197                          true);
02198     break;
02199   }
02200 
02201   return false;
02202 }
02203 
02204 /// \brief Recognize and process idiom involving test for multiplication
02205 /// overflow.
02206 ///
02207 /// The caller has matched a pattern of the form:
02208 ///   I = cmp u (mul(zext A, zext B), V
02209 /// The function checks if this is a test for overflow and if so replaces
02210 /// multiplication with call to 'mul.with.overflow' intrinsic.
02211 ///
02212 /// \param I Compare instruction.
02213 /// \param MulVal Result of 'mult' instruction.  It is one of the arguments of
02214 ///               the compare instruction.  Must be of integer type.
02215 /// \param OtherVal The other argument of compare instruction.
02216 /// \returns Instruction which must replace the compare instruction, NULL if no
02217 ///          replacement required.
02218 static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal,
02219                                          Value *OtherVal, InstCombiner &IC) {
02220   // Don't bother doing this transformation for pointers, don't do it for
02221   // vectors.
02222   if (!isa<IntegerType>(MulVal->getType()))
02223     return nullptr;
02224 
02225   assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
02226   assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
02227   Instruction *MulInstr = cast<Instruction>(MulVal);
02228   assert(MulInstr->getOpcode() == Instruction::Mul);
02229 
02230   auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
02231        *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
02232   assert(LHS->getOpcode() == Instruction::ZExt);
02233   assert(RHS->getOpcode() == Instruction::ZExt);
02234   Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
02235 
02236   // Calculate type and width of the result produced by mul.with.overflow.
02237   Type *TyA = A->getType(), *TyB = B->getType();
02238   unsigned WidthA = TyA->getPrimitiveSizeInBits(),
02239            WidthB = TyB->getPrimitiveSizeInBits();
02240   unsigned MulWidth;
02241   Type *MulType;
02242   if (WidthB > WidthA) {
02243     MulWidth = WidthB;
02244     MulType = TyB;
02245   } else {
02246     MulWidth = WidthA;
02247     MulType = TyA;
02248   }
02249 
02250   // In order to replace the original mul with a narrower mul.with.overflow,
02251   // all uses must ignore upper bits of the product.  The number of used low
02252   // bits must be not greater than the width of mul.with.overflow.
02253   if (MulVal->hasNUsesOrMore(2))
02254     for (User *U : MulVal->users()) {
02255       if (U == &I)
02256         continue;
02257       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
02258         // Check if truncation ignores bits above MulWidth.
02259         unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
02260         if (TruncWidth > MulWidth)
02261           return nullptr;
02262       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
02263         // Check if AND ignores bits above MulWidth.
02264         if (BO->getOpcode() != Instruction::And)
02265           return nullptr;
02266         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
02267           const APInt &CVal = CI->getValue();
02268           if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
02269             return nullptr;
02270         }
02271       } else {
02272         // Other uses prohibit this transformation.
02273         return nullptr;
02274       }
02275     }
02276 
02277   // Recognize patterns
02278   switch (I.getPredicate()) {
02279   case ICmpInst::ICMP_EQ:
02280   case ICmpInst::ICMP_NE:
02281     // Recognize pattern:
02282     //   mulval = mul(zext A, zext B)
02283     //   cmp eq/neq mulval, zext trunc mulval
02284     if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
02285       if (Zext->hasOneUse()) {
02286         Value *ZextArg = Zext->getOperand(0);
02287         if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
02288           if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth)
02289             break; //Recognized
02290       }
02291 
02292     // Recognize pattern:
02293     //   mulval = mul(zext A, zext B)
02294     //   cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
02295     ConstantInt *CI;
02296     Value *ValToMask;
02297     if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
02298       if (ValToMask != MulVal)
02299         return nullptr;
02300       const APInt &CVal = CI->getValue() + 1;
02301       if (CVal.isPowerOf2()) {
02302         unsigned MaskWidth = CVal.logBase2();
02303         if (MaskWidth == MulWidth)
02304           break; // Recognized
02305       }
02306     }
02307     return nullptr;
02308 
02309   case ICmpInst::ICMP_UGT:
02310     // Recognize pattern:
02311     //   mulval = mul(zext A, zext B)
02312     //   cmp ugt mulval, max
02313     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02314       APInt MaxVal = APInt::getMaxValue(MulWidth);
02315       MaxVal = MaxVal.zext(CI->getBitWidth());
02316       if (MaxVal.eq(CI->getValue()))
02317         break; // Recognized
02318     }
02319     return nullptr;
02320 
02321   case ICmpInst::ICMP_UGE:
02322     // Recognize pattern:
02323     //   mulval = mul(zext A, zext B)
02324     //   cmp uge mulval, max+1
02325     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02326       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
02327       if (MaxVal.eq(CI->getValue()))
02328         break; // Recognized
02329     }
02330     return nullptr;
02331 
02332   case ICmpInst::ICMP_ULE:
02333     // Recognize pattern:
02334     //   mulval = mul(zext A, zext B)
02335     //   cmp ule mulval, max
02336     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02337       APInt MaxVal = APInt::getMaxValue(MulWidth);
02338       MaxVal = MaxVal.zext(CI->getBitWidth());
02339       if (MaxVal.eq(CI->getValue()))
02340         break; // Recognized
02341     }
02342     return nullptr;
02343 
02344   case ICmpInst::ICMP_ULT:
02345     // Recognize pattern:
02346     //   mulval = mul(zext A, zext B)
02347     //   cmp ule mulval, max + 1
02348     if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
02349       APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
02350       if (MaxVal.eq(CI->getValue()))
02351         break; // Recognized
02352     }
02353     return nullptr;
02354 
02355   default:
02356     return nullptr;
02357   }
02358 
02359   InstCombiner::BuilderTy *Builder = IC.Builder;
02360   Builder->SetInsertPoint(MulInstr);
02361   Module *M = I.getParent()->getParent()->getParent();
02362 
02363   // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
02364   Value *MulA = A, *MulB = B;
02365   if (WidthA < MulWidth)
02366     MulA = Builder->CreateZExt(A, MulType);
02367   if (WidthB < MulWidth)
02368     MulB = Builder->CreateZExt(B, MulType);
02369   Value *F =
02370       Intrinsic::getDeclaration(M, Intrinsic::umul_with_overflow, MulType);
02371   CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul");
02372   IC.Worklist.Add(MulInstr);
02373 
02374   // If there are uses of mul result other than the comparison, we know that
02375   // they are truncation or binary AND. Change them to use result of
02376   // mul.with.overflow and adjust properly mask/size.
02377   if (MulVal->hasNUsesOrMore(2)) {
02378     Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value");
02379     for (User *U : MulVal->users()) {
02380       if (U == &I || U == OtherVal)
02381         continue;
02382       if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
02383         if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
02384           IC.ReplaceInstUsesWith(*TI, Mul);
02385         else
02386           TI->setOperand(0, Mul);
02387       } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
02388         assert(BO->getOpcode() == Instruction::And);
02389         // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
02390         ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
02391         APInt ShortMask = CI->getValue().trunc(MulWidth);
02392         Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask);
02393         Instruction *Zext =
02394             cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType()));
02395         IC.Worklist.Add(Zext);
02396         IC.ReplaceInstUsesWith(*BO, Zext);
02397       } else {
02398         llvm_unreachable("Unexpected Binary operation");
02399       }
02400       IC.Worklist.Add(cast<Instruction>(U));
02401     }
02402   }
02403   if (isa<Instruction>(OtherVal))
02404     IC.Worklist.Add(cast<Instruction>(OtherVal));
02405 
02406   // The original icmp gets replaced with the overflow value, maybe inverted
02407   // depending on predicate.
02408   bool Inverse = false;
02409   switch (I.getPredicate()) {
02410   case ICmpInst::ICMP_NE:
02411     break;
02412   case ICmpInst::ICMP_EQ:
02413     Inverse = true;
02414     break;
02415   case ICmpInst::ICMP_UGT:
02416   case ICmpInst::ICMP_UGE:
02417     if (I.getOperand(0) == MulVal)
02418       break;
02419     Inverse = true;
02420     break;
02421   case ICmpInst::ICMP_ULT:
02422   case ICmpInst::ICMP_ULE:
02423     if (I.getOperand(1) == MulVal)
02424       break;
02425     Inverse = true;
02426     break;
02427   default:
02428     llvm_unreachable("Unexpected predicate");
02429   }
02430   if (Inverse) {
02431     Value *Res = Builder->CreateExtractValue(Call, 1);
02432     return BinaryOperator::CreateNot(Res);
02433   }
02434 
02435   return ExtractValueInst::Create(Call, 1);
02436 }
02437 
02438 // DemandedBitsLHSMask - When performing a comparison against a constant,
02439 // it is possible that not all the bits in the LHS are demanded.  This helper
02440 // method computes the mask that IS demanded.
02441 static APInt DemandedBitsLHSMask(ICmpInst &I,
02442                                  unsigned BitWidth, bool isSignCheck) {
02443   if (isSignCheck)
02444     return APInt::getSignBit(BitWidth);
02445 
02446   ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
02447   if (!CI) return APInt::getAllOnesValue(BitWidth);
02448   const APInt &RHS = CI->getValue();
02449 
02450   switch (I.getPredicate()) {
02451   // For a UGT comparison, we don't care about any bits that
02452   // correspond to the trailing ones of the comparand.  The value of these
02453   // bits doesn't impact the outcome of the comparison, because any value
02454   // greater than the RHS must differ in a bit higher than these due to carry.
02455   case ICmpInst::ICMP_UGT: {
02456     unsigned trailingOnes = RHS.countTrailingOnes();
02457     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes);
02458     return ~lowBitsSet;
02459   }
02460 
02461   // Similarly, for a ULT comparison, we don't care about the trailing zeros.
02462   // Any value less than the RHS must differ in a higher bit because of carries.
02463   case ICmpInst::ICMP_ULT: {
02464     unsigned trailingZeros = RHS.countTrailingZeros();
02465     APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros);
02466     return ~lowBitsSet;
02467   }
02468 
02469   default:
02470     return APInt::getAllOnesValue(BitWidth);
02471   }
02472 
02473 }
02474 
02475 /// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst
02476 /// should be swapped.
02477 /// The decision is based on how many times these two operands are reused
02478 /// as subtract operands and their positions in those instructions.
02479 /// The rational is that several architectures use the same instruction for
02480 /// both subtract and cmp, thus it is better if the order of those operands
02481 /// match.
02482 /// \return true if Op0 and Op1 should be swapped.
02483 static bool swapMayExposeCSEOpportunities(const Value * Op0,
02484                                           const Value * Op1) {
02485   // Filter out pointer value as those cannot appears directly in subtract.
02486   // FIXME: we may want to go through inttoptrs or bitcasts.
02487   if (Op0->getType()->isPointerTy())
02488     return false;
02489   // Count every uses of both Op0 and Op1 in a subtract.
02490   // Each time Op0 is the first operand, count -1: swapping is bad, the
02491   // subtract has already the same layout as the compare.
02492   // Each time Op0 is the second operand, count +1: swapping is good, the
02493   // subtract has a different layout as the compare.
02494   // At the end, if the benefit is greater than 0, Op0 should come second to
02495   // expose more CSE opportunities.
02496   int GlobalSwapBenefits = 0;
02497   for (const User *U : Op0->users()) {
02498     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U);
02499     if (!BinOp || BinOp->getOpcode() != Instruction::Sub)
02500       continue;
02501     // If Op0 is the first argument, this is not beneficial to swap the
02502     // arguments.
02503     int LocalSwapBenefits = -1;
02504     unsigned Op1Idx = 1;
02505     if (BinOp->getOperand(Op1Idx) == Op0) {
02506       Op1Idx = 0;
02507       LocalSwapBenefits = 1;
02508     }
02509     if (BinOp->getOperand(Op1Idx) != Op1)
02510       continue;
02511     GlobalSwapBenefits += LocalSwapBenefits;
02512   }
02513   return GlobalSwapBenefits > 0;
02514 }
02515 
02516 /// \brief Check that one use is in the same block as the definition and all
02517 /// other uses are in blocks dominated by a given block
02518 ///
02519 /// \param DI Definition
02520 /// \param UI Use
02521 /// \param DB Block that must dominate all uses of \p DI outside
02522 ///           the parent block
02523 /// \return true when \p UI is the only use of \p DI in the parent block
02524 /// and all other uses of \p DI are in blocks dominated by \p DB.
02525 ///
02526 bool InstCombiner::dominatesAllUses(const Instruction *DI,
02527                                     const Instruction *UI,
02528                                     const BasicBlock *DB) const {
02529   assert(DI && UI && "Instruction not defined\n");
02530   // ignore incomplete definitions
02531   if (!DI->getParent())
02532     return false;
02533   // DI and UI must be in the same block
02534   if (DI->getParent() != UI->getParent())
02535     return false;
02536   // Protect from self-referencing blocks
02537   if (DI->getParent() == DB)
02538     return false;
02539   // DominatorTree available?
02540   if (!DT)
02541     return false;
02542   for (const User *U : DI->users()) {
02543     auto *Usr = cast<Instruction>(U);
02544     if (Usr != UI && !DT->dominates(DB, Usr->getParent()))
02545       return false;
02546   }
02547   return true;
02548 }
02549 
02550 ///
02551 /// true when the instruction sequence within a block is select-cmp-br.
02552 ///
02553 static bool isChainSelectCmpBranch(const SelectInst *SI) {
02554   const BasicBlock *BB = SI->getParent();
02555   if (!BB)
02556     return false;
02557   auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
02558   if (!BI || BI->getNumSuccessors() != 2)
02559     return false;
02560   auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
02561   if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
02562     return false;
02563   return true;
02564 }
02565 
02566 ///
02567 /// \brief True when a select result is replaced by one of its operands
02568 /// in select-icmp sequence. This will eventually result in the elimination
02569 /// of the select.
02570 ///
02571 /// \param SI    Select instruction
02572 /// \param Icmp  Compare instruction
02573 /// \param SIOpd Operand that replaces the select
02574 ///
02575 /// Notes:
02576 /// - The replacement is global and requires dominator information
02577 /// - The caller is responsible for the actual replacement
02578 ///
02579 /// Example:
02580 ///
02581 /// entry:
02582 ///  %4 = select i1 %3, %C* %0, %C* null
02583 ///  %5 = icmp eq %C* %4, null
02584 ///  br i1 %5, label %9, label %7
02585 ///  ...
02586 ///  ; <label>:7                                       ; preds = %entry
02587 ///  %8 = getelementptr inbounds %C* %4, i64 0, i32 0
02588 ///  ...
02589 ///
02590 /// can be transformed to
02591 ///
02592 ///  %5 = icmp eq %C* %0, null
02593 ///  %6 = select i1 %3, i1 %5, i1 true
02594 ///  br i1 %6, label %9, label %7
02595 ///  ...
02596 ///  ; <label>:7                                       ; preds = %entry
02597 ///  %8 = getelementptr inbounds %C* %0, i64 0, i32 0  // replace by %0!
02598 ///
02599 /// Similar when the first operand of the select is a constant or/and
02600 /// the compare is for not equal rather than equal.
02601 ///
02602 /// NOTE: The function is only called when the select and compare constants
02603 /// are equal, the optimization can work only for EQ predicates. This is not a
02604 /// major restriction since a NE compare should be 'normalized' to an equal
02605 /// compare, which usually happens in the combiner and test case
02606 /// select-cmp-br.ll
02607 /// checks for it.
02608 bool InstCombiner::replacedSelectWithOperand(SelectInst *SI,
02609                                              const ICmpInst *Icmp,
02610                                              const unsigned SIOpd) {
02611   assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
02612   if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
02613     BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
02614     // The check for the unique predecessor is not the best that can be
02615     // done. But it protects efficiently against cases like  when SI's
02616     // home block has two successors, Succ and Succ1, and Succ1 predecessor
02617     // of Succ. Then SI can't be replaced by SIOpd because the use that gets
02618     // replaced can be reached on either path. So the uniqueness check
02619     // guarantees that the path all uses of SI (outside SI's parent) are on
02620     // is disjoint from all other paths out of SI. But that information
02621     // is more expensive to compute, and the trade-off here is in favor
02622     // of compile-time.
02623     if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
02624       NumSel++;
02625       SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
02626       return true;
02627     }
02628   }
02629   return false;
02630 }
02631 
02632 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
02633   bool Changed = false;
02634   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
02635   unsigned Op0Cplxity = getComplexity(Op0);
02636   unsigned Op1Cplxity = getComplexity(Op1);
02637 
02638   /// Orders the operands of the compare so that they are listed from most
02639   /// complex to least complex.  This puts constants before unary operators,
02640   /// before binary operators.
02641   if (Op0Cplxity < Op1Cplxity ||
02642         (Op0Cplxity == Op1Cplxity &&
02643          swapMayExposeCSEOpportunities(Op0, Op1))) {
02644     I.swapOperands();
02645     std::swap(Op0, Op1);
02646     Changed = true;
02647   }
02648 
02649   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC))
02650     return ReplaceInstUsesWith(I, V);
02651 
02652   // comparing -val or val with non-zero is the same as just comparing val
02653   // ie, abs(val) != 0 -> val != 0
02654   if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero()))
02655   {
02656     Value *Cond, *SelectTrue, *SelectFalse;
02657     if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
02658                             m_Value(SelectFalse)))) {
02659       if (Value *V = dyn_castNegVal(SelectTrue)) {
02660         if (V == SelectFalse)
02661           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
02662       }
02663       else if (Value *V = dyn_castNegVal(SelectFalse)) {
02664         if (V == SelectTrue)
02665           return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
02666       }
02667     }
02668   }
02669 
02670   Type *Ty = Op0->getType();
02671 
02672   // icmp's with boolean values can always be turned into bitwise operations
02673   if (Ty->isIntegerTy(1)) {
02674     switch (I.getPredicate()) {
02675     default: llvm_unreachable("Invalid icmp instruction!");
02676     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
02677       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
02678       return BinaryOperator::CreateNot(Xor);
02679     }
02680     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
02681       return BinaryOperator::CreateXor(Op0, Op1);
02682 
02683     case ICmpInst::ICMP_UGT:
02684       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
02685       // FALL THROUGH
02686     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
02687       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
02688       return BinaryOperator::CreateAnd(Not, Op1);
02689     }
02690     case ICmpInst::ICMP_SGT:
02691       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
02692       // FALL THROUGH
02693     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
02694       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
02695       return BinaryOperator::CreateAnd(Not, Op0);
02696     }
02697     case ICmpInst::ICMP_UGE:
02698       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
02699       // FALL THROUGH
02700     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
02701       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
02702       return BinaryOperator::CreateOr(Not, Op1);
02703     }
02704     case ICmpInst::ICMP_SGE:
02705       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
02706       // FALL THROUGH
02707     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
02708       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
02709       return BinaryOperator::CreateOr(Not, Op0);
02710     }
02711     }
02712   }
02713 
02714   unsigned BitWidth = 0;
02715   if (Ty->isIntOrIntVectorTy())
02716     BitWidth = Ty->getScalarSizeInBits();
02717   else // Get pointer size.
02718     BitWidth = DL.getTypeSizeInBits(Ty->getScalarType());
02719 
02720   bool isSignBit = false;
02721 
02722   // See if we are doing a comparison with a constant.
02723   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02724     Value *A = nullptr, *B = nullptr;
02725 
02726     // Match the following pattern, which is a common idiom when writing
02727     // overflow-safe integer arithmetic function.  The source performs an
02728     // addition in wider type, and explicitly checks for overflow using
02729     // comparisons against INT_MIN and INT_MAX.  Simplify this by using the
02730     // sadd_with_overflow intrinsic.
02731     //
02732     // TODO: This could probably be generalized to handle other overflow-safe
02733     // operations if we worked out the formulas to compute the appropriate
02734     // magic constants.
02735     //
02736     // sum = a + b
02737     // if (sum+128 >u 255)  ...  -> llvm.sadd.with.overflow.i8
02738     {
02739     ConstantInt *CI2;    // I = icmp ugt (add (add A, B), CI2), CI
02740     if (I.getPredicate() == ICmpInst::ICMP_UGT &&
02741         match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
02742       if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this))
02743         return Res;
02744     }
02745 
02746     // The following transforms are only 'worth it' if the only user of the
02747     // subtraction is the icmp.
02748     if (Op0->hasOneUse()) {
02749       // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
02750       if (I.isEquality() && CI->isZero() &&
02751           match(Op0, m_Sub(m_Value(A), m_Value(B))))
02752         return new ICmpInst(I.getPredicate(), A, B);
02753 
02754       // (icmp sgt (sub nsw A B), -1) -> (icmp sge A, B)
02755       if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isAllOnesValue() &&
02756           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
02757         return new ICmpInst(ICmpInst::ICMP_SGE, A, B);
02758 
02759       // (icmp sgt (sub nsw A B), 0) -> (icmp sgt A, B)
02760       if (I.getPredicate() == ICmpInst::ICMP_SGT && CI->isZero() &&
02761           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
02762         return new ICmpInst(ICmpInst::ICMP_SGT, A, B);
02763 
02764       // (icmp slt (sub nsw A B), 0) -> (icmp slt A, B)
02765       if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isZero() &&
02766           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
02767         return new ICmpInst(ICmpInst::ICMP_SLT, A, B);
02768 
02769       // (icmp slt (sub nsw A B), 1) -> (icmp sle A, B)
02770       if (I.getPredicate() == ICmpInst::ICMP_SLT && CI->isOne() &&
02771           match(Op0, m_NSWSub(m_Value(A), m_Value(B))))
02772         return new ICmpInst(ICmpInst::ICMP_SLE, A, B);
02773     }
02774 
02775     // If we have an icmp le or icmp ge instruction, turn it into the
02776     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
02777     // them being folded in the code below.  The SimplifyICmpInst code has
02778     // already handled the edge cases for us, so we just assert on them.
02779     switch (I.getPredicate()) {
02780     default: break;
02781     case ICmpInst::ICMP_ULE:
02782       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
02783       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
02784                           Builder->getInt(CI->getValue()+1));
02785     case ICmpInst::ICMP_SLE:
02786       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
02787       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
02788                           Builder->getInt(CI->getValue()+1));
02789     case ICmpInst::ICMP_UGE:
02790       assert(!CI->isMinValue(false));                 // A >=u MIN -> TRUE
02791       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
02792                           Builder->getInt(CI->getValue()-1));
02793     case ICmpInst::ICMP_SGE:
02794       assert(!CI->isMinValue(true));                  // A >=s MIN -> TRUE
02795       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
02796                           Builder->getInt(CI->getValue()-1));
02797     }
02798 
02799     if (I.isEquality()) {
02800       ConstantInt *CI2;
02801       if (match(Op0, m_AShr(m_ConstantInt(CI2), m_Value(A))) ||
02802           match(Op0, m_LShr(m_ConstantInt(CI2), m_Value(A)))) {
02803         // (icmp eq/ne (ashr/lshr const2, A), const1)
02804         if (Instruction *Inst = FoldICmpCstShrCst(I, Op0, A, CI, CI2))
02805           return Inst;
02806       }
02807       if (match(Op0, m_Shl(m_ConstantInt(CI2), m_Value(A)))) {
02808         // (icmp eq/ne (shl const2, A), const1)
02809         if (Instruction *Inst = FoldICmpCstShlCst(I, Op0, A, CI, CI2))
02810           return Inst;
02811       }
02812     }
02813 
02814     // If this comparison is a normal comparison, it demands all
02815     // bits, if it is a sign bit comparison, it only demands the sign bit.
02816     bool UnusedBit;
02817     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
02818   }
02819 
02820   // See if we can fold the comparison based on range information we can get
02821   // by checking whether bits are known to be zero or one in the input.
02822   if (BitWidth != 0) {
02823     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
02824     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
02825 
02826     if (SimplifyDemandedBits(I.getOperandUse(0),
02827                              DemandedBitsLHSMask(I, BitWidth, isSignBit),
02828                              Op0KnownZero, Op0KnownOne, 0))
02829       return &I;
02830     if (SimplifyDemandedBits(I.getOperandUse(1),
02831                              APInt::getAllOnesValue(BitWidth), Op1KnownZero,
02832                              Op1KnownOne, 0))
02833       return &I;
02834 
02835     // Given the known and unknown bits, compute a range that the LHS could be
02836     // in.  Compute the Min, Max and RHS values based on the known bits. For the
02837     // EQ and NE we use unsigned values.
02838     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
02839     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
02840     if (I.isSigned()) {
02841       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
02842                                              Op0Min, Op0Max);
02843       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
02844                                              Op1Min, Op1Max);
02845     } else {
02846       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
02847                                                Op0Min, Op0Max);
02848       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
02849                                                Op1Min, Op1Max);
02850     }
02851 
02852     // If Min and Max are known to be the same, then SimplifyDemandedBits
02853     // figured out that the LHS is a constant.  Just constant fold this now so
02854     // that code below can assume that Min != Max.
02855     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
02856       return new ICmpInst(I.getPredicate(),
02857                           ConstantInt::get(Op0->getType(), Op0Min), Op1);
02858     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
02859       return new ICmpInst(I.getPredicate(), Op0,
02860                           ConstantInt::get(Op1->getType(), Op1Min));
02861 
02862     // Based on the range information we know about the LHS, see if we can
02863     // simplify this comparison.  For example, (x&4) < 8 is always true.
02864     switch (I.getPredicate()) {
02865     default: llvm_unreachable("Unknown icmp opcode!");
02866     case ICmpInst::ICMP_EQ: {
02867       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
02868         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02869 
02870       // If all bits are known zero except for one, then we know at most one
02871       // bit is set.   If the comparison is against zero, then this is a check
02872       // to see if *that* bit is set.
02873       APInt Op0KnownZeroInverted = ~Op0KnownZero;
02874       if (~Op1KnownZero == 0) {
02875         // If the LHS is an AND with the same constant, look through it.
02876         Value *LHS = nullptr;
02877         ConstantInt *LHSC = nullptr;
02878         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
02879             LHSC->getValue() != Op0KnownZeroInverted)
02880           LHS = Op0;
02881 
02882         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
02883         // then turn "((1 << x)&8) == 0" into "x != 3".
02884         // or turn "((1 << x)&7) == 0" into "x > 2".
02885         Value *X = nullptr;
02886         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
02887           APInt ValToCheck = Op0KnownZeroInverted;
02888           if (ValToCheck.isPowerOf2()) {
02889             unsigned CmpVal = ValToCheck.countTrailingZeros();
02890             return new ICmpInst(ICmpInst::ICMP_NE, X,
02891                                 ConstantInt::get(X->getType(), CmpVal));
02892           } else if ((++ValToCheck).isPowerOf2()) {
02893             unsigned CmpVal = ValToCheck.countTrailingZeros() - 1;
02894             return new ICmpInst(ICmpInst::ICMP_UGT, X,
02895                                 ConstantInt::get(X->getType(), CmpVal));
02896           }
02897         }
02898 
02899         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
02900         // then turn "((8 >>u x)&1) == 0" into "x != 3".
02901         const APInt *CI;
02902         if (Op0KnownZeroInverted == 1 &&
02903             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
02904           return new ICmpInst(ICmpInst::ICMP_NE, X,
02905                               ConstantInt::get(X->getType(),
02906                                                CI->countTrailingZeros()));
02907       }
02908 
02909       break;
02910     }
02911     case ICmpInst::ICMP_NE: {
02912       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
02913         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02914 
02915       // If all bits are known zero except for one, then we know at most one
02916       // bit is set.   If the comparison is against zero, then this is a check
02917       // to see if *that* bit is set.
02918       APInt Op0KnownZeroInverted = ~Op0KnownZero;
02919       if (~Op1KnownZero == 0) {
02920         // If the LHS is an AND with the same constant, look through it.
02921         Value *LHS = nullptr;
02922         ConstantInt *LHSC = nullptr;
02923         if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) ||
02924             LHSC->getValue() != Op0KnownZeroInverted)
02925           LHS = Op0;
02926 
02927         // If the LHS is 1 << x, and we know the result is a power of 2 like 8,
02928         // then turn "((1 << x)&8) != 0" into "x == 3".
02929         // or turn "((1 << x)&7) != 0" into "x < 3".
02930         Value *X = nullptr;
02931         if (match(LHS, m_Shl(m_One(), m_Value(X)))) {
02932           APInt ValToCheck = Op0KnownZeroInverted;
02933           if (ValToCheck.isPowerOf2()) {
02934             unsigned CmpVal = ValToCheck.countTrailingZeros();
02935             return new ICmpInst(ICmpInst::ICMP_EQ, X,
02936                                 ConstantInt::get(X->getType(), CmpVal));
02937           } else if ((++ValToCheck).isPowerOf2()) {
02938             unsigned CmpVal = ValToCheck.countTrailingZeros();
02939             return new ICmpInst(ICmpInst::ICMP_ULT, X,
02940                                 ConstantInt::get(X->getType(), CmpVal));
02941           }
02942         }
02943 
02944         // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1,
02945         // then turn "((8 >>u x)&1) != 0" into "x == 3".
02946         const APInt *CI;
02947         if (Op0KnownZeroInverted == 1 &&
02948             match(LHS, m_LShr(m_Power2(CI), m_Value(X))))
02949           return new ICmpInst(ICmpInst::ICMP_EQ, X,
02950                               ConstantInt::get(X->getType(),
02951                                                CI->countTrailingZeros()));
02952       }
02953 
02954       break;
02955     }
02956     case ICmpInst::ICMP_ULT:
02957       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
02958         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02959       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
02960         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02961       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
02962         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
02963       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02964         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
02965           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
02966                               Builder->getInt(CI->getValue()-1));
02967 
02968         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
02969         if (CI->isMinValue(true))
02970           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
02971                            Constant::getAllOnesValue(Op0->getType()));
02972       }
02973       break;
02974     case ICmpInst::ICMP_UGT:
02975       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
02976         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02977       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
02978         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02979 
02980       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
02981         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
02982       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
02983         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
02984           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
02985                               Builder->getInt(CI->getValue()+1));
02986 
02987         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
02988         if (CI->isMaxValue(true))
02989           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
02990                               Constant::getNullValue(Op0->getType()));
02991       }
02992       break;
02993     case ICmpInst::ICMP_SLT:
02994       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
02995         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
02996       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
02997         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
02998       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
02999         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
03000       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
03001         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
03002           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
03003                               Builder->getInt(CI->getValue()-1));
03004       }
03005       break;
03006     case ICmpInst::ICMP_SGT:
03007       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
03008         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
03009       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
03010         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
03011 
03012       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
03013         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
03014       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
03015         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
03016           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
03017                               Builder->getInt(CI->getValue()+1));
03018       }
03019       break;
03020     case ICmpInst::ICMP_SGE:
03021       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
03022       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
03023         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
03024       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
03025         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
03026       break;
03027     case ICmpInst::ICMP_SLE:
03028       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
03029       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
03030         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
03031       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
03032         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
03033       break;
03034     case ICmpInst::ICMP_UGE:
03035       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
03036       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
03037         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
03038       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
03039         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
03040       break;
03041     case ICmpInst::ICMP_ULE:
03042       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
03043       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
03044         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
03045       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
03046         return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
03047       break;
03048     }
03049 
03050     // Turn a signed comparison into an unsigned one if both operands
03051     // are known to have the same sign.
03052     if (I.isSigned() &&
03053         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
03054          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
03055       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
03056   }
03057 
03058   // Test if the ICmpInst instruction is used exclusively by a select as
03059   // part of a minimum or maximum operation. If so, refrain from doing
03060   // any other folding. This helps out other analyses which understand
03061   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
03062   // and CodeGen. And in this case, at least one of the comparison
03063   // operands has at least one user besides the compare (the select),
03064   // which would often largely negate the benefit of folding anyway.
03065   if (I.hasOneUse())
03066     if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
03067       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
03068           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
03069         return nullptr;
03070 
03071   // See if we are doing a comparison between a constant and an instruction that
03072   // can be folded into the comparison.
03073   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
03074     // Since the RHS is a ConstantInt (CI), if the left hand side is an
03075     // instruction, see if that instruction also has constants so that the
03076     // instruction can be folded into the icmp
03077     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
03078       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
03079         return Res;
03080   }
03081 
03082   // Handle icmp with constant (but not simple integer constant) RHS
03083   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
03084     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
03085       switch (LHSI->getOpcode()) {
03086       case Instruction::GetElementPtr:
03087           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
03088         if (RHSC->isNullValue() &&
03089             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
03090           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
03091                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
03092         break;
03093       case Instruction::PHI:
03094         // Only fold icmp into the PHI if the phi and icmp are in the same
03095         // block.  If in the same block, we're encouraging jump threading.  If
03096         // not, we are just pessimizing the code by making an i1 phi.
03097         if (LHSI->getParent() == I.getParent())
03098           if (Instruction *NV = FoldOpIntoPhi(I))
03099             return NV;
03100         break;
03101       case Instruction::Select: {
03102         // If either operand of the select is a constant, we can fold the
03103         // comparison into the select arms, which will cause one to be
03104         // constant folded and the select turned into a bitwise or.
03105         Value *Op1 = nullptr, *Op2 = nullptr;
03106         ConstantInt *CI = 0;
03107         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
03108           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
03109           CI = dyn_cast<ConstantInt>(Op1);
03110         }
03111         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
03112           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
03113           CI = dyn_cast<ConstantInt>(Op2);
03114         }
03115 
03116         // We only want to perform this transformation if it will not lead to
03117         // additional code. This is true if either both sides of the select
03118         // fold to a constant (in which case the icmp is replaced with a select
03119         // which will usually simplify) or this is the only user of the
03120         // select (in which case we are trading a select+icmp for a simpler
03121         // select+icmp) or all uses of the select can be replaced based on
03122         // dominance information ("Global cases").
03123         bool Transform = false;
03124         if (Op1 && Op2)
03125           Transform = true;
03126         else if (Op1 || Op2) {
03127           // Local case
03128           if (LHSI->hasOneUse())
03129             Transform = true;
03130           // Global cases
03131           else if (CI && !CI->isZero())
03132             // When Op1 is constant try replacing select with second operand.
03133             // Otherwise Op2 is constant and try replacing select with first
03134             // operand.
03135             Transform = replacedSelectWithOperand(cast<SelectInst>(LHSI), &I,
03136                                                   Op1 ? 2 : 1);
03137         }
03138         if (Transform) {
03139           if (!Op1)
03140             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
03141                                       RHSC, I.getName());
03142           if (!Op2)
03143             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
03144                                       RHSC, I.getName());
03145           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
03146         }
03147         break;
03148       }
03149       case Instruction::IntToPtr:
03150         // icmp pred inttoptr(X), null -> icmp pred X, 0
03151         if (RHSC->isNullValue() &&
03152             DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
03153           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
03154                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
03155         break;
03156 
03157       case Instruction::Load:
03158         // Try to optimize things like "A[i] > 4" to index computations.
03159         if (GetElementPtrInst *GEP =
03160               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
03161           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
03162             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
03163                 !cast<LoadInst>(LHSI)->isVolatile())
03164               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
03165                 return Res;
03166         }
03167         break;
03168       }
03169   }
03170 
03171   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
03172   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
03173     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
03174       return NI;
03175   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
03176     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
03177                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
03178       return NI;
03179 
03180   // Test to see if the operands of the icmp are casted versions of other
03181   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
03182   // now.
03183   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
03184     if (Op0->getType()->isPointerTy() &&
03185         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
03186       // We keep moving the cast from the left operand over to the right
03187       // operand, where it can often be eliminated completely.
03188       Op0 = CI->getOperand(0);
03189 
03190       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
03191       // so eliminate it as well.
03192       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
03193         Op1 = CI2->getOperand(0);
03194 
03195       // If Op1 is a constant, we can fold the cast into the constant.
03196       if (Op0->getType() != Op1->getType()) {
03197         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
03198           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
03199         } else {
03200           // Otherwise, cast the RHS right before the icmp
03201           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
03202         }
03203       }
03204       return new ICmpInst(I.getPredicate(), Op0, Op1);
03205     }
03206   }
03207 
03208   if (isa<CastInst>(Op0)) {
03209     // Handle the special case of: icmp (cast bool to X), <cst>
03210     // This comes up when you have code like
03211     //   int X = A < B;
03212     //   if (X) ...
03213     // For generality, we handle any zero-extension of any operand comparison
03214     // with a constant or another cast from the same type.
03215     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
03216       if (Instruction *R = visitICmpInstWithCastAndCast(I))
03217         return R;
03218   }
03219 
03220   // Special logic for binary operators.
03221   BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
03222   BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
03223   if (BO0 || BO1) {
03224     CmpInst::Predicate Pred = I.getPredicate();
03225     bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
03226     if (BO0 && isa<OverflowingBinaryOperator>(BO0))
03227       NoOp0WrapProblem = ICmpInst::isEquality(Pred) ||
03228         (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
03229         (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
03230     if (BO1 && isa<OverflowingBinaryOperator>(BO1))
03231       NoOp1WrapProblem = ICmpInst::isEquality(Pred) ||
03232         (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
03233         (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
03234 
03235     // Analyze the case when either Op0 or Op1 is an add instruction.
03236     // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
03237     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
03238     if (BO0 && BO0->getOpcode() == Instruction::Add)
03239       A = BO0->getOperand(0), B = BO0->getOperand(1);
03240     if (BO1 && BO1->getOpcode() == Instruction::Add)
03241       C = BO1->getOperand(0), D = BO1->getOperand(1);
03242 
03243     // icmp (X+cst) < 0 --> X < -cst
03244     if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero()))
03245       if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B))
03246         if (!RHSC->isMinValue(/*isSigned=*/true))
03247           return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC));
03248 
03249     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
03250     if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
03251       return new ICmpInst(Pred, A == Op1 ? B : A,
03252                           Constant::getNullValue(Op1->getType()));
03253 
03254     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
03255     if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
03256       return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
03257                           C == Op0 ? D : C);
03258 
03259     // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow.
03260     if (A && C && (A == C || A == D || B == C || B == D) &&
03261         NoOp0WrapProblem && NoOp1WrapProblem &&
03262         // Try not to increase register pressure.
03263         BO0->hasOneUse() && BO1->hasOneUse()) {
03264       // Determine Y and Z in the form icmp (X+Y), (X+Z).
03265       Value *Y, *Z;
03266       if (A == C) {
03267         // C + B == C + D  ->  B == D
03268         Y = B;
03269         Z = D;
03270       } else if (A == D) {
03271         // D + B == C + D  ->  B == C
03272         Y = B;
03273         Z = C;
03274       } else if (B == C) {
03275         // A + C == C + D  ->  A == D
03276         Y = A;
03277         Z = D;
03278       } else {
03279         assert(B == D);
03280         // A + D == C + D  ->  A == C
03281         Y = A;
03282         Z = C;
03283       }
03284       return new ICmpInst(Pred, Y, Z);
03285     }
03286 
03287     // icmp slt (X + -1), Y -> icmp sle X, Y
03288     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
03289         match(B, m_AllOnes()))
03290       return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
03291 
03292     // icmp sge (X + -1), Y -> icmp sgt X, Y
03293     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
03294         match(B, m_AllOnes()))
03295       return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
03296 
03297     // icmp sle (X + 1), Y -> icmp slt X, Y
03298     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE &&
03299         match(B, m_One()))
03300       return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
03301 
03302     // icmp sgt (X + 1), Y -> icmp sge X, Y
03303     if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT &&
03304         match(B, m_One()))
03305       return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
03306 
03307     // if C1 has greater magnitude than C2:
03308     //  icmp (X + C1), (Y + C2) -> icmp (X + C3), Y
03309     //  s.t. C3 = C1 - C2
03310     //
03311     // if C2 has greater magnitude than C1:
03312     //  icmp (X + C1), (Y + C2) -> icmp X, (Y + C3)
03313     //  s.t. C3 = C2 - C1
03314     if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
03315         (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned())
03316       if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
03317         if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) {
03318           const APInt &AP1 = C1->getValue();
03319           const APInt &AP2 = C2->getValue();
03320           if (AP1.isNegative() == AP2.isNegative()) {
03321             APInt AP1Abs = C1->getValue().abs();
03322             APInt AP2Abs = C2->getValue().abs();
03323             if (AP1Abs.uge(AP2Abs)) {
03324               ConstantInt *C3 = Builder->getInt(AP1 - AP2);
03325               Value *NewAdd = Builder->CreateNSWAdd(A, C3);
03326               return new ICmpInst(Pred, NewAdd, C);
03327             } else {
03328               ConstantInt *C3 = Builder->getInt(AP2 - AP1);
03329               Value *NewAdd = Builder->CreateNSWAdd(C, C3);
03330               return new ICmpInst(Pred, A, NewAdd);
03331             }
03332           }
03333         }
03334 
03335 
03336     // Analyze the case when either Op0 or Op1 is a sub instruction.
03337     // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
03338     A = nullptr; B = nullptr; C = nullptr; D = nullptr;
03339     if (BO0 && BO0->getOpcode() == Instruction::Sub)
03340       A = BO0->getOperand(0), B = BO0->getOperand(1);
03341     if (BO1 && BO1->getOpcode() == Instruction::Sub)
03342       C = BO1->getOperand(0), D = BO1->getOperand(1);
03343 
03344     // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow.
03345     if (A == Op1 && NoOp0WrapProblem)
03346       return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
03347 
03348     // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow.
03349     if (C == Op0 && NoOp1WrapProblem)
03350       return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
03351 
03352     // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow.
03353     if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem &&
03354         // Try not to increase register pressure.
03355         BO0->hasOneUse() && BO1->hasOneUse())
03356       return new ICmpInst(Pred, A, C);
03357 
03358     // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow.
03359     if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
03360         // Try not to increase register pressure.
03361         BO0->hasOneUse() && BO1->hasOneUse())
03362       return new ICmpInst(Pred, D, B);
03363 
03364     // icmp (0-X) < cst --> x > -cst
03365     if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
03366       Value *X;
03367       if (match(BO0, m_Neg(m_Value(X))))
03368         if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
03369           if (!RHSC->isMinValue(/*isSigned=*/true))
03370             return new ICmpInst(I.getSwappedPredicate(), X,
03371                                 ConstantExpr::getNeg(RHSC));
03372     }
03373 
03374     BinaryOperator *SRem = nullptr;
03375     // icmp (srem X, Y), Y
03376     if (BO0 && BO0->getOpcode() == Instruction::SRem &&
03377         Op1 == BO0->getOperand(1))
03378       SRem = BO0;
03379     // icmp Y, (srem X, Y)
03380     else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
03381              Op0 == BO1->getOperand(1))
03382       SRem = BO1;
03383     if (SRem) {
03384       // We don't check hasOneUse to avoid increasing register pressure because
03385       // the value we use is the same value this instruction was already using.
03386       switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
03387         default: break;
03388         case ICmpInst::ICMP_EQ:
03389           return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
03390         case ICmpInst::ICMP_NE:
03391           return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
03392         case ICmpInst::ICMP_SGT:
03393         case ICmpInst::ICMP_SGE:
03394           return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
03395                               Constant::getAllOnesValue(SRem->getType()));
03396         case ICmpInst::ICMP_SLT:
03397         case ICmpInst::ICMP_SLE:
03398           return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
03399                               Constant::getNullValue(SRem->getType()));
03400       }
03401     }
03402 
03403     if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
03404         BO0->hasOneUse() && BO1->hasOneUse() &&
03405         BO0->getOperand(1) == BO1->getOperand(1)) {
03406       switch (BO0->getOpcode()) {
03407       default: break;
03408       case Instruction::Add:
03409       case Instruction::Sub:
03410       case Instruction::Xor:
03411         if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
03412           return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
03413                               BO1->getOperand(0));
03414         // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
03415         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
03416           if (CI->getValue().isSignBit()) {
03417             ICmpInst::Predicate Pred = I.isSigned()
03418                                            ? I.getUnsignedPredicate()
03419                                            : I.getSignedPredicate();
03420             return new ICmpInst(Pred, BO0->getOperand(0),
03421                                 BO1->getOperand(0));
03422           }
03423 
03424           if (CI->isMaxValue(true)) {
03425             ICmpInst::Predicate Pred = I.isSigned()
03426                                            ? I.getUnsignedPredicate()
03427                                            : I.getSignedPredicate();
03428             Pred = I.getSwappedPredicate(Pred);
03429             return new ICmpInst(Pred, BO0->getOperand(0),
03430                                 BO1->getOperand(0));
03431           }
03432         }
03433         break;
03434       case Instruction::Mul:
03435         if (!I.isEquality())
03436           break;
03437 
03438         if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) {
03439           // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
03440           // Mask = -1 >> count-trailing-zeros(Cst).
03441           if (!CI->isZero() && !CI->isOne()) {
03442             const APInt &AP = CI->getValue();
03443             ConstantInt *Mask = ConstantInt::get(I.getContext(),
03444                                     APInt::getLowBitsSet(AP.getBitWidth(),
03445                                                          AP.getBitWidth() -
03446                                                     AP.countTrailingZeros()));
03447             Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask);
03448             Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask);
03449             return new ICmpInst(I.getPredicate(), And1, And2);
03450           }
03451         }
03452         break;
03453       case Instruction::UDiv:
03454       case Instruction::LShr:
03455         if (I.isSigned())
03456           break;
03457         // fall-through
03458       case Instruction::SDiv:
03459       case Instruction::AShr:
03460         if (!BO0->isExact() || !BO1->isExact())
03461           break;
03462         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
03463                             BO1->getOperand(0));
03464       case Instruction::Shl: {
03465         bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
03466         bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
03467         if (!NUW && !NSW)
03468           break;
03469         if (!NSW && I.isSigned())
03470           break;
03471         return new ICmpInst(I.getPredicate(), BO0->getOperand(0),
03472                             BO1->getOperand(0));
03473       }
03474       }
03475     }
03476   }
03477 
03478   { Value *A, *B;
03479     // Transform (A & ~B) == 0 --> (A & B) != 0
03480     // and       (A & ~B) != 0 --> (A & B) == 0
03481     // if A is a power of 2.
03482     if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
03483         match(Op1, m_Zero()) &&
03484         isKnownToBeAPowerOfTwo(A, DL, false, 0, AC, &I, DT) && I.isEquality())
03485       return new ICmpInst(I.getInversePredicate(),
03486                           Builder->CreateAnd(A, B),
03487                           Op1);
03488 
03489     // ~x < ~y --> y < x
03490     // ~x < cst --> ~cst < x
03491     if (match(Op0, m_Not(m_Value(A)))) {
03492       if (match(Op1, m_Not(m_Value(B))))
03493         return new ICmpInst(I.getPredicate(), B, A);
03494       if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1))
03495         return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A);
03496     }
03497 
03498     Instruction *AddI = nullptr;
03499     if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
03500                                      m_Instruction(AddI))) &&
03501         isa<IntegerType>(A->getType())) {
03502       Value *Result;
03503       Constant *Overflow;
03504       if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result,
03505                                 Overflow)) {
03506         ReplaceInstUsesWith(*AddI, Result);
03507         return ReplaceInstUsesWith(I, Overflow);
03508       }
03509     }
03510 
03511     // (zext a) * (zext b)  --> llvm.umul.with.overflow.
03512     if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
03513       if (Instruction *R = ProcessUMulZExtIdiom(I, Op0, Op1, *this))
03514         return R;
03515     }
03516     if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
03517       if (Instruction *R = ProcessUMulZExtIdiom(I, Op1, Op0, *this))
03518         return R;
03519     }
03520   }
03521 
03522   if (I.isEquality()) {
03523     Value *A, *B, *C, *D;
03524 
03525     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
03526       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
03527         Value *OtherVal = A == Op1 ? B : A;
03528         return new ICmpInst(I.getPredicate(), OtherVal,
03529                             Constant::getNullValue(A->getType()));
03530       }
03531 
03532       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
03533         // A^c1 == C^c2 --> A == C^(c1^c2)
03534         ConstantInt *C1, *C2;
03535         if (match(B, m_ConstantInt(C1)) &&
03536             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
03537           Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue());
03538           Value *Xor = Builder->CreateXor(C, NC);
03539           return new ICmpInst(I.getPredicate(), A, Xor);
03540         }
03541 
03542         // A^B == A^D -> B == D
03543         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
03544         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
03545         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
03546         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
03547       }
03548     }
03549 
03550     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
03551         (A == Op0 || B == Op0)) {
03552       // A == (A^B)  ->  B == 0
03553       Value *OtherVal = A == Op0 ? B : A;
03554       return new ICmpInst(I.getPredicate(), OtherVal,
03555                           Constant::getNullValue(A->getType()));
03556     }
03557 
03558     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
03559     if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
03560         match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
03561       Value *X = nullptr, *Y = nullptr, *Z = nullptr;
03562 
03563       if (A == C) {
03564         X = B; Y = D; Z = A;
03565       } else if (A == D) {
03566         X = B; Y = C; Z = A;
03567       } else if (B == C) {
03568         X = A; Y = D; Z = B;
03569       } else if (B == D) {
03570         X = A; Y = C; Z = B;
03571       }
03572 
03573       if (X) {   // Build (X^Y) & Z
03574         Op1 = Builder->CreateXor(X, Y);
03575         Op1 = Builder->CreateAnd(Op1, Z);
03576         I.setOperand(0, Op1);
03577         I.setOperand(1, Constant::getNullValue(Op1->getType()));
03578         return &I;
03579       }
03580     }
03581 
03582     // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B)
03583     // and       (B & (1<<X)-1) == (zext A) --> A == (trunc B)
03584     ConstantInt *Cst1;
03585     if ((Op0->hasOneUse() &&
03586          match(Op0, m_ZExt(m_Value(A))) &&
03587          match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) ||
03588         (Op1->hasOneUse() &&
03589          match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) &&
03590          match(Op1, m_ZExt(m_Value(A))))) {
03591       APInt Pow2 = Cst1->getValue() + 1;
03592       if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) &&
03593           Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth())
03594         return new ICmpInst(I.getPredicate(), A,
03595                             Builder->CreateTrunc(B, A->getType()));
03596     }
03597 
03598     // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
03599     // For lshr and ashr pairs.
03600     if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) &&
03601          match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) ||
03602         (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) &&
03603          match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) {
03604       unsigned TypeBits = Cst1->getBitWidth();
03605       unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
03606       if (ShAmt < TypeBits && ShAmt != 0) {
03607         ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE
03608                                        ? ICmpInst::ICMP_UGE
03609                                        : ICmpInst::ICMP_ULT;
03610         Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
03611         APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
03612         return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal));
03613       }
03614     }
03615 
03616     // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
03617     if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
03618         match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
03619       unsigned TypeBits = Cst1->getBitWidth();
03620       unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
03621       if (ShAmt < TypeBits && ShAmt != 0) {
03622         Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted");
03623         APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
03624         Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal),
03625                                         I.getName() + ".mask");
03626         return new ICmpInst(I.getPredicate(), And,
03627                             Constant::getNullValue(Cst1->getType()));
03628       }
03629     }
03630 
03631     // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
03632     // "icmp (and X, mask), cst"
03633     uint64_t ShAmt = 0;
03634     if (Op0->hasOneUse() &&
03635         match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A),
03636                                            m_ConstantInt(ShAmt))))) &&
03637         match(Op1, m_ConstantInt(Cst1)) &&
03638         // Only do this when A has multiple uses.  This is most important to do
03639         // when it exposes other optimizations.
03640         !A->hasOneUse()) {
03641       unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
03642 
03643       if (ShAmt < ASize) {
03644         APInt MaskV =
03645           APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
03646         MaskV <<= ShAmt;
03647 
03648         APInt CmpV = Cst1->getValue().zext(ASize);
03649         CmpV <<= ShAmt;
03650 
03651         Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV));
03652         return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV));
03653       }
03654     }
03655   }
03656 
03657   // The 'cmpxchg' instruction returns an aggregate containing the old value and
03658   // an i1 which indicates whether or not we successfully did the swap.
03659   //
03660   // Replace comparisons between the old value and the expected value with the
03661   // indicator that 'cmpxchg' returns.
03662   //
03663   // N.B.  This transform is only valid when the 'cmpxchg' is not permitted to
03664   // spuriously fail.  In those cases, the old value may equal the expected
03665   // value but it is possible for the swap to not occur.
03666   if (I.getPredicate() == ICmpInst::ICMP_EQ)
03667     if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
03668       if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
03669         if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
03670             !ACXI->isWeak())
03671           return ExtractValueInst::Create(ACXI, 1);
03672 
03673   {
03674     Value *X; ConstantInt *Cst;
03675     // icmp X+Cst, X
03676     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
03677       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate());
03678 
03679     // icmp X, X+Cst
03680     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
03681       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate());
03682   }
03683   return Changed ? &I : nullptr;
03684 }
03685 
03686 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
03687 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
03688                                                 Instruction *LHSI,
03689                                                 Constant *RHSC) {
03690   if (!isa<ConstantFP>(RHSC)) return nullptr;
03691   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
03692 
03693   // Get the width of the mantissa.  We don't want to hack on conversions that
03694   // might lose information from the integer, e.g. "i64 -> float"
03695   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
03696   if (MantissaWidth == -1) return nullptr;  // Unknown.
03697 
03698   IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
03699 
03700   // Check to see that the input is converted from an integer type that is small
03701   // enough that preserves all bits.  TODO: check here for "known" sign bits.
03702   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
03703   unsigned InputSize = IntTy->getScalarSizeInBits();
03704 
03705   // If this is a uitofp instruction, we need an extra bit to hold the sign.
03706   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
03707   if (LHSUnsigned)
03708     ++InputSize;
03709 
03710   if (I.isEquality()) {
03711     FCmpInst::Predicate P = I.getPredicate();
03712     bool IsExact = false;
03713     APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
03714     RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
03715 
03716     // If the floating point constant isn't an integer value, we know if we will
03717     // ever compare equal / not equal to it.
03718     if (!IsExact) {
03719       // TODO: Can never be -0.0 and other non-representable values
03720       APFloat RHSRoundInt(RHS);
03721       RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
03722       if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) {
03723         if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
03724           return ReplaceInstUsesWith(I, Builder->getFalse());
03725 
03726         assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
03727         return ReplaceInstUsesWith(I, Builder->getTrue());
03728       }
03729     }
03730 
03731     // TODO: If the constant is exactly representable, is it always OK to do
03732     // equality compares as integer?
03733   }
03734 
03735   // Comparisons with zero are a special case where we know we won't lose
03736   // information.
03737   bool IsCmpZero = RHS.isPosZero();
03738 
03739   // If the conversion would lose info, don't hack on this.
03740   if ((int)InputSize > MantissaWidth && !IsCmpZero)
03741     return nullptr;
03742 
03743   // Otherwise, we can potentially simplify the comparison.  We know that it
03744   // will always come through as an integer value and we know the constant is
03745   // not a NAN (it would have been previously simplified).
03746   assert(!RHS.isNaN() && "NaN comparison not already folded!");
03747 
03748   ICmpInst::Predicate Pred;
03749   switch (I.getPredicate()) {
03750   default: llvm_unreachable("Unexpected predicate!");
03751   case FCmpInst::FCMP_UEQ:
03752   case FCmpInst::FCMP_OEQ:
03753     Pred = ICmpInst::ICMP_EQ;
03754     break;
03755   case FCmpInst::FCMP_UGT:
03756   case FCmpInst::FCMP_OGT:
03757     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
03758     break;
03759   case FCmpInst::FCMP_UGE:
03760   case FCmpInst::FCMP_OGE:
03761     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
03762     break;
03763   case FCmpInst::FCMP_ULT:
03764   case FCmpInst::FCMP_OLT:
03765     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
03766     break;
03767   case FCmpInst::FCMP_ULE:
03768   case FCmpInst::FCMP_OLE:
03769     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
03770     break;
03771   case FCmpInst::FCMP_UNE:
03772   case FCmpInst::FCMP_ONE:
03773     Pred = ICmpInst::ICMP_NE;
03774     break;
03775   case FCmpInst::FCMP_ORD:
03776     return ReplaceInstUsesWith(I, Builder->getTrue());
03777   case FCmpInst::FCMP_UNO:
03778     return ReplaceInstUsesWith(I, Builder->getFalse());
03779   }
03780 
03781   // Now we know that the APFloat is a normal number, zero or inf.
03782 
03783   // See if the FP constant is too large for the integer.  For example,
03784   // comparing an i8 to 300.0.
03785   unsigned IntWidth = IntTy->getScalarSizeInBits();
03786 
03787   if (!LHSUnsigned) {
03788     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
03789     // and large values.
03790     APFloat SMax(RHS.getSemantics());
03791     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
03792                           APFloat::rmNearestTiesToEven);
03793     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
03794       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
03795           Pred == ICmpInst::ICMP_SLE)
03796         return ReplaceInstUsesWith(I, Builder->getTrue());
03797       return ReplaceInstUsesWith(I, Builder->getFalse());
03798     }
03799   } else {
03800     // If the RHS value is > UnsignedMax, fold the comparison. This handles
03801     // +INF and large values.
03802     APFloat UMax(RHS.getSemantics());
03803     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
03804                           APFloat::rmNearestTiesToEven);
03805     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
03806       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
03807           Pred == ICmpInst::ICMP_ULE)
03808         return ReplaceInstUsesWith(I, Builder->getTrue());
03809       return ReplaceInstUsesWith(I, Builder->getFalse());
03810     }
03811   }
03812 
03813   if (!LHSUnsigned) {
03814     // See if the RHS value is < SignedMin.
03815     APFloat SMin(RHS.getSemantics());
03816     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
03817                           APFloat::rmNearestTiesToEven);
03818     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
03819       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
03820           Pred == ICmpInst::ICMP_SGE)
03821         return ReplaceInstUsesWith(I, Builder->getTrue());
03822       return ReplaceInstUsesWith(I, Builder->getFalse());
03823     }
03824   } else {
03825     // See if the RHS value is < UnsignedMin.
03826     APFloat SMin(RHS.getSemantics());
03827     SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
03828                           APFloat::rmNearestTiesToEven);
03829     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0
03830       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
03831           Pred == ICmpInst::ICMP_UGE)
03832         return ReplaceInstUsesWith(I, Builder->getTrue());
03833       return ReplaceInstUsesWith(I, Builder->getFalse());
03834     }
03835   }
03836 
03837   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
03838   // [0, UMAX], but it may still be fractional.  See if it is fractional by
03839   // casting the FP value to the integer value and back, checking for equality.
03840   // Don't do this for zero, because -0.0 is not fractional.
03841   Constant *RHSInt = LHSUnsigned
03842     ? ConstantExpr::getFPToUI(RHSC, IntTy)
03843     : ConstantExpr::getFPToSI(RHSC, IntTy);
03844   if (!RHS.isZero()) {
03845     bool Equal = LHSUnsigned
03846       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
03847       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
03848     if (!Equal) {
03849       // If we had a comparison against a fractional value, we have to adjust
03850       // the compare predicate and sometimes the value.  RHSC is rounded towards
03851       // zero at this point.
03852       switch (Pred) {
03853       default: llvm_unreachable("Unexpected integer comparison!");
03854       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
03855         return ReplaceInstUsesWith(I, Builder->getTrue());
03856       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
03857         return ReplaceInstUsesWith(I, Builder->getFalse());
03858       case ICmpInst::ICMP_ULE:
03859         // (float)int <= 4.4   --> int <= 4
03860         // (float)int <= -4.4  --> false
03861         if (RHS.isNegative())
03862           return ReplaceInstUsesWith(I, Builder->getFalse());
03863         break;
03864       case ICmpInst::ICMP_SLE:
03865         // (float)int <= 4.4   --> int <= 4
03866         // (float)int <= -4.4  --> int < -4
03867         if (RHS.isNegative())
03868           Pred = ICmpInst::ICMP_SLT;
03869         break;
03870       case ICmpInst::ICMP_ULT:
03871         // (float)int < -4.4   --> false
03872         // (float)int < 4.4    --> int <= 4
03873         if (RHS.isNegative())
03874           return ReplaceInstUsesWith(I, Builder->getFalse());
03875         Pred = ICmpInst::ICMP_ULE;
03876         break;
03877       case ICmpInst::ICMP_SLT:
03878         // (float)int < -4.4   --> int < -4
03879         // (float)int < 4.4    --> int <= 4
03880         if (!RHS.isNegative())
03881           Pred = ICmpInst::ICMP_SLE;
03882         break;
03883       case ICmpInst::ICMP_UGT:
03884         // (float)int > 4.4    --> int > 4
03885         // (float)int > -4.4   --> true
03886         if (RHS.isNegative())
03887           return ReplaceInstUsesWith(I, Builder->getTrue());
03888         break;
03889       case ICmpInst::ICMP_SGT:
03890         // (float)int > 4.4    --> int > 4
03891         // (float)int > -4.4   --> int >= -4
03892         if (RHS.isNegative())
03893           Pred = ICmpInst::ICMP_SGE;
03894         break;
03895       case ICmpInst::ICMP_UGE:
03896         // (float)int >= -4.4   --> true
03897         // (float)int >= 4.4    --> int > 4
03898         if (RHS.isNegative())
03899           return ReplaceInstUsesWith(I, Builder->getTrue());
03900         Pred = ICmpInst::ICMP_UGT;
03901         break;
03902       case ICmpInst::ICMP_SGE:
03903         // (float)int >= -4.4   --> int >= -4
03904         // (float)int >= 4.4    --> int > 4
03905         if (!RHS.isNegative())
03906           Pred = ICmpInst::ICMP_SGT;
03907         break;
03908       }
03909     }
03910   }
03911 
03912   // Lower this FP comparison into an appropriate integer version of the
03913   // comparison.
03914   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
03915 }
03916 
03917 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
03918   bool Changed = false;
03919 
03920   /// Orders the operands of the compare so that they are listed from most
03921   /// complex to least complex.  This puts constants before unary operators,
03922   /// before binary operators.
03923   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
03924     I.swapOperands();
03925     Changed = true;
03926   }
03927 
03928   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
03929 
03930   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, DL, TLI, DT, AC))
03931     return ReplaceInstUsesWith(I, V);
03932 
03933   // Simplify 'fcmp pred X, X'
03934   if (Op0 == Op1) {
03935     switch (I.getPredicate()) {
03936     default: llvm_unreachable("Unknown predicate!");
03937     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
03938     case FCmpInst::FCMP_ULT:    // True if unordered or less than
03939     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
03940     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
03941       // Canonicalize these to be 'fcmp uno %X, 0.0'.
03942       I.setPredicate(FCmpInst::FCMP_UNO);
03943       I.setOperand(1, Constant::getNullValue(Op0->getType()));
03944       return &I;
03945 
03946     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
03947     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
03948     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
03949     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
03950       // Canonicalize these to be 'fcmp ord %X, 0.0'.
03951       I.setPredicate(FCmpInst::FCMP_ORD);
03952       I.setOperand(1, Constant::getNullValue(Op0->getType()));
03953       return &I;
03954     }
03955   }
03956 
03957   // Test if the FCmpInst instruction is used exclusively by a select as
03958   // part of a minimum or maximum operation. If so, refrain from doing
03959   // any other folding. This helps out other analyses which understand
03960   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
03961   // and CodeGen. And in this case, at least one of the comparison
03962   // operands has at least one user besides the compare (the select),
03963   // which would often largely negate the benefit of folding anyway.
03964   if (I.hasOneUse())
03965     if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin()))
03966       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
03967           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
03968         return nullptr;
03969 
03970   // Handle fcmp with constant RHS
03971   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
03972     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
03973       switch (LHSI->getOpcode()) {
03974       case Instruction::FPExt: {
03975         // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless
03976         FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
03977         ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC);
03978         if (!RHSF)
03979           break;
03980 
03981         const fltSemantics *Sem;
03982         // FIXME: This shouldn't be here.
03983         if (LHSExt->getSrcTy()->isHalfTy())
03984           Sem = &APFloat::IEEEhalf;
03985         else if (LHSExt->getSrcTy()->isFloatTy())
03986           Sem = &APFloat::IEEEsingle;
03987         else if (LHSExt->getSrcTy()->isDoubleTy())
03988           Sem = &APFloat::IEEEdouble;
03989         else if (LHSExt->getSrcTy()->isFP128Ty())
03990           Sem = &APFloat::IEEEquad;
03991         else if (LHSExt->getSrcTy()->isX86_FP80Ty())
03992           Sem = &APFloat::x87DoubleExtended;
03993         else if (LHSExt->getSrcTy()->isPPC_FP128Ty())
03994           Sem = &APFloat::PPCDoubleDouble;
03995         else
03996           break;
03997 
03998         bool Lossy;
03999         APFloat F = RHSF->getValueAPF();
04000         F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy);
04001 
04002         // Avoid lossy conversions and denormals. Zero is a special case
04003         // that's OK to convert.
04004         APFloat Fabs = F;
04005         Fabs.clearSign();
04006         if (!Lossy &&
04007             ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) !=
04008                  APFloat::cmpLessThan) || Fabs.isZero()))
04009 
04010           return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
04011                               ConstantFP::get(RHSC->getContext(), F));
04012         break;
04013       }
04014       case Instruction::PHI:
04015         // Only fold fcmp into the PHI if the phi and fcmp are in the same
04016         // block.  If in the same block, we're encouraging jump threading.  If
04017         // not, we are just pessimizing the code by making an i1 phi.
04018         if (LHSI->getParent() == I.getParent())
04019           if (Instruction *NV = FoldOpIntoPhi(I))
04020             return NV;
04021         break;
04022       case Instruction::SIToFP:
04023       case Instruction::UIToFP:
04024         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
04025           return NV;
04026         break;
04027       case Instruction::FSub: {
04028         // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C
04029         Value *Op;
04030         if (match(LHSI, m_FNeg(m_Value(Op))))
04031           return new FCmpInst(I.getSwappedPredicate(), Op,
04032                               ConstantExpr::getFNeg(RHSC));
04033         break;
04034       }
04035       case Instruction::Load:
04036         if (GetElementPtrInst *GEP =
04037             dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
04038           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
04039             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
04040                 !cast<LoadInst>(LHSI)->isVolatile())
04041               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
04042                 return Res;
04043         }
04044         break;
04045       case Instruction::Call: {
04046         if (!RHSC->isNullValue())
04047           break;
04048 
04049         CallInst *CI = cast<CallInst>(LHSI);
04050         const Function *F = CI->getCalledFunction();
04051         if (!F)
04052           break;
04053 
04054         // Various optimization for fabs compared with zero.
04055         LibFunc::Func Func;
04056         if (F->getIntrinsicID() == Intrinsic::fabs ||
04057             (TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
04058              (Func == LibFunc::fabs || Func == LibFunc::fabsf ||
04059               Func == LibFunc::fabsl))) {
04060           switch (I.getPredicate()) {
04061           default:
04062             break;
04063             // fabs(x) < 0 --> false
04064           case FCmpInst::FCMP_OLT:
04065             return ReplaceInstUsesWith(I, Builder->getFalse());
04066             // fabs(x) > 0 --> x != 0
04067           case FCmpInst::FCMP_OGT:
04068             return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC);
04069             // fabs(x) <= 0 --> x == 0
04070           case FCmpInst::FCMP_OLE:
04071             return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC);
04072             // fabs(x) >= 0 --> !isnan(x)
04073           case FCmpInst::FCMP_OGE:
04074             return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC);
04075             // fabs(x) == 0 --> x == 0
04076             // fabs(x) != 0 --> x != 0
04077           case FCmpInst::FCMP_OEQ:
04078           case FCmpInst::FCMP_UEQ:
04079           case FCmpInst::FCMP_ONE:
04080           case FCmpInst::FCMP_UNE:
04081             return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC);
04082           }
04083         }
04084       }
04085       }
04086   }
04087 
04088   // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y
04089   Value *X, *Y;
04090   if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
04091     return new FCmpInst(I.getSwappedPredicate(), X, Y);
04092 
04093   // fcmp (fpext x), (fpext y) -> fcmp x, y
04094   if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
04095     if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
04096       if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
04097         return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0),
04098                             RHSExt->getOperand(0));
04099 
04100   return Changed ? &I : nullptr;
04101 }