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