LLVM  mainline
InstCombineMulDivRem.cpp
Go to the documentation of this file.
00001 //===- InstCombineMulDivRem.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 visit functions for mul, fmul, sdiv, udiv, fdiv,
00011 // srem, urem, frem.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "InstCombineInternal.h"
00016 #include "llvm/Analysis/InstructionSimplify.h"
00017 #include "llvm/IR/IntrinsicInst.h"
00018 #include "llvm/IR/PatternMatch.h"
00019 using namespace llvm;
00020 using namespace PatternMatch;
00021 
00022 #define DEBUG_TYPE "instcombine"
00023 
00024 
00025 /// The specific integer value is used in a context where it is known to be
00026 /// non-zero.  If this allows us to simplify the computation, do so and return
00027 /// the new operand, otherwise return null.
00028 static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
00029                                         Instruction &CxtI) {
00030   // If V has multiple uses, then we would have to do more analysis to determine
00031   // if this is safe.  For example, the use could be in dynamically unreached
00032   // code.
00033   if (!V->hasOneUse()) return nullptr;
00034 
00035   bool MadeChange = false;
00036 
00037   // ((1 << A) >>u B) --> (1 << (A-B))
00038   // Because V cannot be zero, we know that B is less than A.
00039   Value *A = nullptr, *B = nullptr, *One = nullptr;
00040   if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
00041       match(One, m_One())) {
00042     A = IC.Builder->CreateSub(A, B);
00043     return IC.Builder->CreateShl(One, A);
00044   }
00045 
00046   // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
00047   // inexact.  Similarly for <<.
00048   if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
00049     if (I->isLogicalShift() &&
00050         isKnownToBeAPowerOfTwo(I->getOperand(0), IC.getDataLayout(), false, 0,
00051                                IC.getAssumptionCache(), &CxtI,
00052                                IC.getDominatorTree())) {
00053       // We know that this is an exact/nuw shift and that the input is a
00054       // non-zero context as well.
00055       if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
00056         I->setOperand(0, V2);
00057         MadeChange = true;
00058       }
00059 
00060       if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
00061         I->setIsExact();
00062         MadeChange = true;
00063       }
00064 
00065       if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
00066         I->setHasNoUnsignedWrap();
00067         MadeChange = true;
00068       }
00069     }
00070 
00071   // TODO: Lots more we could do here:
00072   //    If V is a phi node, we can call this on each of its operands.
00073   //    "select cond, X, 0" can simplify to "X".
00074 
00075   return MadeChange ? V : nullptr;
00076 }
00077 
00078 
00079 /// True if the multiply can not be expressed in an int this size.
00080 static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
00081                               bool IsSigned) {
00082   bool Overflow;
00083   if (IsSigned)
00084     Product = C1.smul_ov(C2, Overflow);
00085   else
00086     Product = C1.umul_ov(C2, Overflow);
00087 
00088   return Overflow;
00089 }
00090 
00091 /// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
00092 static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
00093                        bool IsSigned) {
00094   assert(C1.getBitWidth() == C2.getBitWidth() &&
00095          "Inconsistent width of constants!");
00096 
00097   // Bail if we will divide by zero.
00098   if (C2.isMinValue())
00099     return false;
00100 
00101   // Bail if we would divide INT_MIN by -1.
00102   if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
00103     return false;
00104 
00105   APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
00106   if (IsSigned)
00107     APInt::sdivrem(C1, C2, Quotient, Remainder);
00108   else
00109     APInt::udivrem(C1, C2, Quotient, Remainder);
00110 
00111   return Remainder.isMinValue();
00112 }
00113 
00114 /// \brief A helper routine of InstCombiner::visitMul().
00115 ///
00116 /// If C is a vector of known powers of 2, then this function returns
00117 /// a new vector obtained from C replacing each element with its logBase2.
00118 /// Return a null pointer otherwise.
00119 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
00120   const APInt *IVal;
00121   SmallVector<Constant *, 4> Elts;
00122 
00123   for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
00124     Constant *Elt = CV->getElementAsConstant(I);
00125     if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
00126       return nullptr;
00127     Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
00128   }
00129 
00130   return ConstantVector::get(Elts);
00131 }
00132 
00133 /// \brief Return true if we can prove that:
00134 ///    (mul LHS, RHS)  === (mul nsw LHS, RHS)
00135 bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS,
00136                                             Instruction &CxtI) {
00137   // Multiplying n * m significant bits yields a result of n + m significant
00138   // bits. If the total number of significant bits does not exceed the
00139   // result bit width (minus 1), there is no overflow.
00140   // This means if we have enough leading sign bits in the operands
00141   // we can guarantee that the result does not overflow.
00142   // Ref: "Hacker's Delight" by Henry Warren
00143   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
00144 
00145   // Note that underestimating the number of sign bits gives a more
00146   // conservative answer.
00147   unsigned SignBits =
00148       ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
00149 
00150   // First handle the easy case: if we have enough sign bits there's
00151   // definitely no overflow.
00152   if (SignBits > BitWidth + 1)
00153     return true;
00154 
00155   // There are two ambiguous cases where there can be no overflow:
00156   //   SignBits == BitWidth + 1    and
00157   //   SignBits == BitWidth
00158   // The second case is difficult to check, therefore we only handle the
00159   // first case.
00160   if (SignBits == BitWidth + 1) {
00161     // It overflows only when both arguments are negative and the true
00162     // product is exactly the minimum negative number.
00163     // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
00164     // For simplicity we just check if at least one side is not negative.
00165     bool LHSNonNegative, LHSNegative;
00166     bool RHSNonNegative, RHSNegative;
00167     ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, &CxtI);
00168     ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, &CxtI);
00169     if (LHSNonNegative || RHSNonNegative)
00170       return true;
00171   }
00172   return false;
00173 }
00174 
00175 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
00176   bool Changed = SimplifyAssociativeOrCommutative(I);
00177   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00178 
00179   if (Value *V = SimplifyVectorOp(I))
00180     return ReplaceInstUsesWith(I, V);
00181 
00182   if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AC))
00183     return ReplaceInstUsesWith(I, V);
00184 
00185   if (Value *V = SimplifyUsingDistributiveLaws(I))
00186     return ReplaceInstUsesWith(I, V);
00187 
00188   // X * -1 == 0 - X
00189   if (match(Op1, m_AllOnes())) {
00190     BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
00191     if (I.hasNoSignedWrap())
00192       BO->setHasNoSignedWrap();
00193     return BO;
00194   }
00195 
00196   // Also allow combining multiply instructions on vectors.
00197   {
00198     Value *NewOp;
00199     Constant *C1, *C2;
00200     const APInt *IVal;
00201     if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
00202                         m_Constant(C1))) &&
00203         match(C1, m_APInt(IVal))) {
00204       // ((X << C2)*C1) == (X * (C1 << C2))
00205       Constant *Shl = ConstantExpr::getShl(C1, C2);
00206       BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
00207       BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
00208       if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
00209         BO->setHasNoUnsignedWrap();
00210       if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
00211           Shl->isNotMinSignedValue())
00212         BO->setHasNoSignedWrap();
00213       return BO;
00214     }
00215 
00216     if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
00217       Constant *NewCst = nullptr;
00218       if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
00219         // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
00220         NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
00221       else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
00222         // Replace X*(2^C) with X << C, where C is a vector of known
00223         // constant powers of 2.
00224         NewCst = getLogBase2Vector(CV);
00225 
00226       if (NewCst) {
00227         unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
00228         BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
00229 
00230         if (I.hasNoUnsignedWrap())
00231           Shl->setHasNoUnsignedWrap();
00232         if (I.hasNoSignedWrap()) {
00233           uint64_t V;
00234           if (match(NewCst, m_ConstantInt(V)) && V != Width - 1)
00235             Shl->setHasNoSignedWrap();
00236         }
00237 
00238         return Shl;
00239       }
00240     }
00241   }
00242 
00243   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
00244     // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
00245     // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
00246     // The "* (2**n)" thus becomes a potential shifting opportunity.
00247     {
00248       const APInt &   Val = CI->getValue();
00249       const APInt &PosVal = Val.abs();
00250       if (Val.isNegative() && PosVal.isPowerOf2()) {
00251         Value *X = nullptr, *Y = nullptr;
00252         if (Op0->hasOneUse()) {
00253           ConstantInt *C1;
00254           Value *Sub = nullptr;
00255           if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
00256             Sub = Builder->CreateSub(X, Y, "suba");
00257           else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
00258             Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
00259           if (Sub)
00260             return
00261               BinaryOperator::CreateMul(Sub,
00262                                         ConstantInt::get(Y->getType(), PosVal));
00263         }
00264       }
00265     }
00266   }
00267 
00268   // Simplify mul instructions with a constant RHS.
00269   if (isa<Constant>(Op1)) {
00270     // Try to fold constant mul into select arguments.
00271     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
00272       if (Instruction *R = FoldOpIntoSelect(I, SI))
00273         return R;
00274 
00275     if (isa<PHINode>(Op0))
00276       if (Instruction *NV = FoldOpIntoPhi(I))
00277         return NV;
00278 
00279     // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
00280     {
00281       Value *X;
00282       Constant *C1;
00283       if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
00284         Value *Mul = Builder->CreateMul(C1, Op1);
00285         // Only go forward with the transform if C1*CI simplifies to a tidier
00286         // constant.
00287         if (!match(Mul, m_Mul(m_Value(), m_Value())))
00288           return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
00289       }
00290     }
00291   }
00292 
00293   if (Value *Op0v = dyn_castNegVal(Op0)) {   // -X * -Y = X*Y
00294     if (Value *Op1v = dyn_castNegVal(Op1)) {
00295       BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
00296       if (I.hasNoSignedWrap() &&
00297           match(Op0, m_NSWSub(m_Value(), m_Value())) &&
00298           match(Op1, m_NSWSub(m_Value(), m_Value())))
00299         BO->setHasNoSignedWrap();
00300       return BO;
00301     }
00302   }
00303 
00304   // (X / Y) *  Y = X - (X % Y)
00305   // (X / Y) * -Y = (X % Y) - X
00306   {
00307     Value *Op1C = Op1;
00308     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
00309     if (!BO ||
00310         (BO->getOpcode() != Instruction::UDiv &&
00311          BO->getOpcode() != Instruction::SDiv)) {
00312       Op1C = Op0;
00313       BO = dyn_cast<BinaryOperator>(Op1);
00314     }
00315     Value *Neg = dyn_castNegVal(Op1C);
00316     if (BO && BO->hasOneUse() &&
00317         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
00318         (BO->getOpcode() == Instruction::UDiv ||
00319          BO->getOpcode() == Instruction::SDiv)) {
00320       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
00321 
00322       // If the division is exact, X % Y is zero, so we end up with X or -X.
00323       if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
00324         if (SDiv->isExact()) {
00325           if (Op1BO == Op1C)
00326             return ReplaceInstUsesWith(I, Op0BO);
00327           return BinaryOperator::CreateNeg(Op0BO);
00328         }
00329 
00330       Value *Rem;
00331       if (BO->getOpcode() == Instruction::UDiv)
00332         Rem = Builder->CreateURem(Op0BO, Op1BO);
00333       else
00334         Rem = Builder->CreateSRem(Op0BO, Op1BO);
00335       Rem->takeName(BO);
00336 
00337       if (Op1BO == Op1C)
00338         return BinaryOperator::CreateSub(Op0BO, Rem);
00339       return BinaryOperator::CreateSub(Rem, Op0BO);
00340     }
00341   }
00342 
00343   /// i1 mul -> i1 and.
00344   if (I.getType()->getScalarType()->isIntegerTy(1))
00345     return BinaryOperator::CreateAnd(Op0, Op1);
00346 
00347   // X*(1 << Y) --> X << Y
00348   // (1 << Y)*X --> X << Y
00349   {
00350     Value *Y;
00351     BinaryOperator *BO = nullptr;
00352     bool ShlNSW = false;
00353     if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
00354       BO = BinaryOperator::CreateShl(Op1, Y);
00355       ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
00356     } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
00357       BO = BinaryOperator::CreateShl(Op0, Y);
00358       ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
00359     }
00360     if (BO) {
00361       if (I.hasNoUnsignedWrap())
00362         BO->setHasNoUnsignedWrap();
00363       if (I.hasNoSignedWrap() && ShlNSW)
00364         BO->setHasNoSignedWrap();
00365       return BO;
00366     }
00367   }
00368 
00369   // If one of the operands of the multiply is a cast from a boolean value, then
00370   // we know the bool is either zero or one, so this is a 'masking' multiply.
00371   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
00372   if (!I.getType()->isVectorTy()) {
00373     // -2 is "-1 << 1" so it is all bits set except the low one.
00374     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
00375 
00376     Value *BoolCast = nullptr, *OtherOp = nullptr;
00377     if (MaskedValueIsZero(Op0, Negative2, 0, &I))
00378       BoolCast = Op0, OtherOp = Op1;
00379     else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
00380       BoolCast = Op1, OtherOp = Op0;
00381 
00382     if (BoolCast) {
00383       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
00384                                     BoolCast);
00385       return BinaryOperator::CreateAnd(V, OtherOp);
00386     }
00387   }
00388 
00389   if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, I)) {
00390     Changed = true;
00391     I.setHasNoSignedWrap(true);
00392   }
00393 
00394   if (!I.hasNoUnsignedWrap() &&
00395       computeOverflowForUnsignedMul(Op0, Op1, &I) ==
00396           OverflowResult::NeverOverflows) {
00397     Changed = true;
00398     I.setHasNoUnsignedWrap(true);
00399   }
00400 
00401   return Changed ? &I : nullptr;
00402 }
00403 
00404 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
00405 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
00406   if (!Op->hasOneUse())
00407     return;
00408 
00409   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
00410   if (!II)
00411     return;
00412   if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
00413     return;
00414   Log2 = II;
00415 
00416   Value *OpLog2Of = II->getArgOperand(0);
00417   if (!OpLog2Of->hasOneUse())
00418     return;
00419 
00420   Instruction *I = dyn_cast<Instruction>(OpLog2Of);
00421   if (!I)
00422     return;
00423   if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
00424     return;
00425 
00426   if (match(I->getOperand(0), m_SpecificFP(0.5)))
00427     Y = I->getOperand(1);
00428   else if (match(I->getOperand(1), m_SpecificFP(0.5)))
00429     Y = I->getOperand(0);
00430 }
00431 
00432 static bool isFiniteNonZeroFp(Constant *C) {
00433   if (C->getType()->isVectorTy()) {
00434     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
00435          ++I) {
00436       ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
00437       if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
00438         return false;
00439     }
00440     return true;
00441   }
00442 
00443   return isa<ConstantFP>(C) &&
00444          cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
00445 }
00446 
00447 static bool isNormalFp(Constant *C) {
00448   if (C->getType()->isVectorTy()) {
00449     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
00450          ++I) {
00451       ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
00452       if (!CFP || !CFP->getValueAPF().isNormal())
00453         return false;
00454     }
00455     return true;
00456   }
00457 
00458   return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
00459 }
00460 
00461 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
00462 /// true iff the given value is FMul or FDiv with one and only one operand
00463 /// being a normal constant (i.e. not Zero/NaN/Infinity).
00464 static bool isFMulOrFDivWithConstant(Value *V) {
00465   Instruction *I = dyn_cast<Instruction>(V);
00466   if (!I || (I->getOpcode() != Instruction::FMul &&
00467              I->getOpcode() != Instruction::FDiv))
00468     return false;
00469 
00470   Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
00471   Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
00472 
00473   if (C0 && C1)
00474     return false;
00475 
00476   return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
00477 }
00478 
00479 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
00480 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
00481 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
00482 /// This function is to simplify "FMulOrDiv * C" and returns the
00483 /// resulting expression. Note that this function could return NULL in
00484 /// case the constants cannot be folded into a normal floating-point.
00485 ///
00486 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
00487                                    Instruction *InsertBefore) {
00488   assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
00489 
00490   Value *Opnd0 = FMulOrDiv->getOperand(0);
00491   Value *Opnd1 = FMulOrDiv->getOperand(1);
00492 
00493   Constant *C0 = dyn_cast<Constant>(Opnd0);
00494   Constant *C1 = dyn_cast<Constant>(Opnd1);
00495 
00496   BinaryOperator *R = nullptr;
00497 
00498   // (X * C0) * C => X * (C0*C)
00499   if (FMulOrDiv->getOpcode() == Instruction::FMul) {
00500     Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
00501     if (isNormalFp(F))
00502       R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
00503   } else {
00504     if (C0) {
00505       // (C0 / X) * C => (C0 * C) / X
00506       if (FMulOrDiv->hasOneUse()) {
00507         // It would otherwise introduce another div.
00508         Constant *F = ConstantExpr::getFMul(C0, C);
00509         if (isNormalFp(F))
00510           R = BinaryOperator::CreateFDiv(F, Opnd1);
00511       }
00512     } else {
00513       // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
00514       Constant *F = ConstantExpr::getFDiv(C, C1);
00515       if (isNormalFp(F)) {
00516         R = BinaryOperator::CreateFMul(Opnd0, F);
00517       } else {
00518         // (X / C1) * C => X / (C1/C)
00519         Constant *F = ConstantExpr::getFDiv(C1, C);
00520         if (isNormalFp(F))
00521           R = BinaryOperator::CreateFDiv(Opnd0, F);
00522       }
00523     }
00524   }
00525 
00526   if (R) {
00527     R->setHasUnsafeAlgebra(true);
00528     InsertNewInstWith(R, *InsertBefore);
00529   }
00530 
00531   return R;
00532 }
00533 
00534 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
00535   bool Changed = SimplifyAssociativeOrCommutative(I);
00536   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00537 
00538   if (Value *V = SimplifyVectorOp(I))
00539     return ReplaceInstUsesWith(I, V);
00540 
00541   if (isa<Constant>(Op0))
00542     std::swap(Op0, Op1);
00543 
00544   if (Value *V =
00545           SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI, DT, AC))
00546     return ReplaceInstUsesWith(I, V);
00547 
00548   bool AllowReassociate = I.hasUnsafeAlgebra();
00549 
00550   // Simplify mul instructions with a constant RHS.
00551   if (isa<Constant>(Op1)) {
00552     // Try to fold constant mul into select arguments.
00553     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
00554       if (Instruction *R = FoldOpIntoSelect(I, SI))
00555         return R;
00556 
00557     if (isa<PHINode>(Op0))
00558       if (Instruction *NV = FoldOpIntoPhi(I))
00559         return NV;
00560 
00561     // (fmul X, -1.0) --> (fsub -0.0, X)
00562     if (match(Op1, m_SpecificFP(-1.0))) {
00563       Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
00564       Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
00565       RI->copyFastMathFlags(&I);
00566       return RI;
00567     }
00568 
00569     Constant *C = cast<Constant>(Op1);
00570     if (AllowReassociate && isFiniteNonZeroFp(C)) {
00571       // Let MDC denote an expression in one of these forms:
00572       // X * C, C/X, X/C, where C is a constant.
00573       //
00574       // Try to simplify "MDC * Constant"
00575       if (isFMulOrFDivWithConstant(Op0))
00576         if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
00577           return ReplaceInstUsesWith(I, V);
00578 
00579       // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
00580       Instruction *FAddSub = dyn_cast<Instruction>(Op0);
00581       if (FAddSub &&
00582           (FAddSub->getOpcode() == Instruction::FAdd ||
00583            FAddSub->getOpcode() == Instruction::FSub)) {
00584         Value *Opnd0 = FAddSub->getOperand(0);
00585         Value *Opnd1 = FAddSub->getOperand(1);
00586         Constant *C0 = dyn_cast<Constant>(Opnd0);
00587         Constant *C1 = dyn_cast<Constant>(Opnd1);
00588         bool Swap = false;
00589         if (C0) {
00590           std::swap(C0, C1);
00591           std::swap(Opnd0, Opnd1);
00592           Swap = true;
00593         }
00594 
00595         if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
00596           Value *M1 = ConstantExpr::getFMul(C1, C);
00597           Value *M0 = isNormalFp(cast<Constant>(M1)) ?
00598                       foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
00599                       nullptr;
00600           if (M0 && M1) {
00601             if (Swap && FAddSub->getOpcode() == Instruction::FSub)
00602               std::swap(M0, M1);
00603 
00604             Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
00605                                   ? BinaryOperator::CreateFAdd(M0, M1)
00606                                   : BinaryOperator::CreateFSub(M0, M1);
00607             RI->copyFastMathFlags(&I);
00608             return RI;
00609           }
00610         }
00611       }
00612     }
00613   }
00614 
00615   // sqrt(X) * sqrt(X) -> X
00616   if (AllowReassociate && (Op0 == Op1))
00617     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
00618       if (II->getIntrinsicID() == Intrinsic::sqrt)
00619         return ReplaceInstUsesWith(I, II->getOperand(0));
00620 
00621   // Under unsafe algebra do:
00622   // X * log2(0.5*Y) = X*log2(Y) - X
00623   if (AllowReassociate) {
00624     Value *OpX = nullptr;
00625     Value *OpY = nullptr;
00626     IntrinsicInst *Log2;
00627     detectLog2OfHalf(Op0, OpY, Log2);
00628     if (OpY) {
00629       OpX = Op1;
00630     } else {
00631       detectLog2OfHalf(Op1, OpY, Log2);
00632       if (OpY) {
00633         OpX = Op0;
00634       }
00635     }
00636     // if pattern detected emit alternate sequence
00637     if (OpX && OpY) {
00638       BuilderTy::FastMathFlagGuard Guard(*Builder);
00639       Builder->setFastMathFlags(Log2->getFastMathFlags());
00640       Log2->setArgOperand(0, OpY);
00641       Value *FMulVal = Builder->CreateFMul(OpX, Log2);
00642       Value *FSub = Builder->CreateFSub(FMulVal, OpX);
00643       FSub->takeName(&I);
00644       return ReplaceInstUsesWith(I, FSub);
00645     }
00646   }
00647 
00648   // Handle symmetric situation in a 2-iteration loop
00649   Value *Opnd0 = Op0;
00650   Value *Opnd1 = Op1;
00651   for (int i = 0; i < 2; i++) {
00652     bool IgnoreZeroSign = I.hasNoSignedZeros();
00653     if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
00654       BuilderTy::FastMathFlagGuard Guard(*Builder);
00655       Builder->setFastMathFlags(I.getFastMathFlags());
00656 
00657       Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
00658       Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
00659 
00660       // -X * -Y => X*Y
00661       if (N1) {
00662         Value *FMul = Builder->CreateFMul(N0, N1);
00663         FMul->takeName(&I);
00664         return ReplaceInstUsesWith(I, FMul);
00665       }
00666 
00667       if (Opnd0->hasOneUse()) {
00668         // -X * Y => -(X*Y) (Promote negation as high as possible)
00669         Value *T = Builder->CreateFMul(N0, Opnd1);
00670         Value *Neg = Builder->CreateFNeg(T);
00671         Neg->takeName(&I);
00672         return ReplaceInstUsesWith(I, Neg);
00673       }
00674     }
00675 
00676     // (X*Y) * X => (X*X) * Y where Y != X
00677     //  The purpose is two-fold:
00678     //   1) to form a power expression (of X).
00679     //   2) potentially shorten the critical path: After transformation, the
00680     //  latency of the instruction Y is amortized by the expression of X*X,
00681     //  and therefore Y is in a "less critical" position compared to what it
00682     //  was before the transformation.
00683     //
00684     if (AllowReassociate) {
00685       Value *Opnd0_0, *Opnd0_1;
00686       if (Opnd0->hasOneUse() &&
00687           match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
00688         Value *Y = nullptr;
00689         if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
00690           Y = Opnd0_1;
00691         else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
00692           Y = Opnd0_0;
00693 
00694         if (Y) {
00695           BuilderTy::FastMathFlagGuard Guard(*Builder);
00696           Builder->setFastMathFlags(I.getFastMathFlags());
00697           Value *T = Builder->CreateFMul(Opnd1, Opnd1);
00698 
00699           Value *R = Builder->CreateFMul(T, Y);
00700           R->takeName(&I);
00701           return ReplaceInstUsesWith(I, R);
00702         }
00703       }
00704     }
00705 
00706     if (!isa<Constant>(Op1))
00707       std::swap(Opnd0, Opnd1);
00708     else
00709       break;
00710   }
00711 
00712   return Changed ? &I : nullptr;
00713 }
00714 
00715 /// Try to fold a divide or remainder of a select instruction.
00716 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
00717   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
00718 
00719   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
00720   int NonNullOperand = -1;
00721   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
00722     if (ST->isNullValue())
00723       NonNullOperand = 2;
00724   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
00725   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
00726     if (ST->isNullValue())
00727       NonNullOperand = 1;
00728 
00729   if (NonNullOperand == -1)
00730     return false;
00731 
00732   Value *SelectCond = SI->getOperand(0);
00733 
00734   // Change the div/rem to use 'Y' instead of the select.
00735   I.setOperand(1, SI->getOperand(NonNullOperand));
00736 
00737   // Okay, we know we replace the operand of the div/rem with 'Y' with no
00738   // problem.  However, the select, or the condition of the select may have
00739   // multiple uses.  Based on our knowledge that the operand must be non-zero,
00740   // propagate the known value for the select into other uses of it, and
00741   // propagate a known value of the condition into its other users.
00742 
00743   // If the select and condition only have a single use, don't bother with this,
00744   // early exit.
00745   if (SI->use_empty() && SelectCond->hasOneUse())
00746     return true;
00747 
00748   // Scan the current block backward, looking for other uses of SI.
00749   BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
00750 
00751   while (BBI != BBFront) {
00752     --BBI;
00753     // If we found a call to a function, we can't assume it will return, so
00754     // information from below it cannot be propagated above it.
00755     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
00756       break;
00757 
00758     // Replace uses of the select or its condition with the known values.
00759     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
00760          I != E; ++I) {
00761       if (*I == SI) {
00762         *I = SI->getOperand(NonNullOperand);
00763         Worklist.Add(&*BBI);
00764       } else if (*I == SelectCond) {
00765         *I = Builder->getInt1(NonNullOperand == 1);
00766         Worklist.Add(&*BBI);
00767       }
00768     }
00769 
00770     // If we past the instruction, quit looking for it.
00771     if (&*BBI == SI)
00772       SI = nullptr;
00773     if (&*BBI == SelectCond)
00774       SelectCond = nullptr;
00775 
00776     // If we ran out of things to eliminate, break out of the loop.
00777     if (!SelectCond && !SI)
00778       break;
00779 
00780   }
00781   return true;
00782 }
00783 
00784 
00785 /// This function implements the transforms common to both integer division
00786 /// instructions (udiv and sdiv). It is called by the visitors to those integer
00787 /// division instructions.
00788 /// @brief Common integer divide transforms
00789 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
00790   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
00791 
00792   // The RHS is known non-zero.
00793   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
00794     I.setOperand(1, V);
00795     return &I;
00796   }
00797 
00798   // Handle cases involving: [su]div X, (select Cond, Y, Z)
00799   // This does not apply for fdiv.
00800   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
00801     return &I;
00802 
00803   if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
00804     const APInt *C2;
00805     if (match(Op1, m_APInt(C2))) {
00806       Value *X;
00807       const APInt *C1;
00808       bool IsSigned = I.getOpcode() == Instruction::SDiv;
00809 
00810       // (X / C1) / C2  -> X / (C1*C2)
00811       if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
00812           (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
00813         APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
00814         if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
00815           return BinaryOperator::Create(I.getOpcode(), X,
00816                                         ConstantInt::get(I.getType(), Product));
00817       }
00818 
00819       if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
00820           (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
00821         APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
00822 
00823         // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
00824         if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
00825           BinaryOperator *BO = BinaryOperator::Create(
00826               I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
00827           BO->setIsExact(I.isExact());
00828           return BO;
00829         }
00830 
00831         // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
00832         if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
00833           BinaryOperator *BO = BinaryOperator::Create(
00834               Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
00835           BO->setHasNoUnsignedWrap(
00836               !IsSigned &&
00837               cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
00838           BO->setHasNoSignedWrap(
00839               cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
00840           return BO;
00841         }
00842       }
00843 
00844       if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
00845            *C1 != C1->getBitWidth() - 1) ||
00846           (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
00847         APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
00848         APInt C1Shifted = APInt::getOneBitSet(
00849             C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
00850 
00851         // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
00852         if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
00853           BinaryOperator *BO = BinaryOperator::Create(
00854               I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
00855           BO->setIsExact(I.isExact());
00856           return BO;
00857         }
00858 
00859         // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
00860         if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
00861           BinaryOperator *BO = BinaryOperator::Create(
00862               Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
00863           BO->setHasNoUnsignedWrap(
00864               !IsSigned &&
00865               cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
00866           BO->setHasNoSignedWrap(
00867               cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
00868           return BO;
00869         }
00870       }
00871 
00872       if (*C2 != 0) { // avoid X udiv 0
00873         if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
00874           if (Instruction *R = FoldOpIntoSelect(I, SI))
00875             return R;
00876         if (isa<PHINode>(Op0))
00877           if (Instruction *NV = FoldOpIntoPhi(I))
00878             return NV;
00879       }
00880     }
00881   }
00882 
00883   if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
00884     if (One->isOne() && !I.getType()->isIntegerTy(1)) {
00885       bool isSigned = I.getOpcode() == Instruction::SDiv;
00886       if (isSigned) {
00887         // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
00888         // result is one, if Op1 is -1 then the result is minus one, otherwise
00889         // it's zero.
00890         Value *Inc = Builder->CreateAdd(Op1, One);
00891         Value *Cmp = Builder->CreateICmpULT(
00892                          Inc, ConstantInt::get(I.getType(), 3));
00893         return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
00894       } else {
00895         // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
00896         // result is one, otherwise it's zero.
00897         return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
00898       }
00899     }
00900   }
00901 
00902   // See if we can fold away this div instruction.
00903   if (SimplifyDemandedInstructionBits(I))
00904     return &I;
00905 
00906   // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
00907   Value *X = nullptr, *Z = nullptr;
00908   if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
00909     bool isSigned = I.getOpcode() == Instruction::SDiv;
00910     if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
00911         (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
00912       return BinaryOperator::Create(I.getOpcode(), X, Op1);
00913   }
00914 
00915   return nullptr;
00916 }
00917 
00918 /// dyn_castZExtVal - Checks if V is a zext or constant that can
00919 /// be truncated to Ty without losing bits.
00920 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
00921   if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
00922     if (Z->getSrcTy() == Ty)
00923       return Z->getOperand(0);
00924   } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
00925     if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
00926       return ConstantExpr::getTrunc(C, Ty);
00927   }
00928   return nullptr;
00929 }
00930 
00931 namespace {
00932 const unsigned MaxDepth = 6;
00933 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
00934                                           const BinaryOperator &I,
00935                                           InstCombiner &IC);
00936 
00937 /// \brief Used to maintain state for visitUDivOperand().
00938 struct UDivFoldAction {
00939   FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
00940                                 ///< operand.  This can be zero if this action
00941                                 ///< joins two actions together.
00942 
00943   Value *OperandToFold;         ///< Which operand to fold.
00944   union {
00945     Instruction *FoldResult;    ///< The instruction returned when FoldAction is
00946                                 ///< invoked.
00947 
00948     size_t SelectLHSIdx;        ///< Stores the LHS action index if this action
00949                                 ///< joins two actions together.
00950   };
00951 
00952   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
00953       : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
00954   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
00955       : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
00956 };
00957 }
00958 
00959 // X udiv 2^C -> X >> C
00960 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
00961                                     const BinaryOperator &I, InstCombiner &IC) {
00962   const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
00963   BinaryOperator *LShr = BinaryOperator::CreateLShr(
00964       Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
00965   if (I.isExact())
00966     LShr->setIsExact();
00967   return LShr;
00968 }
00969 
00970 // X udiv C, where C >= signbit
00971 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
00972                                    const BinaryOperator &I, InstCombiner &IC) {
00973   Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
00974 
00975   return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
00976                             ConstantInt::get(I.getType(), 1));
00977 }
00978 
00979 // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
00980 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
00981                                 InstCombiner &IC) {
00982   Instruction *ShiftLeft = cast<Instruction>(Op1);
00983   if (isa<ZExtInst>(ShiftLeft))
00984     ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
00985 
00986   const APInt &CI =
00987       cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
00988   Value *N = ShiftLeft->getOperand(1);
00989   if (CI != 1)
00990     N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
00991   if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
00992     N = IC.Builder->CreateZExt(N, Z->getDestTy());
00993   BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
00994   if (I.isExact())
00995     LShr->setIsExact();
00996   return LShr;
00997 }
00998 
00999 // \brief Recursively visits the possible right hand operands of a udiv
01000 // instruction, seeing through select instructions, to determine if we can
01001 // replace the udiv with something simpler.  If we find that an operand is not
01002 // able to simplify the udiv, we abort the entire transformation.
01003 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
01004                                SmallVectorImpl<UDivFoldAction> &Actions,
01005                                unsigned Depth = 0) {
01006   // Check to see if this is an unsigned division with an exact power of 2,
01007   // if so, convert to a right shift.
01008   if (match(Op1, m_Power2())) {
01009     Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
01010     return Actions.size();
01011   }
01012 
01013   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
01014     // X udiv C, where C >= signbit
01015     if (C->getValue().isNegative()) {
01016       Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
01017       return Actions.size();
01018     }
01019 
01020   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
01021   if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
01022       match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
01023     Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
01024     return Actions.size();
01025   }
01026 
01027   // The remaining tests are all recursive, so bail out if we hit the limit.
01028   if (Depth++ == MaxDepth)
01029     return 0;
01030 
01031   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
01032     if (size_t LHSIdx =
01033             visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
01034       if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
01035         Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
01036         return Actions.size();
01037       }
01038 
01039   return 0;
01040 }
01041 
01042 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
01043   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01044 
01045   if (Value *V = SimplifyVectorOp(I))
01046     return ReplaceInstUsesWith(I, V);
01047 
01048   if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AC))
01049     return ReplaceInstUsesWith(I, V);
01050 
01051   // Handle the integer div common cases
01052   if (Instruction *Common = commonIDivTransforms(I))
01053     return Common;
01054 
01055   // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
01056   {
01057     Value *X;
01058     const APInt *C1, *C2;
01059     if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
01060         match(Op1, m_APInt(C2))) {
01061       bool Overflow;
01062       APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
01063       if (!Overflow) {
01064         bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
01065         BinaryOperator *BO = BinaryOperator::CreateUDiv(
01066             X, ConstantInt::get(X->getType(), C2ShlC1));
01067         if (IsExact)
01068           BO->setIsExact();
01069         return BO;
01070       }
01071     }
01072   }
01073 
01074   // (zext A) udiv (zext B) --> zext (A udiv B)
01075   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
01076     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
01077       return new ZExtInst(
01078           Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
01079           I.getType());
01080 
01081   // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
01082   SmallVector<UDivFoldAction, 6> UDivActions;
01083   if (visitUDivOperand(Op0, Op1, I, UDivActions))
01084     for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
01085       FoldUDivOperandCb Action = UDivActions[i].FoldAction;
01086       Value *ActionOp1 = UDivActions[i].OperandToFold;
01087       Instruction *Inst;
01088       if (Action)
01089         Inst = Action(Op0, ActionOp1, I, *this);
01090       else {
01091         // This action joins two actions together.  The RHS of this action is
01092         // simply the last action we processed, we saved the LHS action index in
01093         // the joining action.
01094         size_t SelectRHSIdx = i - 1;
01095         Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
01096         size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
01097         Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
01098         Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
01099                                   SelectLHS, SelectRHS);
01100       }
01101 
01102       // If this is the last action to process, return it to the InstCombiner.
01103       // Otherwise, we insert it before the UDiv and record it so that we may
01104       // use it as part of a joining action (i.e., a SelectInst).
01105       if (e - i != 1) {
01106         Inst->insertBefore(&I);
01107         UDivActions[i].FoldResult = Inst;
01108       } else
01109         return Inst;
01110     }
01111 
01112   return nullptr;
01113 }
01114 
01115 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
01116   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01117 
01118   if (Value *V = SimplifyVectorOp(I))
01119     return ReplaceInstUsesWith(I, V);
01120 
01121   if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AC))
01122     return ReplaceInstUsesWith(I, V);
01123 
01124   // Handle the integer div common cases
01125   if (Instruction *Common = commonIDivTransforms(I))
01126     return Common;
01127 
01128   // sdiv X, -1 == -X
01129   if (match(Op1, m_AllOnes()))
01130     return BinaryOperator::CreateNeg(Op0);
01131 
01132   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
01133     // sdiv X, C  -->  ashr exact X, log2(C)
01134     if (I.isExact() && RHS->getValue().isNonNegative() &&
01135         RHS->getValue().isPowerOf2()) {
01136       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
01137                                             RHS->getValue().exactLogBase2());
01138       return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
01139     }
01140   }
01141 
01142   if (Constant *RHS = dyn_cast<Constant>(Op1)) {
01143     // X/INT_MIN -> X == INT_MIN
01144     if (RHS->isMinSignedValue())
01145       return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
01146 
01147     // -X/C  -->  X/-C  provided the negation doesn't overflow.
01148     Value *X;
01149     if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
01150       auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
01151       BO->setIsExact(I.isExact());
01152       return BO;
01153     }
01154   }
01155 
01156   // If the sign bits of both operands are zero (i.e. we can prove they are
01157   // unsigned inputs), turn this into a udiv.
01158   if (I.getType()->isIntegerTy()) {
01159     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
01160     if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
01161       if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
01162         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
01163         auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
01164         BO->setIsExact(I.isExact());
01165         return BO;
01166       }
01167 
01168       if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, AC, &I, DT)) {
01169         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
01170         // Safe because the only negative value (1 << Y) can take on is
01171         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
01172         // the sign bit set.
01173         auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
01174         BO->setIsExact(I.isExact());
01175         return BO;
01176       }
01177     }
01178   }
01179 
01180   return nullptr;
01181 }
01182 
01183 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
01184 /// FP value and:
01185 ///    1) 1/C is exact, or
01186 ///    2) reciprocal is allowed.
01187 /// If the conversion was successful, the simplified expression "X * 1/C" is
01188 /// returned; otherwise, NULL is returned.
01189 ///
01190 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
01191                                              bool AllowReciprocal) {
01192   if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
01193     return nullptr;
01194 
01195   const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
01196   APFloat Reciprocal(FpVal.getSemantics());
01197   bool Cvt = FpVal.getExactInverse(&Reciprocal);
01198 
01199   if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
01200     Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
01201     (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
01202     Cvt = !Reciprocal.isDenormal();
01203   }
01204 
01205   if (!Cvt)
01206     return nullptr;
01207 
01208   ConstantFP *R;
01209   R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
01210   return BinaryOperator::CreateFMul(Dividend, R);
01211 }
01212 
01213 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
01214   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01215 
01216   if (Value *V = SimplifyVectorOp(I))
01217     return ReplaceInstUsesWith(I, V);
01218 
01219   if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
01220                                   DL, TLI, DT, AC))
01221     return ReplaceInstUsesWith(I, V);
01222 
01223   if (isa<Constant>(Op0))
01224     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
01225       if (Instruction *R = FoldOpIntoSelect(I, SI))
01226         return R;
01227 
01228   bool AllowReassociate = I.hasUnsafeAlgebra();
01229   bool AllowReciprocal = I.hasAllowReciprocal();
01230 
01231   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
01232     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
01233       if (Instruction *R = FoldOpIntoSelect(I, SI))
01234         return R;
01235 
01236     if (AllowReassociate) {
01237       Constant *C1 = nullptr;
01238       Constant *C2 = Op1C;
01239       Value *X;
01240       Instruction *Res = nullptr;
01241 
01242       if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
01243         // (X*C1)/C2 => X * (C1/C2)
01244         //
01245         Constant *C = ConstantExpr::getFDiv(C1, C2);
01246         if (isNormalFp(C))
01247           Res = BinaryOperator::CreateFMul(X, C);
01248       } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
01249         // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
01250         //
01251         Constant *C = ConstantExpr::getFMul(C1, C2);
01252         if (isNormalFp(C)) {
01253           Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
01254           if (!Res)
01255             Res = BinaryOperator::CreateFDiv(X, C);
01256         }
01257       }
01258 
01259       if (Res) {
01260         Res->setFastMathFlags(I.getFastMathFlags());
01261         return Res;
01262       }
01263     }
01264 
01265     // X / C => X * 1/C
01266     if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
01267       T->copyFastMathFlags(&I);
01268       return T;
01269     }
01270 
01271     return nullptr;
01272   }
01273 
01274   if (AllowReassociate && isa<Constant>(Op0)) {
01275     Constant *C1 = cast<Constant>(Op0), *C2;
01276     Constant *Fold = nullptr;
01277     Value *X;
01278     bool CreateDiv = true;
01279 
01280     // C1 / (X*C2) => (C1/C2) / X
01281     if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
01282       Fold = ConstantExpr::getFDiv(C1, C2);
01283     else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
01284       // C1 / (X/C2) => (C1*C2) / X
01285       Fold = ConstantExpr::getFMul(C1, C2);
01286     } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
01287       // C1 / (C2/X) => (C1/C2) * X
01288       Fold = ConstantExpr::getFDiv(C1, C2);
01289       CreateDiv = false;
01290     }
01291 
01292     if (Fold && isNormalFp(Fold)) {
01293       Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
01294                                  : BinaryOperator::CreateFMul(X, Fold);
01295       R->setFastMathFlags(I.getFastMathFlags());
01296       return R;
01297     }
01298     return nullptr;
01299   }
01300 
01301   if (AllowReassociate) {
01302     Value *X, *Y;
01303     Value *NewInst = nullptr;
01304     Instruction *SimpR = nullptr;
01305 
01306     if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
01307       // (X/Y) / Z => X / (Y*Z)
01308       //
01309       if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
01310         NewInst = Builder->CreateFMul(Y, Op1);
01311         if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
01312           FastMathFlags Flags = I.getFastMathFlags();
01313           Flags &= cast<Instruction>(Op0)->getFastMathFlags();
01314           RI->setFastMathFlags(Flags);
01315         }
01316         SimpR = BinaryOperator::CreateFDiv(X, NewInst);
01317       }
01318     } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
01319       // Z / (X/Y) => Z*Y / X
01320       //
01321       if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
01322         NewInst = Builder->CreateFMul(Op0, Y);
01323         if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
01324           FastMathFlags Flags = I.getFastMathFlags();
01325           Flags &= cast<Instruction>(Op1)->getFastMathFlags();
01326           RI->setFastMathFlags(Flags);
01327         }
01328         SimpR = BinaryOperator::CreateFDiv(NewInst, X);
01329       }
01330     }
01331 
01332     if (NewInst) {
01333       if (Instruction *T = dyn_cast<Instruction>(NewInst))
01334         T->setDebugLoc(I.getDebugLoc());
01335       SimpR->setFastMathFlags(I.getFastMathFlags());
01336       return SimpR;
01337     }
01338   }
01339 
01340   return nullptr;
01341 }
01342 
01343 /// This function implements the transforms common to both integer remainder
01344 /// instructions (urem and srem). It is called by the visitors to those integer
01345 /// remainder instructions.
01346 /// @brief Common integer remainder transforms
01347 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
01348   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01349 
01350   // The RHS is known non-zero.
01351   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
01352     I.setOperand(1, V);
01353     return &I;
01354   }
01355 
01356   // Handle cases involving: rem X, (select Cond, Y, Z)
01357   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
01358     return &I;
01359 
01360   if (isa<Constant>(Op1)) {
01361     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
01362       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
01363         if (Instruction *R = FoldOpIntoSelect(I, SI))
01364           return R;
01365       } else if (isa<PHINode>(Op0I)) {
01366         if (Instruction *NV = FoldOpIntoPhi(I))
01367           return NV;
01368       }
01369 
01370       // See if we can fold away this rem instruction.
01371       if (SimplifyDemandedInstructionBits(I))
01372         return &I;
01373     }
01374   }
01375 
01376   return nullptr;
01377 }
01378 
01379 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
01380   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01381 
01382   if (Value *V = SimplifyVectorOp(I))
01383     return ReplaceInstUsesWith(I, V);
01384 
01385   if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AC))
01386     return ReplaceInstUsesWith(I, V);
01387 
01388   if (Instruction *common = commonIRemTransforms(I))
01389     return common;
01390 
01391   // (zext A) urem (zext B) --> zext (A urem B)
01392   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
01393     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
01394       return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
01395                           I.getType());
01396 
01397   // X urem Y -> X and Y-1, where Y is a power of 2,
01398   if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, AC, &I, DT)) {
01399     Constant *N1 = Constant::getAllOnesValue(I.getType());
01400     Value *Add = Builder->CreateAdd(Op1, N1);
01401     return BinaryOperator::CreateAnd(Op0, Add);
01402   }
01403 
01404   // 1 urem X -> zext(X != 1)
01405   if (match(Op0, m_One())) {
01406     Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
01407     Value *Ext = Builder->CreateZExt(Cmp, I.getType());
01408     return ReplaceInstUsesWith(I, Ext);
01409   }
01410 
01411   return nullptr;
01412 }
01413 
01414 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
01415   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01416 
01417   if (Value *V = SimplifyVectorOp(I))
01418     return ReplaceInstUsesWith(I, V);
01419 
01420   if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AC))
01421     return ReplaceInstUsesWith(I, V);
01422 
01423   // Handle the integer rem common cases
01424   if (Instruction *Common = commonIRemTransforms(I))
01425     return Common;
01426 
01427   {
01428     const APInt *Y;
01429     // X % -Y -> X % Y
01430     if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
01431       Worklist.AddValue(I.getOperand(1));
01432       I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
01433       return &I;
01434     }
01435   }
01436 
01437   // If the sign bits of both operands are zero (i.e. we can prove they are
01438   // unsigned inputs), turn this into a urem.
01439   if (I.getType()->isIntegerTy()) {
01440     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
01441     if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
01442         MaskedValueIsZero(Op0, Mask, 0, &I)) {
01443       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
01444       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
01445     }
01446   }
01447 
01448   // If it's a constant vector, flip any negative values positive.
01449   if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
01450     Constant *C = cast<Constant>(Op1);
01451     unsigned VWidth = C->getType()->getVectorNumElements();
01452 
01453     bool hasNegative = false;
01454     bool hasMissing = false;
01455     for (unsigned i = 0; i != VWidth; ++i) {
01456       Constant *Elt = C->getAggregateElement(i);
01457       if (!Elt) {
01458         hasMissing = true;
01459         break;
01460       }
01461 
01462       if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
01463         if (RHS->isNegative())
01464           hasNegative = true;
01465     }
01466 
01467     if (hasNegative && !hasMissing) {
01468       SmallVector<Constant *, 16> Elts(VWidth);
01469       for (unsigned i = 0; i != VWidth; ++i) {
01470         Elts[i] = C->getAggregateElement(i);  // Handle undef, etc.
01471         if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
01472           if (RHS->isNegative())
01473             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
01474         }
01475       }
01476 
01477       Constant *NewRHSV = ConstantVector::get(Elts);
01478       if (NewRHSV != C) {  // Don't loop on -MININT
01479         Worklist.AddValue(I.getOperand(1));
01480         I.setOperand(1, NewRHSV);
01481         return &I;
01482       }
01483     }
01484   }
01485 
01486   return nullptr;
01487 }
01488 
01489 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
01490   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01491 
01492   if (Value *V = SimplifyVectorOp(I))
01493     return ReplaceInstUsesWith(I, V);
01494 
01495   if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
01496                                   DL, TLI, DT, AC))
01497     return ReplaceInstUsesWith(I, V);
01498 
01499   // Handle cases involving: rem X, (select Cond, Y, Z)
01500   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
01501     return &I;
01502 
01503   return nullptr;
01504 }