LLVM API Documentation

ValueTracking.cpp
Go to the documentation of this file.
00001 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
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 contains routines that help analyze properties that chains of
00011 // computations have.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/ValueTracking.h"
00016 #include "llvm/Analysis/AssumptionTracker.h"
00017 #include "llvm/ADT/SmallPtrSet.h"
00018 #include "llvm/Analysis/InstructionSimplify.h"
00019 #include "llvm/Analysis/MemoryBuiltins.h"
00020 #include "llvm/IR/CallSite.h"
00021 #include "llvm/IR/ConstantRange.h"
00022 #include "llvm/IR/Constants.h"
00023 #include "llvm/IR/DataLayout.h"
00024 #include "llvm/IR/Dominators.h"
00025 #include "llvm/IR/GetElementPtrTypeIterator.h"
00026 #include "llvm/IR/GlobalAlias.h"
00027 #include "llvm/IR/GlobalVariable.h"
00028 #include "llvm/IR/Instructions.h"
00029 #include "llvm/IR/IntrinsicInst.h"
00030 #include "llvm/IR/LLVMContext.h"
00031 #include "llvm/IR/Metadata.h"
00032 #include "llvm/IR/Operator.h"
00033 #include "llvm/IR/PatternMatch.h"
00034 #include "llvm/Support/Debug.h"
00035 #include "llvm/Support/MathExtras.h"
00036 #include <cstring>
00037 using namespace llvm;
00038 using namespace llvm::PatternMatch;
00039 
00040 const unsigned MaxDepth = 6;
00041 
00042 /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
00043 /// 0). For vector types, returns the element type's bitwidth.
00044 static unsigned getBitWidth(Type *Ty, const DataLayout *TD) {
00045   if (unsigned BitWidth = Ty->getScalarSizeInBits())
00046     return BitWidth;
00047 
00048   return TD ? TD->getPointerTypeSizeInBits(Ty) : 0;
00049 }
00050 
00051 // Many of these functions have internal versions that take an assumption
00052 // exclusion set. This is because of the potential for mutual recursion to
00053 // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
00054 // classic case of this is assume(x = y), which will attempt to determine
00055 // bits in x from bits in y, which will attempt to determine bits in y from
00056 // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
00057 // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
00058 // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
00059 typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
00060 
00061 namespace {
00062 // Simplifying using an assume can only be done in a particular control-flow
00063 // context (the context instruction provides that context). If an assume and
00064 // the context instruction are not in the same block then the DT helps in
00065 // figuring out if we can use it.
00066 struct Query {
00067   ExclInvsSet ExclInvs;
00068   AssumptionTracker *AT;
00069   const Instruction *CxtI;
00070   const DominatorTree *DT;
00071 
00072   Query(AssumptionTracker *AT = nullptr, const Instruction *CxtI = nullptr,
00073         const DominatorTree *DT = nullptr)
00074     : AT(AT), CxtI(CxtI), DT(DT) {}
00075 
00076   Query(const Query &Q, const Value *NewExcl)
00077     : ExclInvs(Q.ExclInvs), AT(Q.AT), CxtI(Q.CxtI), DT(Q.DT) {
00078     ExclInvs.insert(NewExcl);
00079   }
00080 };
00081 } // end anonymous namespace
00082 
00083 // Given the provided Value and, potentially, a context instruction, return
00084 // the preferred context instruction (if any).
00085 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
00086   // If we've been provided with a context instruction, then use that (provided
00087   // it has been inserted).
00088   if (CxtI && CxtI->getParent())
00089     return CxtI;
00090 
00091   // If the value is really an already-inserted instruction, then use that.
00092   CxtI = dyn_cast<Instruction>(V);
00093   if (CxtI && CxtI->getParent())
00094     return CxtI;
00095 
00096   return nullptr;
00097 }
00098 
00099 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00100                             const DataLayout *TD, unsigned Depth,
00101                             const Query &Q);
00102 
00103 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00104                             const DataLayout *TD, unsigned Depth,
00105                             AssumptionTracker *AT, const Instruction *CxtI,
00106                             const DominatorTree *DT) {
00107   ::computeKnownBits(V, KnownZero, KnownOne, TD, Depth,
00108                      Query(AT, safeCxtI(V, CxtI), DT));
00109 }
00110 
00111 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
00112                           const DataLayout *TD, unsigned Depth,
00113                           const Query &Q);
00114 
00115 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
00116                           const DataLayout *TD, unsigned Depth,
00117                           AssumptionTracker *AT, const Instruction *CxtI,
00118                           const DominatorTree *DT) {
00119   ::ComputeSignBit(V, KnownZero, KnownOne, TD, Depth,
00120                    Query(AT, safeCxtI(V, CxtI), DT));
00121 }
00122 
00123 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
00124                                    const Query &Q);
00125 
00126 bool llvm::isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
00127                                   AssumptionTracker *AT,
00128                                   const Instruction *CxtI,
00129                                   const DominatorTree *DT) {
00130   return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
00131                                   Query(AT, safeCxtI(V, CxtI), DT));
00132 }
00133 
00134 static bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
00135                            const Query &Q);
00136 
00137 bool llvm::isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
00138                           AssumptionTracker *AT, const Instruction *CxtI,
00139                           const DominatorTree *DT) {
00140   return ::isKnownNonZero(V, TD, Depth, Query(AT, safeCxtI(V, CxtI), DT));
00141 }
00142 
00143 static bool MaskedValueIsZero(Value *V, const APInt &Mask,
00144                               const DataLayout *TD, unsigned Depth,
00145                               const Query &Q);
00146 
00147 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
00148                              const DataLayout *TD, unsigned Depth,
00149                              AssumptionTracker *AT, const Instruction *CxtI,
00150                              const DominatorTree *DT) {
00151   return ::MaskedValueIsZero(V, Mask, TD, Depth,
00152                              Query(AT, safeCxtI(V, CxtI), DT));
00153 }
00154 
00155 static unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
00156                                    unsigned Depth, const Query &Q);
00157 
00158 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout *TD,
00159                                   unsigned Depth, AssumptionTracker *AT,
00160                                   const Instruction *CxtI,
00161                                   const DominatorTree *DT) {
00162   return ::ComputeNumSignBits(V, TD, Depth, Query(AT, safeCxtI(V, CxtI), DT));
00163 }
00164 
00165 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
00166                                    APInt &KnownZero, APInt &KnownOne,
00167                                    APInt &KnownZero2, APInt &KnownOne2,
00168                                    const DataLayout *TD, unsigned Depth,
00169                                    const Query &Q) {
00170   if (!Add) {
00171     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
00172       // We know that the top bits of C-X are clear if X contains less bits
00173       // than C (i.e. no wrap-around can happen).  For example, 20-X is
00174       // positive if we can prove that X is >= 0 and < 16.
00175       if (!CLHS->getValue().isNegative()) {
00176         unsigned BitWidth = KnownZero.getBitWidth();
00177         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
00178         // NLZ can't be BitWidth with no sign bit
00179         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
00180         computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
00181 
00182         // If all of the MaskV bits are known to be zero, then we know the
00183         // output top bits are zero, because we now know that the output is
00184         // from [0-C].
00185         if ((KnownZero2 & MaskV) == MaskV) {
00186           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
00187           // Top bits known zero.
00188           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
00189         }
00190       }
00191     }
00192   }
00193 
00194   unsigned BitWidth = KnownZero.getBitWidth();
00195 
00196   // If an initial sequence of bits in the result is not needed, the
00197   // corresponding bits in the operands are not needed.
00198   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
00199   computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, TD, Depth+1, Q);
00200   computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
00201 
00202   // Carry in a 1 for a subtract, rather than a 0.
00203   APInt CarryIn(BitWidth, 0);
00204   if (!Add) {
00205     // Sum = LHS + ~RHS + 1
00206     std::swap(KnownZero2, KnownOne2);
00207     CarryIn.setBit(0);
00208   }
00209 
00210   APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
00211   APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
00212 
00213   // Compute known bits of the carry.
00214   APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
00215   APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
00216 
00217   // Compute set of known bits (where all three relevant bits are known).
00218   APInt LHSKnown = LHSKnownZero | LHSKnownOne;
00219   APInt RHSKnown = KnownZero2 | KnownOne2;
00220   APInt CarryKnown = CarryKnownZero | CarryKnownOne;
00221   APInt Known = LHSKnown & RHSKnown & CarryKnown;
00222 
00223   assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
00224          "known bits of sum differ");
00225 
00226   // Compute known bits of the result.
00227   KnownZero = ~PossibleSumOne & Known;
00228   KnownOne = PossibleSumOne & Known;
00229 
00230   // Are we still trying to solve for the sign bit?
00231   if (!Known.isNegative()) {
00232     if (NSW) {
00233       // Adding two non-negative numbers, or subtracting a negative number from
00234       // a non-negative one, can't wrap into negative.
00235       if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
00236         KnownZero |= APInt::getSignBit(BitWidth);
00237       // Adding two negative numbers, or subtracting a non-negative number from
00238       // a negative one, can't wrap into non-negative.
00239       else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
00240         KnownOne |= APInt::getSignBit(BitWidth);
00241     }
00242   }
00243 }
00244 
00245 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
00246                                 APInt &KnownZero, APInt &KnownOne,
00247                                 APInt &KnownZero2, APInt &KnownOne2,
00248                                 const DataLayout *TD, unsigned Depth,
00249                                 const Query &Q) {
00250   unsigned BitWidth = KnownZero.getBitWidth();
00251   computeKnownBits(Op1, KnownZero, KnownOne, TD, Depth+1, Q);
00252   computeKnownBits(Op0, KnownZero2, KnownOne2, TD, Depth+1, Q);
00253 
00254   bool isKnownNegative = false;
00255   bool isKnownNonNegative = false;
00256   // If the multiplication is known not to overflow, compute the sign bit.
00257   if (NSW) {
00258     if (Op0 == Op1) {
00259       // The product of a number with itself is non-negative.
00260       isKnownNonNegative = true;
00261     } else {
00262       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
00263       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
00264       bool isKnownNegativeOp1 = KnownOne.isNegative();
00265       bool isKnownNegativeOp0 = KnownOne2.isNegative();
00266       // The product of two numbers with the same sign is non-negative.
00267       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
00268         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
00269       // The product of a negative number and a non-negative number is either
00270       // negative or zero.
00271       if (!isKnownNonNegative)
00272         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
00273                            isKnownNonZero(Op0, TD, Depth, Q)) ||
00274                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
00275                            isKnownNonZero(Op1, TD, Depth, Q));
00276     }
00277   }
00278 
00279   // If low bits are zero in either operand, output low known-0 bits.
00280   // Also compute a conserative estimate for high known-0 bits.
00281   // More trickiness is possible, but this is sufficient for the
00282   // interesting case of alignment computation.
00283   KnownOne.clearAllBits();
00284   unsigned TrailZ = KnownZero.countTrailingOnes() +
00285                     KnownZero2.countTrailingOnes();
00286   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
00287                              KnownZero2.countLeadingOnes(),
00288                              BitWidth) - BitWidth;
00289 
00290   TrailZ = std::min(TrailZ, BitWidth);
00291   LeadZ = std::min(LeadZ, BitWidth);
00292   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
00293               APInt::getHighBitsSet(BitWidth, LeadZ);
00294 
00295   // Only make use of no-wrap flags if we failed to compute the sign bit
00296   // directly.  This matters if the multiplication always overflows, in
00297   // which case we prefer to follow the result of the direct computation,
00298   // though as the program is invoking undefined behaviour we can choose
00299   // whatever we like here.
00300   if (isKnownNonNegative && !KnownOne.isNegative())
00301     KnownZero.setBit(BitWidth - 1);
00302   else if (isKnownNegative && !KnownZero.isNegative())
00303     KnownOne.setBit(BitWidth - 1);
00304 }
00305 
00306 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
00307                                              APInt &KnownZero) {
00308   unsigned BitWidth = KnownZero.getBitWidth();
00309   unsigned NumRanges = Ranges.getNumOperands() / 2;
00310   assert(NumRanges >= 1);
00311 
00312   // Use the high end of the ranges to find leading zeros.
00313   unsigned MinLeadingZeros = BitWidth;
00314   for (unsigned i = 0; i < NumRanges; ++i) {
00315     ConstantInt *Lower =
00316         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
00317     ConstantInt *Upper =
00318         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
00319     ConstantRange Range(Lower->getValue(), Upper->getValue());
00320     if (Range.isWrappedSet())
00321       MinLeadingZeros = 0; // -1 has no zeros
00322     unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
00323     MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
00324   }
00325 
00326   KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
00327 }
00328 
00329 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
00330   SmallVector<const Value *, 16> WorkSet(1, I);
00331   SmallPtrSet<const Value *, 32> Visited;
00332   SmallPtrSet<const Value *, 16> EphValues;
00333 
00334   while (!WorkSet.empty()) {
00335     const Value *V = WorkSet.pop_back_val();
00336     if (!Visited.insert(V).second)
00337       continue;
00338 
00339     // If all uses of this value are ephemeral, then so is this value.
00340     bool FoundNEUse = false;
00341     for (const User *I : V->users())
00342       if (!EphValues.count(I)) {
00343         FoundNEUse = true;
00344         break;
00345       }
00346 
00347     if (!FoundNEUse) {
00348       if (V == E)
00349         return true;
00350 
00351       EphValues.insert(V);
00352       if (const User *U = dyn_cast<User>(V))
00353         for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
00354              J != JE; ++J) {
00355           if (isSafeToSpeculativelyExecute(*J))
00356             WorkSet.push_back(*J);
00357         }
00358     }
00359   }
00360 
00361   return false;
00362 }
00363 
00364 // Is this an intrinsic that cannot be speculated but also cannot trap?
00365 static bool isAssumeLikeIntrinsic(const Instruction *I) {
00366   if (const CallInst *CI = dyn_cast<CallInst>(I))
00367     if (Function *F = CI->getCalledFunction())
00368       switch (F->getIntrinsicID()) {
00369       default: break;
00370       // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
00371       case Intrinsic::assume:
00372       case Intrinsic::dbg_declare:
00373       case Intrinsic::dbg_value:
00374       case Intrinsic::invariant_start:
00375       case Intrinsic::invariant_end:
00376       case Intrinsic::lifetime_start:
00377       case Intrinsic::lifetime_end:
00378       case Intrinsic::objectsize:
00379       case Intrinsic::ptr_annotation:
00380       case Intrinsic::var_annotation:
00381         return true;
00382       }
00383 
00384   return false;
00385 }
00386 
00387 static bool isValidAssumeForContext(Value *V, const Query &Q,
00388                                     const DataLayout *DL) {
00389   Instruction *Inv = cast<Instruction>(V);
00390 
00391   // There are two restrictions on the use of an assume:
00392   //  1. The assume must dominate the context (or the control flow must
00393   //     reach the assume whenever it reaches the context).
00394   //  2. The context must not be in the assume's set of ephemeral values
00395   //     (otherwise we will use the assume to prove that the condition
00396   //     feeding the assume is trivially true, thus causing the removal of
00397   //     the assume).
00398 
00399   if (Q.DT) {
00400     if (Q.DT->dominates(Inv, Q.CxtI)) {
00401       return true;
00402     } else if (Inv->getParent() == Q.CxtI->getParent()) {
00403       // The context comes first, but they're both in the same block. Make sure
00404       // there is nothing in between that might interrupt the control flow.
00405       for (BasicBlock::const_iterator I =
00406              std::next(BasicBlock::const_iterator(Q.CxtI)),
00407                                       IE(Inv); I != IE; ++I)
00408         if (!isSafeToSpeculativelyExecute(I, DL) &&
00409             !isAssumeLikeIntrinsic(I))
00410           return false;
00411 
00412       return !isEphemeralValueOf(Inv, Q.CxtI);
00413     }
00414 
00415     return false;
00416   }
00417 
00418   // When we don't have a DT, we do a limited search...
00419   if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
00420     return true;
00421   } else if (Inv->getParent() == Q.CxtI->getParent()) {
00422     // Search forward from the assume until we reach the context (or the end
00423     // of the block); the common case is that the assume will come first.
00424     for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
00425          IE = Inv->getParent()->end(); I != IE; ++I)
00426       if (I == Q.CxtI)
00427         return true;
00428 
00429     // The context must come first...
00430     for (BasicBlock::const_iterator I =
00431            std::next(BasicBlock::const_iterator(Q.CxtI)),
00432                                     IE(Inv); I != IE; ++I)
00433       if (!isSafeToSpeculativelyExecute(I, DL) &&
00434           !isAssumeLikeIntrinsic(I))
00435         return false;
00436 
00437     return !isEphemeralValueOf(Inv, Q.CxtI);
00438   }
00439 
00440   return false;
00441 }
00442 
00443 bool llvm::isValidAssumeForContext(const Instruction *I,
00444                                    const Instruction *CxtI,
00445                                    const DataLayout *DL,
00446                                    const DominatorTree *DT) {
00447   return ::isValidAssumeForContext(const_cast<Instruction*>(I),
00448                                    Query(nullptr, CxtI, DT), DL);
00449 }
00450 
00451 template<typename LHS, typename RHS>
00452 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
00453                         CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
00454 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
00455   return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
00456 }
00457 
00458 template<typename LHS, typename RHS>
00459 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
00460                         BinaryOp_match<RHS, LHS, Instruction::And>>
00461 m_c_And(const LHS &L, const RHS &R) {
00462   return m_CombineOr(m_And(L, R), m_And(R, L));
00463 }
00464 
00465 template<typename LHS, typename RHS>
00466 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
00467                         BinaryOp_match<RHS, LHS, Instruction::Or>>
00468 m_c_Or(const LHS &L, const RHS &R) {
00469   return m_CombineOr(m_Or(L, R), m_Or(R, L));
00470 }
00471 
00472 template<typename LHS, typename RHS>
00473 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
00474                         BinaryOp_match<RHS, LHS, Instruction::Xor>>
00475 m_c_Xor(const LHS &L, const RHS &R) {
00476   return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
00477 }
00478 
00479 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
00480                                        APInt &KnownOne,
00481                                        const DataLayout *DL,
00482                                        unsigned Depth, const Query &Q) {
00483   // Use of assumptions is context-sensitive. If we don't have a context, we
00484   // cannot use them!
00485   if (!Q.AT || !Q.CxtI)
00486     return;
00487 
00488   unsigned BitWidth = KnownZero.getBitWidth();
00489 
00490   Function *F = const_cast<Function*>(Q.CxtI->getParent()->getParent());
00491   for (auto &CI : Q.AT->assumptions(F)) {
00492     CallInst *I = CI;
00493     if (Q.ExclInvs.count(I))
00494       continue;
00495 
00496     // Warning: This loop can end up being somewhat performance sensetive.
00497     // We're running this loop for once for each value queried resulting in a
00498     // runtime of ~O(#assumes * #values).
00499 
00500     assert(isa<IntrinsicInst>(I) &&
00501            dyn_cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::assume &&
00502            "must be an assume intrinsic");
00503     
00504     Value *Arg = I->getArgOperand(0);
00505 
00506     if (Arg == V &&
00507         isValidAssumeForContext(I, Q, DL)) {
00508       assert(BitWidth == 1 && "assume operand is not i1?");
00509       KnownZero.clearAllBits();
00510       KnownOne.setAllBits();
00511       return;
00512     }
00513 
00514     // The remaining tests are all recursive, so bail out if we hit the limit.
00515     if (Depth == MaxDepth)
00516       continue;
00517 
00518     Value *A, *B;
00519     auto m_V = m_CombineOr(m_Specific(V),
00520                            m_CombineOr(m_PtrToInt(m_Specific(V)),
00521                            m_BitCast(m_Specific(V))));
00522 
00523     CmpInst::Predicate Pred;
00524     ConstantInt *C;
00525     // assume(v = a)
00526     if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
00527         Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00528       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00529       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00530       KnownZero |= RHSKnownZero;
00531       KnownOne  |= RHSKnownOne;
00532     // assume(v & b = a)
00533     } else if (match(Arg, m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)),
00534                                    m_Value(A))) &&
00535                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00536       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00537       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00538       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
00539       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
00540 
00541       // For those bits in the mask that are known to be one, we can propagate
00542       // known bits from the RHS to V.
00543       KnownZero |= RHSKnownZero & MaskKnownOne;
00544       KnownOne  |= RHSKnownOne  & MaskKnownOne;
00545     // assume(~(v & b) = a)
00546     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
00547                                    m_Value(A))) &&
00548                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00549       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00550       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00551       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
00552       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
00553 
00554       // For those bits in the mask that are known to be one, we can propagate
00555       // inverted known bits from the RHS to V.
00556       KnownZero |= RHSKnownOne  & MaskKnownOne;
00557       KnownOne  |= RHSKnownZero & MaskKnownOne;
00558     // assume(v | b = a)
00559     } else if (match(Arg, m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)),
00560                                    m_Value(A))) &&
00561                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00562       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00563       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00564       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00565       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
00566 
00567       // For those bits in B that are known to be zero, we can propagate known
00568       // bits from the RHS to V.
00569       KnownZero |= RHSKnownZero & BKnownZero;
00570       KnownOne  |= RHSKnownOne  & BKnownZero;
00571     // assume(~(v | b) = a)
00572     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
00573                                    m_Value(A))) &&
00574                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00575       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00576       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00577       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00578       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
00579 
00580       // For those bits in B that are known to be zero, we can propagate
00581       // inverted known bits from the RHS to V.
00582       KnownZero |= RHSKnownOne  & BKnownZero;
00583       KnownOne  |= RHSKnownZero & BKnownZero;
00584     // assume(v ^ b = a)
00585     } else if (match(Arg, m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)),
00586                                    m_Value(A))) &&
00587                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00588       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00589       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00590       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00591       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
00592 
00593       // For those bits in B that are known to be zero, we can propagate known
00594       // bits from the RHS to V. For those bits in B that are known to be one,
00595       // we can propagate inverted known bits from the RHS to V.
00596       KnownZero |= RHSKnownZero & BKnownZero;
00597       KnownOne  |= RHSKnownOne  & BKnownZero;
00598       KnownZero |= RHSKnownOne  & BKnownOne;
00599       KnownOne  |= RHSKnownZero & BKnownOne;
00600     // assume(~(v ^ b) = a)
00601     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
00602                                    m_Value(A))) &&
00603                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00604       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00605       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00606       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00607       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
00608 
00609       // For those bits in B that are known to be zero, we can propagate
00610       // inverted known bits from the RHS to V. For those bits in B that are
00611       // known to be one, we can propagate known bits from the RHS to V.
00612       KnownZero |= RHSKnownOne  & BKnownZero;
00613       KnownOne  |= RHSKnownZero & BKnownZero;
00614       KnownZero |= RHSKnownZero & BKnownOne;
00615       KnownOne  |= RHSKnownOne  & BKnownOne;
00616     // assume(v << c = a)
00617     } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
00618                                    m_Value(A))) &&
00619                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00620       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00621       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00622       // For those bits in RHS that are known, we can propagate them to known
00623       // bits in V shifted to the right by C.
00624       KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
00625       KnownOne  |= RHSKnownOne.lshr(C->getZExtValue());
00626     // assume(~(v << c) = a)
00627     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
00628                                    m_Value(A))) &&
00629                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00630       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00631       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00632       // For those bits in RHS that are known, we can propagate them inverted
00633       // to known bits in V shifted to the right by C.
00634       KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
00635       KnownOne  |= RHSKnownZero.lshr(C->getZExtValue());
00636     // assume(v >> c = a)
00637     } else if (match(Arg,
00638                      m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
00639                                                   m_AShr(m_V,
00640                                                          m_ConstantInt(C))),
00641                                      m_Value(A))) &&
00642                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00643       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00644       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00645       // For those bits in RHS that are known, we can propagate them to known
00646       // bits in V shifted to the right by C.
00647       KnownZero |= RHSKnownZero << C->getZExtValue();
00648       KnownOne  |= RHSKnownOne  << C->getZExtValue();
00649     // assume(~(v >> c) = a)
00650     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
00651                                               m_LShr(m_V, m_ConstantInt(C)),
00652                                               m_AShr(m_V, m_ConstantInt(C)))),
00653                                    m_Value(A))) &&
00654                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00655       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00656       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00657       // For those bits in RHS that are known, we can propagate them inverted
00658       // to known bits in V shifted to the right by C.
00659       KnownZero |= RHSKnownOne  << C->getZExtValue();
00660       KnownOne  |= RHSKnownZero << C->getZExtValue();
00661     // assume(v >=_s c) where c is non-negative
00662     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00663                Pred == ICmpInst::ICMP_SGE &&
00664                isValidAssumeForContext(I, Q, DL)) {
00665       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00666       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00667 
00668       if (RHSKnownZero.isNegative()) {
00669         // We know that the sign bit is zero.
00670         KnownZero |= APInt::getSignBit(BitWidth);
00671       }
00672     // assume(v >_s c) where c is at least -1.
00673     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00674                Pred == ICmpInst::ICMP_SGT &&
00675                isValidAssumeForContext(I, Q, DL)) {
00676       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00677       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00678 
00679       if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
00680         // We know that the sign bit is zero.
00681         KnownZero |= APInt::getSignBit(BitWidth);
00682       }
00683     // assume(v <=_s c) where c is negative
00684     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00685                Pred == ICmpInst::ICMP_SLE &&
00686                isValidAssumeForContext(I, Q, DL)) {
00687       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00688       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00689 
00690       if (RHSKnownOne.isNegative()) {
00691         // We know that the sign bit is one.
00692         KnownOne |= APInt::getSignBit(BitWidth);
00693       }
00694     // assume(v <_s c) where c is non-positive
00695     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00696                Pred == ICmpInst::ICMP_SLT &&
00697                isValidAssumeForContext(I, Q, DL)) {
00698       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00699       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00700 
00701       if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
00702         // We know that the sign bit is one.
00703         KnownOne |= APInt::getSignBit(BitWidth);
00704       }
00705     // assume(v <=_u c)
00706     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00707                Pred == ICmpInst::ICMP_ULE &&
00708                isValidAssumeForContext(I, Q, DL)) {
00709       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00710       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00711 
00712       // Whatever high bits in c are zero are known to be zero.
00713       KnownZero |=
00714         APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
00715     // assume(v <_u c)
00716     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00717                Pred == ICmpInst::ICMP_ULT &&
00718                isValidAssumeForContext(I, Q, DL)) {
00719       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00720       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00721 
00722       // Whatever high bits in c are zero are known to be zero (if c is a power
00723       // of 2, then one more).
00724       if (isKnownToBeAPowerOfTwo(A, false, Depth+1, Query(Q, I)))
00725         KnownZero |=
00726           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
00727       else
00728         KnownZero |=
00729           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
00730     }
00731   }
00732 }
00733 
00734 /// Determine which bits of V are known to be either zero or one and return
00735 /// them in the KnownZero/KnownOne bit sets.
00736 ///
00737 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
00738 /// we cannot optimize based on the assumption that it is zero without changing
00739 /// it to be an explicit zero.  If we don't change it to zero, other code could
00740 /// optimized based on the contradictory assumption that it is non-zero.
00741 /// Because instcombine aggressively folds operations with undef args anyway,
00742 /// this won't lose us code quality.
00743 ///
00744 /// This function is defined on values with integer type, values with pointer
00745 /// type (but only if TD is non-null), and vectors of integers.  In the case
00746 /// where V is a vector, known zero, and known one values are the
00747 /// same width as the vector element, and the bit is set only if it is true
00748 /// for all of the elements in the vector.
00749 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00750                       const DataLayout *TD, unsigned Depth,
00751                       const Query &Q) {
00752   assert(V && "No Value?");
00753   assert(Depth <= MaxDepth && "Limit Search Depth");
00754   unsigned BitWidth = KnownZero.getBitWidth();
00755 
00756   assert((V->getType()->isIntOrIntVectorTy() ||
00757           V->getType()->getScalarType()->isPointerTy()) &&
00758          "Not integer or pointer type!");
00759   assert((!TD ||
00760           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
00761          (!V->getType()->isIntOrIntVectorTy() ||
00762           V->getType()->getScalarSizeInBits() == BitWidth) &&
00763          KnownZero.getBitWidth() == BitWidth &&
00764          KnownOne.getBitWidth() == BitWidth &&
00765          "V, KnownOne and KnownZero should have same BitWidth");
00766 
00767   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00768     // We know all of the bits for a constant!
00769     KnownOne = CI->getValue();
00770     KnownZero = ~KnownOne;
00771     return;
00772   }
00773   // Null and aggregate-zero are all-zeros.
00774   if (isa<ConstantPointerNull>(V) ||
00775       isa<ConstantAggregateZero>(V)) {
00776     KnownOne.clearAllBits();
00777     KnownZero = APInt::getAllOnesValue(BitWidth);
00778     return;
00779   }
00780   // Handle a constant vector by taking the intersection of the known bits of
00781   // each element.  There is no real need to handle ConstantVector here, because
00782   // we don't handle undef in any particularly useful way.
00783   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
00784     // We know that CDS must be a vector of integers. Take the intersection of
00785     // each element.
00786     KnownZero.setAllBits(); KnownOne.setAllBits();
00787     APInt Elt(KnownZero.getBitWidth(), 0);
00788     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
00789       Elt = CDS->getElementAsInteger(i);
00790       KnownZero &= ~Elt;
00791       KnownOne &= Elt;
00792     }
00793     return;
00794   }
00795 
00796   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
00797   // the bits of its aliasee.
00798   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00799     if (GA->mayBeOverridden()) {
00800       KnownZero.clearAllBits(); KnownOne.clearAllBits();
00801     } else {
00802       computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth+1, Q);
00803     }
00804     return;
00805   }
00806 
00807   // The address of an aligned GlobalValue has trailing zeros.
00808   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
00809     unsigned Align = GV->getAlignment();
00810     if (Align == 0 && TD) {
00811       if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
00812         Type *ObjectType = GVar->getType()->getElementType();
00813         if (ObjectType->isSized()) {
00814           // If the object is defined in the current Module, we'll be giving
00815           // it the preferred alignment. Otherwise, we have to assume that it
00816           // may only have the minimum ABI alignment.
00817           if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
00818             Align = TD->getPreferredAlignment(GVar);
00819           else
00820             Align = TD->getABITypeAlignment(ObjectType);
00821         }
00822       }
00823     }
00824     if (Align > 0)
00825       KnownZero = APInt::getLowBitsSet(BitWidth,
00826                                        countTrailingZeros(Align));
00827     else
00828       KnownZero.clearAllBits();
00829     KnownOne.clearAllBits();
00830     return;
00831   }
00832 
00833   if (Argument *A = dyn_cast<Argument>(V)) {
00834     unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
00835 
00836     if (!Align && TD && A->hasStructRetAttr()) {
00837       // An sret parameter has at least the ABI alignment of the return type.
00838       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
00839       if (EltTy->isSized())
00840         Align = TD->getABITypeAlignment(EltTy);
00841     }
00842 
00843     if (Align)
00844       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
00845 
00846     // Don't give up yet... there might be an assumption that provides more
00847     // information...
00848     computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
00849     return;
00850   }
00851 
00852   // Start out not knowing anything.
00853   KnownZero.clearAllBits(); KnownOne.clearAllBits();
00854 
00855   if (Depth == MaxDepth)
00856     return;  // Limit search depth.
00857 
00858   // Check whether a nearby assume intrinsic can determine some known bits.
00859   computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
00860 
00861   Operator *I = dyn_cast<Operator>(V);
00862   if (!I) return;
00863 
00864   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
00865   switch (I->getOpcode()) {
00866   default: break;
00867   case Instruction::Load:
00868     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
00869       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
00870     break;
00871   case Instruction::And: {
00872     // If either the LHS or the RHS are Zero, the result is zero.
00873     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
00874     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00875 
00876     // Output known-1 bits are only known if set in both the LHS & RHS.
00877     KnownOne &= KnownOne2;
00878     // Output known-0 are known to be clear if zero in either the LHS | RHS.
00879     KnownZero |= KnownZero2;
00880     break;
00881   }
00882   case Instruction::Or: {
00883     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
00884     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00885 
00886     // Output known-0 bits are only known if clear in both the LHS & RHS.
00887     KnownZero &= KnownZero2;
00888     // Output known-1 are known to be set if set in either the LHS | RHS.
00889     KnownOne |= KnownOne2;
00890     break;
00891   }
00892   case Instruction::Xor: {
00893     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
00894     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00895 
00896     // Output known-0 bits are known if clear or set in both the LHS & RHS.
00897     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
00898     // Output known-1 are known to be set if set in only one of the LHS, RHS.
00899     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
00900     KnownZero = KnownZeroOut;
00901     break;
00902   }
00903   case Instruction::Mul: {
00904     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
00905     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW,
00906                          KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
00907                          Depth, Q);
00908     break;
00909   }
00910   case Instruction::UDiv: {
00911     // For the purposes of computing leading zeros we can conservatively
00912     // treat a udiv as a logical right shift by the power of 2 known to
00913     // be less than the denominator.
00914     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00915     unsigned LeadZ = KnownZero2.countLeadingOnes();
00916 
00917     KnownOne2.clearAllBits();
00918     KnownZero2.clearAllBits();
00919     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
00920     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
00921     if (RHSUnknownLeadingOnes != BitWidth)
00922       LeadZ = std::min(BitWidth,
00923                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
00924 
00925     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
00926     break;
00927   }
00928   case Instruction::Select:
00929     computeKnownBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1, Q);
00930     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
00931 
00932     // Only known if known in both the LHS and RHS.
00933     KnownOne &= KnownOne2;
00934     KnownZero &= KnownZero2;
00935     break;
00936   case Instruction::FPTrunc:
00937   case Instruction::FPExt:
00938   case Instruction::FPToUI:
00939   case Instruction::FPToSI:
00940   case Instruction::SIToFP:
00941   case Instruction::UIToFP:
00942     break; // Can't work with floating point.
00943   case Instruction::PtrToInt:
00944   case Instruction::IntToPtr:
00945   case Instruction::AddrSpaceCast: // Pointers could be different sizes.
00946     // We can't handle these if we don't know the pointer size.
00947     if (!TD) break;
00948     // FALL THROUGH and handle them the same as zext/trunc.
00949   case Instruction::ZExt:
00950   case Instruction::Trunc: {
00951     Type *SrcTy = I->getOperand(0)->getType();
00952 
00953     unsigned SrcBitWidth;
00954     // Note that we handle pointer operands here because of inttoptr/ptrtoint
00955     // which fall through here.
00956     if(TD) {
00957       SrcBitWidth = TD->getTypeSizeInBits(SrcTy->getScalarType());
00958     } else {
00959       SrcBitWidth = SrcTy->getScalarSizeInBits();
00960       if (!SrcBitWidth) break;
00961     }
00962 
00963     assert(SrcBitWidth && "SrcBitWidth can't be zero");
00964     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
00965     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
00966     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
00967     KnownZero = KnownZero.zextOrTrunc(BitWidth);
00968     KnownOne = KnownOne.zextOrTrunc(BitWidth);
00969     // Any top bits are known to be zero.
00970     if (BitWidth > SrcBitWidth)
00971       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00972     break;
00973   }
00974   case Instruction::BitCast: {
00975     Type *SrcTy = I->getOperand(0)->getType();
00976     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
00977         // TODO: For now, not handling conversions like:
00978         // (bitcast i64 %x to <2 x i32>)
00979         !I->getType()->isVectorTy()) {
00980       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
00981       break;
00982     }
00983     break;
00984   }
00985   case Instruction::SExt: {
00986     // Compute the bits in the result that are not present in the input.
00987     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
00988 
00989     KnownZero = KnownZero.trunc(SrcBitWidth);
00990     KnownOne = KnownOne.trunc(SrcBitWidth);
00991     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
00992     KnownZero = KnownZero.zext(BitWidth);
00993     KnownOne = KnownOne.zext(BitWidth);
00994 
00995     // If the sign bit of the input is known set or clear, then we know the
00996     // top bits of the result.
00997     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
00998       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00999     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
01000       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
01001     break;
01002   }
01003   case Instruction::Shl:
01004     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
01005     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01006       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
01007       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01008       KnownZero <<= ShiftAmt;
01009       KnownOne  <<= ShiftAmt;
01010       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
01011     }
01012     break;
01013   case Instruction::LShr:
01014     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
01015     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01016       // Compute the new bits that are at the top now.
01017       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
01018 
01019       // Unsigned shift right.
01020       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01021       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
01022       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
01023       // high bits known zero.
01024       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
01025     }
01026     break;
01027   case Instruction::AShr:
01028     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
01029     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01030       // Compute the new bits that are at the top now.
01031       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
01032 
01033       // Signed shift right.
01034       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01035       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
01036       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
01037 
01038       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
01039       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
01040         KnownZero |= HighBits;
01041       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
01042         KnownOne |= HighBits;
01043     }
01044     break;
01045   case Instruction::Sub: {
01046     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
01047     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
01048                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
01049                             Depth, Q);
01050     break;
01051   }
01052   case Instruction::Add: {
01053     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
01054     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
01055                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
01056                             Depth, Q);
01057     break;
01058   }
01059   case Instruction::SRem:
01060     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
01061       APInt RA = Rem->getValue().abs();
01062       if (RA.isPowerOf2()) {
01063         APInt LowBits = RA - 1;
01064         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD,
01065                          Depth+1, Q);
01066 
01067         // The low bits of the first operand are unchanged by the srem.
01068         KnownZero = KnownZero2 & LowBits;
01069         KnownOne = KnownOne2 & LowBits;
01070 
01071         // If the first operand is non-negative or has all low bits zero, then
01072         // the upper bits are all zero.
01073         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
01074           KnownZero |= ~LowBits;
01075 
01076         // If the first operand is negative and not all low bits are zero, then
01077         // the upper bits are all one.
01078         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
01079           KnownOne |= ~LowBits;
01080 
01081         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01082       }
01083     }
01084 
01085     // The sign bit is the LHS's sign bit, except when the result of the
01086     // remainder is zero.
01087     if (KnownZero.isNonNegative()) {
01088       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
01089       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, TD,
01090                        Depth+1, Q);
01091       // If it's known zero, our sign bit is also zero.
01092       if (LHSKnownZero.isNegative())
01093         KnownZero.setBit(BitWidth - 1);
01094     }
01095 
01096     break;
01097   case Instruction::URem: {
01098     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
01099       APInt RA = Rem->getValue();
01100       if (RA.isPowerOf2()) {
01101         APInt LowBits = (RA - 1);
01102         computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD,
01103                          Depth+1, Q);
01104         KnownZero |= ~LowBits;
01105         KnownOne &= LowBits;
01106         break;
01107       }
01108     }
01109 
01110     // Since the result is less than or equal to either operand, any leading
01111     // zero bits in either operand must also exist in the result.
01112     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01113     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
01114 
01115     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
01116                                 KnownZero2.countLeadingOnes());
01117     KnownOne.clearAllBits();
01118     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
01119     break;
01120   }
01121 
01122   case Instruction::Alloca: {
01123     AllocaInst *AI = cast<AllocaInst>(V);
01124     unsigned Align = AI->getAlignment();
01125     if (Align == 0 && TD)
01126       Align = TD->getABITypeAlignment(AI->getType()->getElementType());
01127 
01128     if (Align > 0)
01129       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
01130     break;
01131   }
01132   case Instruction::GetElementPtr: {
01133     // Analyze all of the subscripts of this getelementptr instruction
01134     // to determine if we can prove known low zero bits.
01135     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
01136     computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, TD,
01137                      Depth+1, Q);
01138     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
01139 
01140     gep_type_iterator GTI = gep_type_begin(I);
01141     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
01142       Value *Index = I->getOperand(i);
01143       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
01144         // Handle struct member offset arithmetic.
01145         if (!TD) {
01146           TrailZ = 0;
01147           break;
01148         }
01149 
01150         // Handle case when index is vector zeroinitializer
01151         Constant *CIndex = cast<Constant>(Index);
01152         if (CIndex->isZeroValue())
01153           continue;
01154 
01155         if (CIndex->getType()->isVectorTy())
01156           Index = CIndex->getSplatValue();
01157 
01158         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
01159         const StructLayout *SL = TD->getStructLayout(STy);
01160         uint64_t Offset = SL->getElementOffset(Idx);
01161         TrailZ = std::min<unsigned>(TrailZ,
01162                                     countTrailingZeros(Offset));
01163       } else {
01164         // Handle array index arithmetic.
01165         Type *IndexedTy = GTI.getIndexedType();
01166         if (!IndexedTy->isSized()) {
01167           TrailZ = 0;
01168           break;
01169         }
01170         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
01171         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
01172         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
01173         computeKnownBits(Index, LocalKnownZero, LocalKnownOne, TD, Depth+1, Q);
01174         TrailZ = std::min(TrailZ,
01175                           unsigned(countTrailingZeros(TypeSize) +
01176                                    LocalKnownZero.countTrailingOnes()));
01177       }
01178     }
01179 
01180     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
01181     break;
01182   }
01183   case Instruction::PHI: {
01184     PHINode *P = cast<PHINode>(I);
01185     // Handle the case of a simple two-predecessor recurrence PHI.
01186     // There's a lot more that could theoretically be done here, but
01187     // this is sufficient to catch some interesting cases.
01188     if (P->getNumIncomingValues() == 2) {
01189       for (unsigned i = 0; i != 2; ++i) {
01190         Value *L = P->getIncomingValue(i);
01191         Value *R = P->getIncomingValue(!i);
01192         Operator *LU = dyn_cast<Operator>(L);
01193         if (!LU)
01194           continue;
01195         unsigned Opcode = LU->getOpcode();
01196         // Check for operations that have the property that if
01197         // both their operands have low zero bits, the result
01198         // will have low zero bits.
01199         if (Opcode == Instruction::Add ||
01200             Opcode == Instruction::Sub ||
01201             Opcode == Instruction::And ||
01202             Opcode == Instruction::Or ||
01203             Opcode == Instruction::Mul) {
01204           Value *LL = LU->getOperand(0);
01205           Value *LR = LU->getOperand(1);
01206           // Find a recurrence.
01207           if (LL == I)
01208             L = LR;
01209           else if (LR == I)
01210             L = LL;
01211           else
01212             break;
01213           // Ok, we have a PHI of the form L op= R. Check for low
01214           // zero bits.
01215           computeKnownBits(R, KnownZero2, KnownOne2, TD, Depth+1, Q);
01216 
01217           // We need to take the minimum number of known bits
01218           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
01219           computeKnownBits(L, KnownZero3, KnownOne3, TD, Depth+1, Q);
01220 
01221           KnownZero = APInt::getLowBitsSet(BitWidth,
01222                                            std::min(KnownZero2.countTrailingOnes(),
01223                                                     KnownZero3.countTrailingOnes()));
01224           break;
01225         }
01226       }
01227     }
01228 
01229     // Unreachable blocks may have zero-operand PHI nodes.
01230     if (P->getNumIncomingValues() == 0)
01231       break;
01232 
01233     // Otherwise take the unions of the known bit sets of the operands,
01234     // taking conservative care to avoid excessive recursion.
01235     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
01236       // Skip if every incoming value references to ourself.
01237       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
01238         break;
01239 
01240       KnownZero = APInt::getAllOnesValue(BitWidth);
01241       KnownOne = APInt::getAllOnesValue(BitWidth);
01242       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
01243         // Skip direct self references.
01244         if (P->getIncomingValue(i) == P) continue;
01245 
01246         KnownZero2 = APInt(BitWidth, 0);
01247         KnownOne2 = APInt(BitWidth, 0);
01248         // Recurse, but cap the recursion to one level, because we don't
01249         // want to waste time spinning around in loops.
01250         computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, TD,
01251                          MaxDepth-1, Q);
01252         KnownZero &= KnownZero2;
01253         KnownOne &= KnownOne2;
01254         // If all bits have been ruled out, there's no need to check
01255         // more operands.
01256         if (!KnownZero && !KnownOne)
01257           break;
01258       }
01259     }
01260     break;
01261   }
01262   case Instruction::Call:
01263   case Instruction::Invoke:
01264     if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
01265       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
01266     // If a range metadata is attached to this IntrinsicInst, intersect the
01267     // explicit range specified by the metadata and the implicit range of
01268     // the intrinsic.
01269     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01270       switch (II->getIntrinsicID()) {
01271       default: break;
01272       case Intrinsic::ctlz:
01273       case Intrinsic::cttz: {
01274         unsigned LowBits = Log2_32(BitWidth)+1;
01275         // If this call is undefined for 0, the result will be less than 2^n.
01276         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
01277           LowBits -= 1;
01278         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
01279         break;
01280       }
01281       case Intrinsic::ctpop: {
01282         unsigned LowBits = Log2_32(BitWidth)+1;
01283         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
01284         break;
01285       }
01286       case Intrinsic::x86_sse42_crc32_64_64:
01287         KnownZero |= APInt::getHighBitsSet(64, 32);
01288         break;
01289       }
01290     }
01291     break;
01292   case Instruction::ExtractValue:
01293     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
01294       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
01295       if (EVI->getNumIndices() != 1) break;
01296       if (EVI->getIndices()[0] == 0) {
01297         switch (II->getIntrinsicID()) {
01298         default: break;
01299         case Intrinsic::uadd_with_overflow:
01300         case Intrinsic::sadd_with_overflow:
01301           computeKnownBitsAddSub(true, II->getArgOperand(0),
01302                                  II->getArgOperand(1), false, KnownZero,
01303                                  KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
01304           break;
01305         case Intrinsic::usub_with_overflow:
01306         case Intrinsic::ssub_with_overflow:
01307           computeKnownBitsAddSub(false, II->getArgOperand(0),
01308                                  II->getArgOperand(1), false, KnownZero,
01309                                  KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
01310           break;
01311         case Intrinsic::umul_with_overflow:
01312         case Intrinsic::smul_with_overflow:
01313           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1),
01314                               false, KnownZero, KnownOne,
01315                               KnownZero2, KnownOne2, TD, Depth, Q);
01316           break;
01317         }
01318       }
01319     }
01320   }
01321 
01322   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01323 }
01324 
01325 /// Determine whether the sign bit is known to be zero or one.
01326 /// Convenience wrapper around computeKnownBits.
01327 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
01328                     const DataLayout *TD, unsigned Depth,
01329                     const Query &Q) {
01330   unsigned BitWidth = getBitWidth(V->getType(), TD);
01331   if (!BitWidth) {
01332     KnownZero = false;
01333     KnownOne = false;
01334     return;
01335   }
01336   APInt ZeroBits(BitWidth, 0);
01337   APInt OneBits(BitWidth, 0);
01338   computeKnownBits(V, ZeroBits, OneBits, TD, Depth, Q);
01339   KnownOne = OneBits[BitWidth - 1];
01340   KnownZero = ZeroBits[BitWidth - 1];
01341 }
01342 
01343 /// Return true if the given value is known to have exactly one
01344 /// bit set when defined. For vectors return true if every element is known to
01345 /// be a power of two when defined. Supports values with integer or pointer
01346 /// types and vectors of integers.
01347 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
01348                             const Query &Q) {
01349   if (Constant *C = dyn_cast<Constant>(V)) {
01350     if (C->isNullValue())
01351       return OrZero;
01352     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
01353       return CI->getValue().isPowerOf2();
01354     // TODO: Handle vector constants.
01355   }
01356 
01357   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
01358   // it is shifted off the end then the result is undefined.
01359   if (match(V, m_Shl(m_One(), m_Value())))
01360     return true;
01361 
01362   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
01363   // bottom.  If it is shifted off the bottom then the result is undefined.
01364   if (match(V, m_LShr(m_SignBit(), m_Value())))
01365     return true;
01366 
01367   // The remaining tests are all recursive, so bail out if we hit the limit.
01368   if (Depth++ == MaxDepth)
01369     return false;
01370 
01371   Value *X = nullptr, *Y = nullptr;
01372   // A shift of a power of two is a power of two or zero.
01373   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
01374                  match(V, m_Shr(m_Value(X), m_Value()))))
01375     return isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q);
01376 
01377   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
01378     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
01379 
01380   if (SelectInst *SI = dyn_cast<SelectInst>(V))
01381     return
01382       isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
01383       isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
01384 
01385   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
01386     // A power of two and'd with anything is a power of two or zero.
01387     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q) ||
01388         isKnownToBeAPowerOfTwo(Y, /*OrZero*/true, Depth, Q))
01389       return true;
01390     // X & (-X) is always a power of two or zero.
01391     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
01392       return true;
01393     return false;
01394   }
01395 
01396   // Adding a power-of-two or zero to the same power-of-two or zero yields
01397   // either the original power-of-two, a larger power-of-two or zero.
01398   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
01399     OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
01400     if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
01401       if (match(X, m_And(m_Specific(Y), m_Value())) ||
01402           match(X, m_And(m_Value(), m_Specific(Y))))
01403         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
01404           return true;
01405       if (match(Y, m_And(m_Specific(X), m_Value())) ||
01406           match(Y, m_And(m_Value(), m_Specific(X))))
01407         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
01408           return true;
01409 
01410       unsigned BitWidth = V->getType()->getScalarSizeInBits();
01411       APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
01412       computeKnownBits(X, LHSZeroBits, LHSOneBits, nullptr, Depth, Q);
01413 
01414       APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
01415       computeKnownBits(Y, RHSZeroBits, RHSOneBits, nullptr, Depth, Q);
01416       // If i8 V is a power of two or zero:
01417       //  ZeroBits: 1 1 1 0 1 1 1 1
01418       // ~ZeroBits: 0 0 0 1 0 0 0 0
01419       if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
01420         // If OrZero isn't set, we cannot give back a zero result.
01421         // Make sure either the LHS or RHS has a bit set.
01422         if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
01423           return true;
01424     }
01425   }
01426 
01427   // An exact divide or right shift can only shift off zero bits, so the result
01428   // is a power of two only if the first operand is a power of two and not
01429   // copying a sign bit (sdiv int_min, 2).
01430   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
01431       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
01432     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
01433                                   Depth, Q);
01434   }
01435 
01436   return false;
01437 }
01438 
01439 /// \brief Test whether a GEP's result is known to be non-null.
01440 ///
01441 /// Uses properties inherent in a GEP to try to determine whether it is known
01442 /// to be non-null.
01443 ///
01444 /// Currently this routine does not support vector GEPs.
01445 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout *DL,
01446                               unsigned Depth, const Query &Q) {
01447   if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
01448     return false;
01449 
01450   // FIXME: Support vector-GEPs.
01451   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
01452 
01453   // If the base pointer is non-null, we cannot walk to a null address with an
01454   // inbounds GEP in address space zero.
01455   if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
01456     return true;
01457 
01458   // Past this, if we don't have DataLayout, we can't do much.
01459   if (!DL)
01460     return false;
01461 
01462   // Walk the GEP operands and see if any operand introduces a non-zero offset.
01463   // If so, then the GEP cannot produce a null pointer, as doing so would
01464   // inherently violate the inbounds contract within address space zero.
01465   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
01466        GTI != GTE; ++GTI) {
01467     // Struct types are easy -- they must always be indexed by a constant.
01468     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
01469       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
01470       unsigned ElementIdx = OpC->getZExtValue();
01471       const StructLayout *SL = DL->getStructLayout(STy);
01472       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
01473       if (ElementOffset > 0)
01474         return true;
01475       continue;
01476     }
01477 
01478     // If we have a zero-sized type, the index doesn't matter. Keep looping.
01479     if (DL->getTypeAllocSize(GTI.getIndexedType()) == 0)
01480       continue;
01481 
01482     // Fast path the constant operand case both for efficiency and so we don't
01483     // increment Depth when just zipping down an all-constant GEP.
01484     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
01485       if (!OpC->isZero())
01486         return true;
01487       continue;
01488     }
01489 
01490     // We post-increment Depth here because while isKnownNonZero increments it
01491     // as well, when we pop back up that increment won't persist. We don't want
01492     // to recurse 10k times just because we have 10k GEP operands. We don't
01493     // bail completely out because we want to handle constant GEPs regardless
01494     // of depth.
01495     if (Depth++ >= MaxDepth)
01496       continue;
01497 
01498     if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
01499       return true;
01500   }
01501 
01502   return false;
01503 }
01504 
01505 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
01506 /// ensure that the value it's attached to is never Value?  'RangeType' is
01507 /// is the type of the value described by the range.
01508 static bool rangeMetadataExcludesValue(MDNode* Ranges,
01509                                        const APInt& Value) {
01510   const unsigned NumRanges = Ranges->getNumOperands() / 2;
01511   assert(NumRanges >= 1);
01512   for (unsigned i = 0; i < NumRanges; ++i) {
01513     ConstantInt *Lower =
01514         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
01515     ConstantInt *Upper =
01516         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
01517     ConstantRange Range(Lower->getValue(), Upper->getValue());
01518     if (Range.contains(Value))
01519       return false;
01520   }
01521   return true;
01522 }
01523 
01524 /// Return true if the given value is known to be non-zero when defined.
01525 /// For vectors return true if every element is known to be non-zero when
01526 /// defined. Supports values with integer or pointer type and vectors of
01527 /// integers.
01528 bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
01529                     const Query &Q) {
01530   if (Constant *C = dyn_cast<Constant>(V)) {
01531     if (C->isNullValue())
01532       return false;
01533     if (isa<ConstantInt>(C))
01534       // Must be non-zero due to null test above.
01535       return true;
01536     // TODO: Handle vectors
01537     return false;
01538   }
01539 
01540   if (Instruction* I = dyn_cast<Instruction>(V)) {
01541     if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
01542       // If the possible ranges don't contain zero, then the value is
01543       // definitely non-zero.
01544       if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
01545         const APInt ZeroValue(Ty->getBitWidth(), 0);
01546         if (rangeMetadataExcludesValue(Ranges, ZeroValue))
01547           return true;
01548       }
01549     }
01550   }
01551 
01552   // The remaining tests are all recursive, so bail out if we hit the limit.
01553   if (Depth++ >= MaxDepth)
01554     return false;
01555 
01556   // Check for pointer simplifications.
01557   if (V->getType()->isPointerTy()) {
01558     if (isKnownNonNull(V))
01559       return true; 
01560     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
01561       if (isGEPKnownNonNull(GEP, TD, Depth, Q))
01562         return true;
01563   }
01564 
01565   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
01566 
01567   // X | Y != 0 if X != 0 or Y != 0.
01568   Value *X = nullptr, *Y = nullptr;
01569   if (match(V, m_Or(m_Value(X), m_Value(Y))))
01570     return isKnownNonZero(X, TD, Depth, Q) ||
01571            isKnownNonZero(Y, TD, Depth, Q);
01572 
01573   // ext X != 0 if X != 0.
01574   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
01575     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth, Q);
01576 
01577   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
01578   // if the lowest bit is shifted off the end.
01579   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
01580     // shl nuw can't remove any non-zero bits.
01581     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
01582     if (BO->hasNoUnsignedWrap())
01583       return isKnownNonZero(X, TD, Depth, Q);
01584 
01585     APInt KnownZero(BitWidth, 0);
01586     APInt KnownOne(BitWidth, 0);
01587     computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
01588     if (KnownOne[0])
01589       return true;
01590   }
01591   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
01592   // defined if the sign bit is shifted off the end.
01593   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
01594     // shr exact can only shift out zero bits.
01595     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
01596     if (BO->isExact())
01597       return isKnownNonZero(X, TD, Depth, Q);
01598 
01599     bool XKnownNonNegative, XKnownNegative;
01600     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
01601     if (XKnownNegative)
01602       return true;
01603   }
01604   // div exact can only produce a zero if the dividend is zero.
01605   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
01606     return isKnownNonZero(X, TD, Depth, Q);
01607   }
01608   // X + Y.
01609   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
01610     bool XKnownNonNegative, XKnownNegative;
01611     bool YKnownNonNegative, YKnownNegative;
01612     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
01613     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth, Q);
01614 
01615     // If X and Y are both non-negative (as signed values) then their sum is not
01616     // zero unless both X and Y are zero.
01617     if (XKnownNonNegative && YKnownNonNegative)
01618       if (isKnownNonZero(X, TD, Depth, Q) ||
01619           isKnownNonZero(Y, TD, Depth, Q))
01620         return true;
01621 
01622     // If X and Y are both negative (as signed values) then their sum is not
01623     // zero unless both X and Y equal INT_MIN.
01624     if (BitWidth && XKnownNegative && YKnownNegative) {
01625       APInt KnownZero(BitWidth, 0);
01626       APInt KnownOne(BitWidth, 0);
01627       APInt Mask = APInt::getSignedMaxValue(BitWidth);
01628       // The sign bit of X is set.  If some other bit is set then X is not equal
01629       // to INT_MIN.
01630       computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
01631       if ((KnownOne & Mask) != 0)
01632         return true;
01633       // The sign bit of Y is set.  If some other bit is set then Y is not equal
01634       // to INT_MIN.
01635       computeKnownBits(Y, KnownZero, KnownOne, TD, Depth, Q);
01636       if ((KnownOne & Mask) != 0)
01637         return true;
01638     }
01639 
01640     // The sum of a non-negative number and a power of two is not zero.
01641     if (XKnownNonNegative &&
01642         isKnownToBeAPowerOfTwo(Y, /*OrZero*/false, Depth, Q))
01643       return true;
01644     if (YKnownNonNegative &&
01645         isKnownToBeAPowerOfTwo(X, /*OrZero*/false, Depth, Q))
01646       return true;
01647   }
01648   // X * Y.
01649   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
01650     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
01651     // If X and Y are non-zero then so is X * Y as long as the multiplication
01652     // does not overflow.
01653     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
01654         isKnownNonZero(X, TD, Depth, Q) &&
01655         isKnownNonZero(Y, TD, Depth, Q))
01656       return true;
01657   }
01658   // (C ? X : Y) != 0 if X != 0 and Y != 0.
01659   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
01660     if (isKnownNonZero(SI->getTrueValue(), TD, Depth, Q) &&
01661         isKnownNonZero(SI->getFalseValue(), TD, Depth, Q))
01662       return true;
01663   }
01664 
01665   if (!BitWidth) return false;
01666   APInt KnownZero(BitWidth, 0);
01667   APInt KnownOne(BitWidth, 0);
01668   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
01669   return KnownOne != 0;
01670 }
01671 
01672 /// Return true if 'V & Mask' is known to be zero.  We use this predicate to
01673 /// simplify operations downstream. Mask is known to be zero for bits that V
01674 /// cannot have.
01675 ///
01676 /// This function is defined on values with integer type, values with pointer
01677 /// type (but only if TD is non-null), and vectors of integers.  In the case
01678 /// where V is a vector, the mask, known zero, and known one values are the
01679 /// same width as the vector element, and the bit is set only if it is true
01680 /// for all of the elements in the vector.
01681 bool MaskedValueIsZero(Value *V, const APInt &Mask,
01682                        const DataLayout *TD, unsigned Depth,
01683                        const Query &Q) {
01684   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
01685   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
01686   return (KnownZero & Mask) == Mask;
01687 }
01688 
01689 
01690 
01691 /// Return the number of times the sign bit of the register is replicated into
01692 /// the other bits. We know that at least 1 bit is always equal to the sign bit
01693 /// (itself), but other cases can give us information. For example, immediately
01694 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
01695 /// other, so we return 3.
01696 ///
01697 /// 'Op' must have a scalar integer type.
01698 ///
01699 unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
01700                             unsigned Depth, const Query &Q) {
01701   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
01702          "ComputeNumSignBits requires a DataLayout object to operate "
01703          "on non-integer values!");
01704   Type *Ty = V->getType();
01705   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
01706                          Ty->getScalarSizeInBits();
01707   unsigned Tmp, Tmp2;
01708   unsigned FirstAnswer = 1;
01709 
01710   // Note that ConstantInt is handled by the general computeKnownBits case
01711   // below.
01712 
01713   if (Depth == 6)
01714     return 1;  // Limit search depth.
01715 
01716   Operator *U = dyn_cast<Operator>(V);
01717   switch (Operator::getOpcode(V)) {
01718   default: break;
01719   case Instruction::SExt:
01720     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
01721     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q) + Tmp;
01722 
01723   case Instruction::AShr: {
01724     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01725     // ashr X, C   -> adds C sign bits.  Vectors too.
01726     const APInt *ShAmt;
01727     if (match(U->getOperand(1), m_APInt(ShAmt))) {
01728       Tmp += ShAmt->getZExtValue();
01729       if (Tmp > TyBits) Tmp = TyBits;
01730     }
01731     return Tmp;
01732   }
01733   case Instruction::Shl: {
01734     const APInt *ShAmt;
01735     if (match(U->getOperand(1), m_APInt(ShAmt))) {
01736       // shl destroys sign bits.
01737       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01738       Tmp2 = ShAmt->getZExtValue();
01739       if (Tmp2 >= TyBits ||      // Bad shift.
01740           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
01741       return Tmp - Tmp2;
01742     }
01743     break;
01744   }
01745   case Instruction::And:
01746   case Instruction::Or:
01747   case Instruction::Xor:    // NOT is handled here.
01748     // Logical binary ops preserve the number of sign bits at the worst.
01749     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01750     if (Tmp != 1) {
01751       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01752       FirstAnswer = std::min(Tmp, Tmp2);
01753       // We computed what we know about the sign bits as our first
01754       // answer. Now proceed to the generic code that uses
01755       // computeKnownBits, and pick whichever answer is better.
01756     }
01757     break;
01758 
01759   case Instruction::Select:
01760     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01761     if (Tmp == 1) return 1;  // Early out.
01762     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1, Q);
01763     return std::min(Tmp, Tmp2);
01764 
01765   case Instruction::Add:
01766     // Add can have at most one carry bit.  Thus we know that the output
01767     // is, at worst, one more bit than the inputs.
01768     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01769     if (Tmp == 1) return 1;  // Early out.
01770 
01771     // Special case decrementing a value (ADD X, -1):
01772     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
01773       if (CRHS->isAllOnesValue()) {
01774         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01775         computeKnownBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01776 
01777         // If the input is known to be 0 or 1, the output is 0/-1, which is all
01778         // sign bits set.
01779         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
01780           return TyBits;
01781 
01782         // If we are subtracting one from a positive number, there is no carry
01783         // out of the result.
01784         if (KnownZero.isNegative())
01785           return Tmp;
01786       }
01787 
01788     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01789     if (Tmp2 == 1) return 1;
01790     return std::min(Tmp, Tmp2)-1;
01791 
01792   case Instruction::Sub:
01793     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01794     if (Tmp2 == 1) return 1;
01795 
01796     // Handle NEG.
01797     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
01798       if (CLHS->isNullValue()) {
01799         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01800         computeKnownBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
01801         // If the input is known to be 0 or 1, the output is 0/-1, which is all
01802         // sign bits set.
01803         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
01804           return TyBits;
01805 
01806         // If the input is known to be positive (the sign bit is known clear),
01807         // the output of the NEG has the same number of sign bits as the input.
01808         if (KnownZero.isNegative())
01809           return Tmp2;
01810 
01811         // Otherwise, we treat this like a SUB.
01812       }
01813 
01814     // Sub can have at most one carry bit.  Thus we know that the output
01815     // is, at worst, one more bit than the inputs.
01816     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01817     if (Tmp == 1) return 1;  // Early out.
01818     return std::min(Tmp, Tmp2)-1;
01819 
01820   case Instruction::PHI: {
01821     PHINode *PN = cast<PHINode>(U);
01822     // Don't analyze large in-degree PHIs.
01823     if (PN->getNumIncomingValues() > 4) break;
01824 
01825     // Take the minimum of all incoming values.  This can't infinitely loop
01826     // because of our depth threshold.
01827     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1, Q);
01828     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
01829       if (Tmp == 1) return Tmp;
01830       Tmp = std::min(Tmp,
01831                      ComputeNumSignBits(PN->getIncomingValue(i), TD,
01832                                         Depth+1, Q));
01833     }
01834     return Tmp;
01835   }
01836 
01837   case Instruction::Trunc:
01838     // FIXME: it's tricky to do anything useful for this, but it is an important
01839     // case for targets like X86.
01840     break;
01841   }
01842 
01843   // Finally, if we can prove that the top bits of the result are 0's or 1's,
01844   // use this information.
01845   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01846   APInt Mask;
01847   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
01848 
01849   if (KnownZero.isNegative()) {        // sign bit is 0
01850     Mask = KnownZero;
01851   } else if (KnownOne.isNegative()) {  // sign bit is 1;
01852     Mask = KnownOne;
01853   } else {
01854     // Nothing known.
01855     return FirstAnswer;
01856   }
01857 
01858   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
01859   // the number of identical bits in the top of the input value.
01860   Mask = ~Mask;
01861   Mask <<= Mask.getBitWidth()-TyBits;
01862   // Return # leading zeros.  We use 'min' here in case Val was zero before
01863   // shifting.  We don't want to return '64' as for an i32 "0".
01864   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
01865 }
01866 
01867 /// This function computes the integer multiple of Base that equals V.
01868 /// If successful, it returns true and returns the multiple in
01869 /// Multiple. If unsuccessful, it returns false. It looks
01870 /// through SExt instructions only if LookThroughSExt is true.
01871 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
01872                            bool LookThroughSExt, unsigned Depth) {
01873   const unsigned MaxDepth = 6;
01874 
01875   assert(V && "No Value?");
01876   assert(Depth <= MaxDepth && "Limit Search Depth");
01877   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
01878 
01879   Type *T = V->getType();
01880 
01881   ConstantInt *CI = dyn_cast<ConstantInt>(V);
01882 
01883   if (Base == 0)
01884     return false;
01885 
01886   if (Base == 1) {
01887     Multiple = V;
01888     return true;
01889   }
01890 
01891   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
01892   Constant *BaseVal = ConstantInt::get(T, Base);
01893   if (CO && CO == BaseVal) {
01894     // Multiple is 1.
01895     Multiple = ConstantInt::get(T, 1);
01896     return true;
01897   }
01898 
01899   if (CI && CI->getZExtValue() % Base == 0) {
01900     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
01901     return true;
01902   }
01903 
01904   if (Depth == MaxDepth) return false;  // Limit search depth.
01905 
01906   Operator *I = dyn_cast<Operator>(V);
01907   if (!I) return false;
01908 
01909   switch (I->getOpcode()) {
01910   default: break;
01911   case Instruction::SExt:
01912     if (!LookThroughSExt) return false;
01913     // otherwise fall through to ZExt
01914   case Instruction::ZExt:
01915     return ComputeMultiple(I->getOperand(0), Base, Multiple,
01916                            LookThroughSExt, Depth+1);
01917   case Instruction::Shl:
01918   case Instruction::Mul: {
01919     Value *Op0 = I->getOperand(0);
01920     Value *Op1 = I->getOperand(1);
01921 
01922     if (I->getOpcode() == Instruction::Shl) {
01923       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
01924       if (!Op1CI) return false;
01925       // Turn Op0 << Op1 into Op0 * 2^Op1
01926       APInt Op1Int = Op1CI->getValue();
01927       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
01928       APInt API(Op1Int.getBitWidth(), 0);
01929       API.setBit(BitToSet);
01930       Op1 = ConstantInt::get(V->getContext(), API);
01931     }
01932 
01933     Value *Mul0 = nullptr;
01934     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
01935       if (Constant *Op1C = dyn_cast<Constant>(Op1))
01936         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
01937           if (Op1C->getType()->getPrimitiveSizeInBits() <
01938               MulC->getType()->getPrimitiveSizeInBits())
01939             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
01940           if (Op1C->getType()->getPrimitiveSizeInBits() >
01941               MulC->getType()->getPrimitiveSizeInBits())
01942             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
01943 
01944           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
01945           Multiple = ConstantExpr::getMul(MulC, Op1C);
01946           return true;
01947         }
01948 
01949       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
01950         if (Mul0CI->getValue() == 1) {
01951           // V == Base * Op1, so return Op1
01952           Multiple = Op1;
01953           return true;
01954         }
01955     }
01956 
01957     Value *Mul1 = nullptr;
01958     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
01959       if (Constant *Op0C = dyn_cast<Constant>(Op0))
01960         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
01961           if (Op0C->getType()->getPrimitiveSizeInBits() <
01962               MulC->getType()->getPrimitiveSizeInBits())
01963             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
01964           if (Op0C->getType()->getPrimitiveSizeInBits() >
01965               MulC->getType()->getPrimitiveSizeInBits())
01966             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
01967 
01968           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
01969           Multiple = ConstantExpr::getMul(MulC, Op0C);
01970           return true;
01971         }
01972 
01973       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
01974         if (Mul1CI->getValue() == 1) {
01975           // V == Base * Op0, so return Op0
01976           Multiple = Op0;
01977           return true;
01978         }
01979     }
01980   }
01981   }
01982 
01983   // We could not determine if V is a multiple of Base.
01984   return false;
01985 }
01986 
01987 /// Return true if we can prove that the specified FP value is never equal to
01988 /// -0.0.
01989 ///
01990 /// NOTE: this function will need to be revisited when we support non-default
01991 /// rounding modes!
01992 ///
01993 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
01994   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
01995     return !CFP->getValueAPF().isNegZero();
01996 
01997   if (Depth == 6)
01998     return 1;  // Limit search depth.
01999 
02000   const Operator *I = dyn_cast<Operator>(V);
02001   if (!I) return false;
02002 
02003   // Check if the nsz fast-math flag is set
02004   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
02005     if (FPO->hasNoSignedZeros())
02006       return true;
02007 
02008   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
02009   if (I->getOpcode() == Instruction::FAdd)
02010     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
02011       if (CFP->isNullValue())
02012         return true;
02013 
02014   // sitofp and uitofp turn into +0.0 for zero.
02015   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
02016     return true;
02017 
02018   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
02019     // sqrt(-0.0) = -0.0, no other negative results are possible.
02020     if (II->getIntrinsicID() == Intrinsic::sqrt)
02021       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
02022 
02023   if (const CallInst *CI = dyn_cast<CallInst>(I))
02024     if (const Function *F = CI->getCalledFunction()) {
02025       if (F->isDeclaration()) {
02026         // abs(x) != -0.0
02027         if (F->getName() == "abs") return true;
02028         // fabs[lf](x) != -0.0
02029         if (F->getName() == "fabs") return true;
02030         if (F->getName() == "fabsf") return true;
02031         if (F->getName() == "fabsl") return true;
02032         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
02033             F->getName() == "sqrtl")
02034           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
02035       }
02036     }
02037 
02038   return false;
02039 }
02040 
02041 /// If the specified value can be set by repeating the same byte in memory,
02042 /// return the i8 value that it is represented with.  This is
02043 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
02044 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
02045 /// byte store (e.g. i16 0x1234), return null.
02046 Value *llvm::isBytewiseValue(Value *V) {
02047   // All byte-wide stores are splatable, even of arbitrary variables.
02048   if (V->getType()->isIntegerTy(8)) return V;
02049 
02050   // Handle 'null' ConstantArrayZero etc.
02051   if (Constant *C = dyn_cast<Constant>(V))
02052     if (C->isNullValue())
02053       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
02054 
02055   // Constant float and double values can be handled as integer values if the
02056   // corresponding integer value is "byteable".  An important case is 0.0.
02057   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
02058     if (CFP->getType()->isFloatTy())
02059       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
02060     if (CFP->getType()->isDoubleTy())
02061       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
02062     // Don't handle long double formats, which have strange constraints.
02063   }
02064 
02065   // We can handle constant integers that are power of two in size and a
02066   // multiple of 8 bits.
02067   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
02068     unsigned Width = CI->getBitWidth();
02069     if (isPowerOf2_32(Width) && Width > 8) {
02070       // We can handle this value if the recursive binary decomposition is the
02071       // same at all levels.
02072       APInt Val = CI->getValue();
02073       APInt Val2;
02074       while (Val.getBitWidth() != 8) {
02075         unsigned NextWidth = Val.getBitWidth()/2;
02076         Val2  = Val.lshr(NextWidth);
02077         Val2 = Val2.trunc(Val.getBitWidth()/2);
02078         Val = Val.trunc(Val.getBitWidth()/2);
02079 
02080         // If the top/bottom halves aren't the same, reject it.
02081         if (Val != Val2)
02082           return nullptr;
02083       }
02084       return ConstantInt::get(V->getContext(), Val);
02085     }
02086   }
02087 
02088   // A ConstantDataArray/Vector is splatable if all its members are equal and
02089   // also splatable.
02090   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
02091     Value *Elt = CA->getElementAsConstant(0);
02092     Value *Val = isBytewiseValue(Elt);
02093     if (!Val)
02094       return nullptr;
02095 
02096     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
02097       if (CA->getElementAsConstant(I) != Elt)
02098         return nullptr;
02099 
02100     return Val;
02101   }
02102 
02103   // Conceptually, we could handle things like:
02104   //   %a = zext i8 %X to i16
02105   //   %b = shl i16 %a, 8
02106   //   %c = or i16 %a, %b
02107   // but until there is an example that actually needs this, it doesn't seem
02108   // worth worrying about.
02109   return nullptr;
02110 }
02111 
02112 
02113 // This is the recursive version of BuildSubAggregate. It takes a few different
02114 // arguments. Idxs is the index within the nested struct From that we are
02115 // looking at now (which is of type IndexedType). IdxSkip is the number of
02116 // indices from Idxs that should be left out when inserting into the resulting
02117 // struct. To is the result struct built so far, new insertvalue instructions
02118 // build on that.
02119 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
02120                                 SmallVectorImpl<unsigned> &Idxs,
02121                                 unsigned IdxSkip,
02122                                 Instruction *InsertBefore) {
02123   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
02124   if (STy) {
02125     // Save the original To argument so we can modify it
02126     Value *OrigTo = To;
02127     // General case, the type indexed by Idxs is a struct
02128     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
02129       // Process each struct element recursively
02130       Idxs.push_back(i);
02131       Value *PrevTo = To;
02132       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
02133                              InsertBefore);
02134       Idxs.pop_back();
02135       if (!To) {
02136         // Couldn't find any inserted value for this index? Cleanup
02137         while (PrevTo != OrigTo) {
02138           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
02139           PrevTo = Del->getAggregateOperand();
02140           Del->eraseFromParent();
02141         }
02142         // Stop processing elements
02143         break;
02144       }
02145     }
02146     // If we successfully found a value for each of our subaggregates
02147     if (To)
02148       return To;
02149   }
02150   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
02151   // the struct's elements had a value that was inserted directly. In the latter
02152   // case, perhaps we can't determine each of the subelements individually, but
02153   // we might be able to find the complete struct somewhere.
02154 
02155   // Find the value that is at that particular spot
02156   Value *V = FindInsertedValue(From, Idxs);
02157 
02158   if (!V)
02159     return nullptr;
02160 
02161   // Insert the value in the new (sub) aggregrate
02162   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
02163                                        "tmp", InsertBefore);
02164 }
02165 
02166 // This helper takes a nested struct and extracts a part of it (which is again a
02167 // struct) into a new value. For example, given the struct:
02168 // { a, { b, { c, d }, e } }
02169 // and the indices "1, 1" this returns
02170 // { c, d }.
02171 //
02172 // It does this by inserting an insertvalue for each element in the resulting
02173 // struct, as opposed to just inserting a single struct. This will only work if
02174 // each of the elements of the substruct are known (ie, inserted into From by an
02175 // insertvalue instruction somewhere).
02176 //
02177 // All inserted insertvalue instructions are inserted before InsertBefore
02178 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
02179                                 Instruction *InsertBefore) {
02180   assert(InsertBefore && "Must have someplace to insert!");
02181   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
02182                                                              idx_range);
02183   Value *To = UndefValue::get(IndexedType);
02184   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
02185   unsigned IdxSkip = Idxs.size();
02186 
02187   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
02188 }
02189 
02190 /// Given an aggregrate and an sequence of indices, see if
02191 /// the scalar value indexed is already around as a register, for example if it
02192 /// were inserted directly into the aggregrate.
02193 ///
02194 /// If InsertBefore is not null, this function will duplicate (modified)
02195 /// insertvalues when a part of a nested struct is extracted.
02196 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
02197                                Instruction *InsertBefore) {
02198   // Nothing to index? Just return V then (this is useful at the end of our
02199   // recursion).
02200   if (idx_range.empty())
02201     return V;
02202   // We have indices, so V should have an indexable type.
02203   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
02204          "Not looking at a struct or array?");
02205   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
02206          "Invalid indices for type?");
02207 
02208   if (Constant *C = dyn_cast<Constant>(V)) {
02209     C = C->getAggregateElement(idx_range[0]);
02210     if (!C) return nullptr;
02211     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
02212   }
02213 
02214   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
02215     // Loop the indices for the insertvalue instruction in parallel with the
02216     // requested indices
02217     const unsigned *req_idx = idx_range.begin();
02218     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
02219          i != e; ++i, ++req_idx) {
02220       if (req_idx == idx_range.end()) {
02221         // We can't handle this without inserting insertvalues
02222         if (!InsertBefore)
02223           return nullptr;
02224 
02225         // The requested index identifies a part of a nested aggregate. Handle
02226         // this specially. For example,
02227         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
02228         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
02229         // %C = extractvalue {i32, { i32, i32 } } %B, 1
02230         // This can be changed into
02231         // %A = insertvalue {i32, i32 } undef, i32 10, 0
02232         // %C = insertvalue {i32, i32 } %A, i32 11, 1
02233         // which allows the unused 0,0 element from the nested struct to be
02234         // removed.
02235         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
02236                                  InsertBefore);
02237       }
02238 
02239       // This insert value inserts something else than what we are looking for.
02240       // See if the (aggregrate) value inserted into has the value we are
02241       // looking for, then.
02242       if (*req_idx != *i)
02243         return FindInsertedValue(I->getAggregateOperand(), idx_range,
02244                                  InsertBefore);
02245     }
02246     // If we end up here, the indices of the insertvalue match with those
02247     // requested (though possibly only partially). Now we recursively look at
02248     // the inserted value, passing any remaining indices.
02249     return FindInsertedValue(I->getInsertedValueOperand(),
02250                              makeArrayRef(req_idx, idx_range.end()),
02251                              InsertBefore);
02252   }
02253 
02254   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
02255     // If we're extracting a value from an aggregrate that was extracted from
02256     // something else, we can extract from that something else directly instead.
02257     // However, we will need to chain I's indices with the requested indices.
02258 
02259     // Calculate the number of indices required
02260     unsigned size = I->getNumIndices() + idx_range.size();
02261     // Allocate some space to put the new indices in
02262     SmallVector<unsigned, 5> Idxs;
02263     Idxs.reserve(size);
02264     // Add indices from the extract value instruction
02265     Idxs.append(I->idx_begin(), I->idx_end());
02266 
02267     // Add requested indices
02268     Idxs.append(idx_range.begin(), idx_range.end());
02269 
02270     assert(Idxs.size() == size
02271            && "Number of indices added not correct?");
02272 
02273     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
02274   }
02275   // Otherwise, we don't know (such as, extracting from a function return value
02276   // or load instruction)
02277   return nullptr;
02278 }
02279 
02280 /// Analyze the specified pointer to see if it can be expressed as a base
02281 /// pointer plus a constant offset. Return the base and offset to the caller.
02282 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
02283                                               const DataLayout *DL) {
02284   // Without DataLayout, conservatively assume 64-bit offsets, which is
02285   // the widest we support.
02286   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(Ptr->getType()) : 64;
02287   APInt ByteOffset(BitWidth, 0);
02288   while (1) {
02289     if (Ptr->getType()->isVectorTy())
02290       break;
02291 
02292     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
02293       if (DL) {
02294         APInt GEPOffset(BitWidth, 0);
02295         if (!GEP->accumulateConstantOffset(*DL, GEPOffset))
02296           break;
02297 
02298         ByteOffset += GEPOffset;
02299       }
02300 
02301       Ptr = GEP->getPointerOperand();
02302     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
02303                Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
02304       Ptr = cast<Operator>(Ptr)->getOperand(0);
02305     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
02306       if (GA->mayBeOverridden())
02307         break;
02308       Ptr = GA->getAliasee();
02309     } else {
02310       break;
02311     }
02312   }
02313   Offset = ByteOffset.getSExtValue();
02314   return Ptr;
02315 }
02316 
02317 
02318 /// This function computes the length of a null-terminated C string pointed to
02319 /// by V. If successful, it returns true and returns the string in Str.
02320 /// If unsuccessful, it returns false.
02321 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
02322                                  uint64_t Offset, bool TrimAtNul) {
02323   assert(V);
02324 
02325   // Look through bitcast instructions and geps.
02326   V = V->stripPointerCasts();
02327 
02328   // If the value is a GEP instructionor  constant expression, treat it as an
02329   // offset.
02330   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
02331     // Make sure the GEP has exactly three arguments.
02332     if (GEP->getNumOperands() != 3)
02333       return false;
02334 
02335     // Make sure the index-ee is a pointer to array of i8.
02336     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
02337     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
02338     if (!AT || !AT->getElementType()->isIntegerTy(8))
02339       return false;
02340 
02341     // Check to make sure that the first operand of the GEP is an integer and
02342     // has value 0 so that we are sure we're indexing into the initializer.
02343     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
02344     if (!FirstIdx || !FirstIdx->isZero())
02345       return false;
02346 
02347     // If the second index isn't a ConstantInt, then this is a variable index
02348     // into the array.  If this occurs, we can't say anything meaningful about
02349     // the string.
02350     uint64_t StartIdx = 0;
02351     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
02352       StartIdx = CI->getZExtValue();
02353     else
02354       return false;
02355     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
02356   }
02357 
02358   // The GEP instruction, constant or instruction, must reference a global
02359   // variable that is a constant and is initialized. The referenced constant
02360   // initializer is the array that we'll use for optimization.
02361   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
02362   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
02363     return false;
02364 
02365   // Handle the all-zeros case
02366   if (GV->getInitializer()->isNullValue()) {
02367     // This is a degenerate case. The initializer is constant zero so the
02368     // length of the string must be zero.
02369     Str = "";
02370     return true;
02371   }
02372 
02373   // Must be a Constant Array
02374   const ConstantDataArray *Array =
02375     dyn_cast<ConstantDataArray>(GV->getInitializer());
02376   if (!Array || !Array->isString())
02377     return false;
02378 
02379   // Get the number of elements in the array
02380   uint64_t NumElts = Array->getType()->getArrayNumElements();
02381 
02382   // Start out with the entire array in the StringRef.
02383   Str = Array->getAsString();
02384 
02385   if (Offset > NumElts)
02386     return false;
02387 
02388   // Skip over 'offset' bytes.
02389   Str = Str.substr(Offset);
02390 
02391   if (TrimAtNul) {
02392     // Trim off the \0 and anything after it.  If the array is not nul
02393     // terminated, we just return the whole end of string.  The client may know
02394     // some other way that the string is length-bound.
02395     Str = Str.substr(0, Str.find('\0'));
02396   }
02397   return true;
02398 }
02399 
02400 // These next two are very similar to the above, but also look through PHI
02401 // nodes.
02402 // TODO: See if we can integrate these two together.
02403 
02404 /// If we can compute the length of the string pointed to by
02405 /// the specified pointer, return 'len+1'.  If we can't, return 0.
02406 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
02407   // Look through noop bitcast instructions.
02408   V = V->stripPointerCasts();
02409 
02410   // If this is a PHI node, there are two cases: either we have already seen it
02411   // or we haven't.
02412   if (PHINode *PN = dyn_cast<PHINode>(V)) {
02413     if (!PHIs.insert(PN).second)
02414       return ~0ULL;  // already in the set.
02415 
02416     // If it was new, see if all the input strings are the same length.
02417     uint64_t LenSoFar = ~0ULL;
02418     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
02419       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
02420       if (Len == 0) return 0; // Unknown length -> unknown.
02421 
02422       if (Len == ~0ULL) continue;
02423 
02424       if (Len != LenSoFar && LenSoFar != ~0ULL)
02425         return 0;    // Disagree -> unknown.
02426       LenSoFar = Len;
02427     }
02428 
02429     // Success, all agree.
02430     return LenSoFar;
02431   }
02432 
02433   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
02434   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
02435     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
02436     if (Len1 == 0) return 0;
02437     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
02438     if (Len2 == 0) return 0;
02439     if (Len1 == ~0ULL) return Len2;
02440     if (Len2 == ~0ULL) return Len1;
02441     if (Len1 != Len2) return 0;
02442     return Len1;
02443   }
02444 
02445   // Otherwise, see if we can read the string.
02446   StringRef StrData;
02447   if (!getConstantStringInfo(V, StrData))
02448     return 0;
02449 
02450   return StrData.size()+1;
02451 }
02452 
02453 /// If we can compute the length of the string pointed to by
02454 /// the specified pointer, return 'len+1'.  If we can't, return 0.
02455 uint64_t llvm::GetStringLength(Value *V) {
02456   if (!V->getType()->isPointerTy()) return 0;
02457 
02458   SmallPtrSet<PHINode*, 32> PHIs;
02459   uint64_t Len = GetStringLengthH(V, PHIs);
02460   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
02461   // an empty string as a length.
02462   return Len == ~0ULL ? 1 : Len;
02463 }
02464 
02465 Value *
02466 llvm::GetUnderlyingObject(Value *V, const DataLayout *TD, unsigned MaxLookup) {
02467   if (!V->getType()->isPointerTy())
02468     return V;
02469   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
02470     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
02471       V = GEP->getPointerOperand();
02472     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
02473                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
02474       V = cast<Operator>(V)->getOperand(0);
02475     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
02476       if (GA->mayBeOverridden())
02477         return V;
02478       V = GA->getAliasee();
02479     } else {
02480       // See if InstructionSimplify knows any relevant tricks.
02481       if (Instruction *I = dyn_cast<Instruction>(V))
02482         // TODO: Acquire a DominatorTree and AssumptionTracker and use them.
02483         if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
02484           V = Simplified;
02485           continue;
02486         }
02487 
02488       return V;
02489     }
02490     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
02491   }
02492   return V;
02493 }
02494 
02495 void
02496 llvm::GetUnderlyingObjects(Value *V,
02497                            SmallVectorImpl<Value *> &Objects,
02498                            const DataLayout *TD,
02499                            unsigned MaxLookup) {
02500   SmallPtrSet<Value *, 4> Visited;
02501   SmallVector<Value *, 4> Worklist;
02502   Worklist.push_back(V);
02503   do {
02504     Value *P = Worklist.pop_back_val();
02505     P = GetUnderlyingObject(P, TD, MaxLookup);
02506 
02507     if (!Visited.insert(P).second)
02508       continue;
02509 
02510     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
02511       Worklist.push_back(SI->getTrueValue());
02512       Worklist.push_back(SI->getFalseValue());
02513       continue;
02514     }
02515 
02516     if (PHINode *PN = dyn_cast<PHINode>(P)) {
02517       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
02518         Worklist.push_back(PN->getIncomingValue(i));
02519       continue;
02520     }
02521 
02522     Objects.push_back(P);
02523   } while (!Worklist.empty());
02524 }
02525 
02526 /// Return true if the only users of this pointer are lifetime markers.
02527 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
02528   for (const User *U : V->users()) {
02529     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
02530     if (!II) return false;
02531 
02532     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
02533         II->getIntrinsicID() != Intrinsic::lifetime_end)
02534       return false;
02535   }
02536   return true;
02537 }
02538 
02539 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
02540                                         const DataLayout *TD) {
02541   const Operator *Inst = dyn_cast<Operator>(V);
02542   if (!Inst)
02543     return false;
02544 
02545   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
02546     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
02547       if (C->canTrap())
02548         return false;
02549 
02550   switch (Inst->getOpcode()) {
02551   default:
02552     return true;
02553   case Instruction::UDiv:
02554   case Instruction::URem: {
02555     // x / y is undefined if y == 0.
02556     const APInt *V;
02557     if (match(Inst->getOperand(1), m_APInt(V)))
02558       return *V != 0;
02559     return false;
02560   }
02561   case Instruction::SDiv:
02562   case Instruction::SRem: {
02563     // x / y is undefined if y == 0 or x == INT_MIN and y == -1
02564     const APInt *X, *Y;
02565     if (match(Inst->getOperand(1), m_APInt(Y))) {
02566       if (*Y != 0) {
02567         if (*Y == -1) {
02568           // The numerator can't be MinSignedValue if the denominator is -1.
02569           if (match(Inst->getOperand(0), m_APInt(X)))
02570             return !Y->isMinSignedValue();
02571           // The numerator *might* be MinSignedValue.
02572           return false;
02573         }
02574         // The denominator is not 0 or -1, it's safe to proceed.
02575         return true;
02576       }
02577     }
02578     return false;
02579   }
02580   case Instruction::Load: {
02581     const LoadInst *LI = cast<LoadInst>(Inst);
02582     if (!LI->isUnordered() ||
02583         // Speculative load may create a race that did not exist in the source.
02584         LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
02585       return false;
02586     return LI->getPointerOperand()->isDereferenceablePointer(TD);
02587   }
02588   case Instruction::Call: {
02589     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
02590       switch (II->getIntrinsicID()) {
02591       // These synthetic intrinsics have no side-effects and just mark
02592       // information about their operands.
02593       // FIXME: There are other no-op synthetic instructions that potentially
02594       // should be considered at least *safe* to speculate...
02595       case Intrinsic::dbg_declare:
02596       case Intrinsic::dbg_value:
02597         return true;
02598 
02599       case Intrinsic::bswap:
02600       case Intrinsic::ctlz:
02601       case Intrinsic::ctpop:
02602       case Intrinsic::cttz:
02603       case Intrinsic::objectsize:
02604       case Intrinsic::sadd_with_overflow:
02605       case Intrinsic::smul_with_overflow:
02606       case Intrinsic::ssub_with_overflow:
02607       case Intrinsic::uadd_with_overflow:
02608       case Intrinsic::umul_with_overflow:
02609       case Intrinsic::usub_with_overflow:
02610         return true;
02611       // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
02612       // errno like libm sqrt would.
02613       case Intrinsic::sqrt:
02614       case Intrinsic::fma:
02615       case Intrinsic::fmuladd:
02616       case Intrinsic::fabs:
02617       case Intrinsic::minnum:
02618       case Intrinsic::maxnum:
02619         return true;
02620       // TODO: some fp intrinsics are marked as having the same error handling
02621       // as libm. They're safe to speculate when they won't error.
02622       // TODO: are convert_{from,to}_fp16 safe?
02623       // TODO: can we list target-specific intrinsics here?
02624       default: break;
02625       }
02626     }
02627     return false; // The called function could have undefined behavior or
02628                   // side-effects, even if marked readnone nounwind.
02629   }
02630   case Instruction::VAArg:
02631   case Instruction::Alloca:
02632   case Instruction::Invoke:
02633   case Instruction::PHI:
02634   case Instruction::Store:
02635   case Instruction::Ret:
02636   case Instruction::Br:
02637   case Instruction::IndirectBr:
02638   case Instruction::Switch:
02639   case Instruction::Unreachable:
02640   case Instruction::Fence:
02641   case Instruction::LandingPad:
02642   case Instruction::AtomicRMW:
02643   case Instruction::AtomicCmpXchg:
02644   case Instruction::Resume:
02645     return false; // Misc instructions which have effects
02646   }
02647 }
02648 
02649 /// Return true if we know that the specified value is never null.
02650 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
02651   // Alloca never returns null, malloc might.
02652   if (isa<AllocaInst>(V)) return true;
02653 
02654   // A byval, inalloca, or nonnull argument is never null.
02655   if (const Argument *A = dyn_cast<Argument>(V))
02656     return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
02657 
02658   // Global values are not null unless extern weak.
02659   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
02660     return !GV->hasExternalWeakLinkage();
02661 
02662   // A Load tagged w/nonnull metadata is never null. 
02663   if (const LoadInst *LI = dyn_cast<LoadInst>(V))
02664     return LI->getMetadata(LLVMContext::MD_nonnull);
02665 
02666   if (ImmutableCallSite CS = V)
02667     if (CS.isReturnNonNull())
02668       return true;
02669 
02670   // operator new never returns null.
02671   if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
02672     return true;
02673 
02674   return false;
02675 }