LLVM API Documentation

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