LLVM API Documentation

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