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 /// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
00043 /// unknown returns 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, returned
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 = cast<ConstantInt>(Ranges.getOperand(2*i + 0));
00316     ConstantInt *Upper = cast<ConstantInt>(Ranges.getOperand(2*i + 1));
00317     ConstantRange Range(Lower->getValue(), Upper->getValue());
00318     if (Range.isWrappedSet())
00319       MinLeadingZeros = 0; // -1 has no zeros
00320     unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
00321     MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
00322   }
00323 
00324   KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
00325 }
00326 
00327 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
00328   SmallVector<const Value *, 16> WorkSet(1, I);
00329   SmallPtrSet<const Value *, 32> Visited;
00330   SmallPtrSet<const Value *, 16> EphValues;
00331 
00332   while (!WorkSet.empty()) {
00333     const Value *V = WorkSet.pop_back_val();
00334     if (!Visited.insert(V))
00335       continue;
00336 
00337     // If all uses of this value are ephemeral, then so is this value.
00338     bool FoundNEUse = false;
00339     for (const User *I : V->users())
00340       if (!EphValues.count(I)) {
00341         FoundNEUse = true;
00342         break;
00343       }
00344 
00345     if (!FoundNEUse) {
00346       if (V == E)
00347         return true;
00348 
00349       EphValues.insert(V);
00350       if (const User *U = dyn_cast<User>(V))
00351         for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
00352              J != JE; ++J) {
00353           if (isSafeToSpeculativelyExecute(*J))
00354             WorkSet.push_back(*J);
00355         }
00356     }
00357   }
00358 
00359   return false;
00360 }
00361 
00362 // Is this an intrinsic that cannot be speculated but also cannot trap?
00363 static bool isAssumeLikeIntrinsic(const Instruction *I) {
00364   if (const CallInst *CI = dyn_cast<CallInst>(I))
00365     if (Function *F = CI->getCalledFunction())
00366       switch (F->getIntrinsicID()) {
00367       default: break;
00368       // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
00369       case Intrinsic::assume:
00370       case Intrinsic::dbg_declare:
00371       case Intrinsic::dbg_value:
00372       case Intrinsic::invariant_start:
00373       case Intrinsic::invariant_end:
00374       case Intrinsic::lifetime_start:
00375       case Intrinsic::lifetime_end:
00376       case Intrinsic::objectsize:
00377       case Intrinsic::ptr_annotation:
00378       case Intrinsic::var_annotation:
00379         return true;
00380       }
00381 
00382   return false;
00383 }
00384 
00385 static bool isValidAssumeForContext(Value *V, const Query &Q,
00386                                     const DataLayout *DL) {
00387   Instruction *Inv = cast<Instruction>(V);
00388 
00389   // There are two restrictions on the use of an assume:
00390   //  1. The assume must dominate the context (or the control flow must
00391   //     reach the assume whenever it reaches the context).
00392   //  2. The context must not be in the assume's set of ephemeral values
00393   //     (otherwise we will use the assume to prove that the condition
00394   //     feeding the assume is trivially true, thus causing the removal of
00395   //     the assume).
00396 
00397   if (Q.DT) {
00398     if (Q.DT->dominates(Inv, Q.CxtI)) {
00399       return true;
00400     } else if (Inv->getParent() == Q.CxtI->getParent()) {
00401       // The context comes first, but they're both in the same block. Make sure
00402       // there is nothing in between that might interrupt the control flow.
00403       for (BasicBlock::const_iterator I =
00404              std::next(BasicBlock::const_iterator(Q.CxtI)),
00405                                       IE(Inv); I != IE; ++I)
00406         if (!isSafeToSpeculativelyExecute(I, DL) &&
00407             !isAssumeLikeIntrinsic(I))
00408           return false;
00409 
00410       return !isEphemeralValueOf(Inv, Q.CxtI);
00411     }
00412 
00413     return false;
00414   }
00415 
00416   // When we don't have a DT, we do a limited search...
00417   if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
00418     return true;
00419   } else if (Inv->getParent() == Q.CxtI->getParent()) {
00420     // Search forward from the assume until we reach the context (or the end
00421     // of the block); the common case is that the assume will come first.
00422     for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
00423          IE = Inv->getParent()->end(); I != IE; ++I)
00424       if (I == Q.CxtI)
00425         return true;
00426 
00427     // The context must come first...
00428     for (BasicBlock::const_iterator I =
00429            std::next(BasicBlock::const_iterator(Q.CxtI)),
00430                                     IE(Inv); I != IE; ++I)
00431       if (!isSafeToSpeculativelyExecute(I, DL) &&
00432           !isAssumeLikeIntrinsic(I))
00433         return false;
00434 
00435     return !isEphemeralValueOf(Inv, Q.CxtI);
00436   }
00437 
00438   return false;
00439 }
00440 
00441 bool llvm::isValidAssumeForContext(const Instruction *I,
00442                                    const Instruction *CxtI,
00443                                    const DataLayout *DL,
00444                                    const DominatorTree *DT) {
00445   return ::isValidAssumeForContext(const_cast<Instruction*>(I),
00446                                    Query(nullptr, CxtI, DT), DL);
00447 }
00448 
00449 template<typename LHS, typename RHS>
00450 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
00451                         CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
00452 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
00453   return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
00454 }
00455 
00456 template<typename LHS, typename RHS>
00457 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
00458                         BinaryOp_match<RHS, LHS, Instruction::And>>
00459 m_c_And(const LHS &L, const RHS &R) {
00460   return m_CombineOr(m_And(L, R), m_And(R, L));
00461 }
00462 
00463 template<typename LHS, typename RHS>
00464 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
00465                         BinaryOp_match<RHS, LHS, Instruction::Or>>
00466 m_c_Or(const LHS &L, const RHS &R) {
00467   return m_CombineOr(m_Or(L, R), m_Or(R, L));
00468 }
00469 
00470 template<typename LHS, typename RHS>
00471 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
00472                         BinaryOp_match<RHS, LHS, Instruction::Xor>>
00473 m_c_Xor(const LHS &L, const RHS &R) {
00474   return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
00475 }
00476 
00477 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
00478                                        APInt &KnownOne,
00479                                        const DataLayout *DL,
00480                                        unsigned Depth, const Query &Q) {
00481   // Use of assumptions is context-sensitive. If we don't have a context, we
00482   // cannot use them!
00483   if (!Q.AT || !Q.CxtI)
00484     return;
00485 
00486   unsigned BitWidth = KnownZero.getBitWidth();
00487 
00488   Function *F = const_cast<Function*>(Q.CxtI->getParent()->getParent());
00489   for (auto &CI : Q.AT->assumptions(F)) {
00490     CallInst *I = CI;
00491     if (Q.ExclInvs.count(I))
00492       continue;
00493 
00494     if (match(I, m_Intrinsic<Intrinsic::assume>(m_Specific(V))) &&
00495         isValidAssumeForContext(I, Q, DL)) {
00496       assert(BitWidth == 1 && "assume operand is not i1?");
00497       KnownZero.clearAllBits();
00498       KnownOne.setAllBits();
00499       return;
00500     }
00501 
00502     Value *A, *B;
00503     auto m_V = m_CombineOr(m_Specific(V),
00504                            m_CombineOr(m_PtrToInt(m_Specific(V)),
00505                            m_BitCast(m_Specific(V))));
00506 
00507     CmpInst::Predicate Pred;
00508     ConstantInt *C;
00509     // assume(v = a)
00510     if (match(I, m_Intrinsic<Intrinsic::assume>(
00511                    m_c_ICmp(Pred, m_V, m_Value(A)))) &&
00512         Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00513       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00514       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00515       KnownZero |= RHSKnownZero;
00516       KnownOne  |= RHSKnownOne;
00517     // assume(v & b = a)
00518     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00519                        m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A)))) &&
00520                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00521       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00522       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00523       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
00524       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
00525 
00526       // For those bits in the mask that are known to be one, we can propagate
00527       // known bits from the RHS to V.
00528       KnownZero |= RHSKnownZero & MaskKnownOne;
00529       KnownOne  |= RHSKnownOne  & MaskKnownOne;
00530     // assume(~(v & b) = a)
00531     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00532                        m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
00533                                 m_Value(A)))) &&
00534                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00535       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00536       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00537       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
00538       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
00539 
00540       // For those bits in the mask that are known to be one, we can propagate
00541       // inverted known bits from the RHS to V.
00542       KnownZero |= RHSKnownOne  & MaskKnownOne;
00543       KnownOne  |= RHSKnownZero & MaskKnownOne;
00544     // assume(v | b = a)
00545     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00546                        m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A)))) &&
00547                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00548       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00549       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00550       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00551       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
00552 
00553       // For those bits in B that are known to be zero, we can propagate known
00554       // bits from the RHS to V.
00555       KnownZero |= RHSKnownZero & BKnownZero;
00556       KnownOne  |= RHSKnownOne  & BKnownZero;
00557     // assume(~(v | b) = a)
00558     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00559                        m_c_ICmp(Pred, m_Not(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
00568       // inverted known bits from the RHS to V.
00569       KnownZero |= RHSKnownOne  & BKnownZero;
00570       KnownOne  |= RHSKnownZero & BKnownZero;
00571     // assume(v ^ b = a)
00572     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00573                        m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), 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 known
00581       // bits from the RHS to V. For those bits in B that are known to be one,
00582       // we can propagate inverted known bits from the RHS to V.
00583       KnownZero |= RHSKnownZero & BKnownZero;
00584       KnownOne  |= RHSKnownOne  & BKnownZero;
00585       KnownZero |= RHSKnownOne  & BKnownOne;
00586       KnownOne  |= RHSKnownZero & BKnownOne;
00587     // assume(~(v ^ b) = a)
00588     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00589                        m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
00590                                 m_Value(A)))) &&
00591                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00592       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00593       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00594       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00595       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
00596 
00597       // For those bits in B that are known to be zero, we can propagate
00598       // inverted known bits from the RHS to V. For those bits in B that are
00599       // known to be one, we can propagate known bits from the RHS to V.
00600       KnownZero |= RHSKnownOne  & BKnownZero;
00601       KnownOne  |= RHSKnownZero & BKnownZero;
00602       KnownZero |= RHSKnownZero & BKnownOne;
00603       KnownOne  |= RHSKnownOne  & BKnownOne;
00604     // assume(v << c = a)
00605     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00606                        m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
00607                                       m_Value(A)))) &&
00608                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00609       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00610       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00611       // For those bits in RHS that are known, we can propagate them to known
00612       // bits in V shifted to the right by C.
00613       KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
00614       KnownOne  |= RHSKnownOne.lshr(C->getZExtValue());
00615     // assume(~(v << c) = a)
00616     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00617                        m_c_ICmp(Pred, m_Not(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 inverted
00623       // to known bits in V shifted to the right by C.
00624       KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
00625       KnownOne  |= RHSKnownZero.lshr(C->getZExtValue());
00626     // assume(v >> c = a)
00627     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00628                        m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
00629                                                   m_AShr(m_V,
00630                                                          m_ConstantInt(C))),
00631                                      m_Value(A)))) &&
00632                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00633       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00634       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00635       // For those bits in RHS that are known, we can propagate them to known
00636       // bits in V shifted to the right by C.
00637       KnownZero |= RHSKnownZero << C->getZExtValue();
00638       KnownOne  |= RHSKnownOne  << C->getZExtValue();
00639     // assume(~(v >> c) = a)
00640     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00641                        m_c_ICmp(Pred, m_Not(m_CombineOr(
00642                                               m_LShr(m_V, m_ConstantInt(C)),
00643                                               m_AShr(m_V, m_ConstantInt(C)))),
00644                                      m_Value(A)))) &&
00645                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00646       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00647       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00648       // For those bits in RHS that are known, we can propagate them inverted
00649       // to known bits in V shifted to the right by C.
00650       KnownZero |= RHSKnownOne  << C->getZExtValue();
00651       KnownOne  |= RHSKnownZero << C->getZExtValue();
00652     // assume(v >=_s c) where c is non-negative
00653     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00654                        m_ICmp(Pred, m_V, m_Value(A)))) &&
00655                Pred == ICmpInst::ICMP_SGE &&
00656                isValidAssumeForContext(I, Q, DL)) {
00657       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00658       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00659 
00660       if (RHSKnownZero.isNegative()) {
00661         // We know that the sign bit is zero.
00662         KnownZero |= APInt::getSignBit(BitWidth);
00663       }
00664     // assume(v >_s c) where c is at least -1.
00665     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00666                        m_ICmp(Pred, m_V, m_Value(A)))) &&
00667                Pred == ICmpInst::ICMP_SGT &&
00668                isValidAssumeForContext(I, Q, DL)) {
00669       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00670       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00671 
00672       if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
00673         // We know that the sign bit is zero.
00674         KnownZero |= APInt::getSignBit(BitWidth);
00675       }
00676     // assume(v <=_s c) where c is negative
00677     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00678                        m_ICmp(Pred, m_V, m_Value(A)))) &&
00679                Pred == ICmpInst::ICMP_SLE &&
00680                isValidAssumeForContext(I, Q, DL)) {
00681       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00682       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00683 
00684       if (RHSKnownOne.isNegative()) {
00685         // We know that the sign bit is one.
00686         KnownOne |= APInt::getSignBit(BitWidth);
00687       }
00688     // assume(v <_s c) where c is non-positive
00689     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00690                        m_ICmp(Pred, m_V, m_Value(A)))) &&
00691                Pred == ICmpInst::ICMP_SLT &&
00692                isValidAssumeForContext(I, Q, DL)) {
00693       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00694       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00695 
00696       if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
00697         // We know that the sign bit is one.
00698         KnownOne |= APInt::getSignBit(BitWidth);
00699       }
00700     // assume(v <=_u c)
00701     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00702                        m_ICmp(Pred, m_V, m_Value(A)))) &&
00703                Pred == ICmpInst::ICMP_ULE &&
00704                isValidAssumeForContext(I, Q, DL)) {
00705       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00706       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00707 
00708       // Whatever high bits in c are zero are known to be zero.
00709       KnownZero |=
00710         APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
00711     // assume(v <_u c)
00712     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
00713                        m_ICmp(Pred, m_V, m_Value(A)))) &&
00714                Pred == ICmpInst::ICMP_ULT &&
00715                isValidAssumeForContext(I, Q, DL)) {
00716       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00717       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00718 
00719       // Whatever high bits in c are zero are known to be zero (if c is a power
00720       // of 2, then one more).
00721       if (isKnownToBeAPowerOfTwo(A, false, Depth+1, Query(Q, I)))
00722         KnownZero |=
00723           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
00724       else
00725         KnownZero |=
00726           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
00727     }
00728   }
00729 }
00730 
00731 /// Determine which bits of V are known to be either zero or one and return
00732 /// them in the KnownZero/KnownOne bit sets.
00733 ///
00734 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
00735 /// we cannot optimize based on the assumption that it is zero without changing
00736 /// it to be an explicit zero.  If we don't change it to zero, other code could
00737 /// optimized based on the contradictory assumption that it is non-zero.
00738 /// Because instcombine aggressively folds operations with undef args anyway,
00739 /// this won't lose us code quality.
00740 ///
00741 /// This function is defined on values with integer type, values with pointer
00742 /// type (but only if TD is non-null), and vectors of integers.  In the case
00743 /// where V is a vector, known zero, and known one values are the
00744 /// same width as the vector element, and the bit is set only if it is true
00745 /// for all of the elements in the vector.
00746 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00747                       const DataLayout *TD, unsigned Depth,
00748                       const Query &Q) {
00749   assert(V && "No Value?");
00750   assert(Depth <= MaxDepth && "Limit Search Depth");
00751   unsigned BitWidth = KnownZero.getBitWidth();
00752 
00753   assert((V->getType()->isIntOrIntVectorTy() ||
00754           V->getType()->getScalarType()->isPointerTy()) &&
00755          "Not integer or pointer type!");
00756   assert((!TD ||
00757           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
00758          (!V->getType()->isIntOrIntVectorTy() ||
00759           V->getType()->getScalarSizeInBits() == BitWidth) &&
00760          KnownZero.getBitWidth() == BitWidth &&
00761          KnownOne.getBitWidth() == BitWidth &&
00762          "V, KnownOne and KnownZero should have same BitWidth");
00763 
00764   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00765     // We know all of the bits for a constant!
00766     KnownOne = CI->getValue();
00767     KnownZero = ~KnownOne;
00768     return;
00769   }
00770   // Null and aggregate-zero are all-zeros.
00771   if (isa<ConstantPointerNull>(V) ||
00772       isa<ConstantAggregateZero>(V)) {
00773     KnownOne.clearAllBits();
00774     KnownZero = APInt::getAllOnesValue(BitWidth);
00775     return;
00776   }
00777   // Handle a constant vector by taking the intersection of the known bits of
00778   // each element.  There is no real need to handle ConstantVector here, because
00779   // we don't handle undef in any particularly useful way.
00780   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
00781     // We know that CDS must be a vector of integers. Take the intersection of
00782     // each element.
00783     KnownZero.setAllBits(); KnownOne.setAllBits();
00784     APInt Elt(KnownZero.getBitWidth(), 0);
00785     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
00786       Elt = CDS->getElementAsInteger(i);
00787       KnownZero &= ~Elt;
00788       KnownOne &= Elt;
00789     }
00790     return;
00791   }
00792 
00793   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
00794   // the bits of its aliasee.
00795   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00796     if (GA->mayBeOverridden()) {
00797       KnownZero.clearAllBits(); KnownOne.clearAllBits();
00798     } else {
00799       computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth+1, Q);
00800     }
00801     return;
00802   }
00803 
00804   // The address of an aligned GlobalValue has trailing zeros.
00805   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
00806     unsigned Align = GV->getAlignment();
00807     if (Align == 0 && TD) {
00808       if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
00809         Type *ObjectType = GVar->getType()->getElementType();
00810         if (ObjectType->isSized()) {
00811           // If the object is defined in the current Module, we'll be giving
00812           // it the preferred alignment. Otherwise, we have to assume that it
00813           // may only have the minimum ABI alignment.
00814           if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
00815             Align = TD->getPreferredAlignment(GVar);
00816           else
00817             Align = TD->getABITypeAlignment(ObjectType);
00818         }
00819       }
00820     }
00821     if (Align > 0)
00822       KnownZero = APInt::getLowBitsSet(BitWidth,
00823                                        countTrailingZeros(Align));
00824     else
00825       KnownZero.clearAllBits();
00826     KnownOne.clearAllBits();
00827     return;
00828   }
00829 
00830   if (Argument *A = dyn_cast<Argument>(V)) {
00831     unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
00832 
00833     if (!Align && TD && A->hasStructRetAttr()) {
00834       // An sret parameter has at least the ABI alignment of the return type.
00835       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
00836       if (EltTy->isSized())
00837         Align = TD->getABITypeAlignment(EltTy);
00838     }
00839 
00840     if (Align)
00841       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
00842 
00843     // Don't give up yet... there might be an assumption that provides more
00844     // information...
00845     computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
00846     return;
00847   }
00848 
00849   // Start out not knowing anything.
00850   KnownZero.clearAllBits(); KnownOne.clearAllBits();
00851 
00852   if (Depth == MaxDepth)
00853     return;  // Limit search depth.
00854 
00855   // Check whether a nearby assume intrinsic can determine some known bits.
00856   computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
00857 
00858   Operator *I = dyn_cast<Operator>(V);
00859   if (!I) return;
00860 
00861   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
00862   switch (I->getOpcode()) {
00863   default: break;
00864   case Instruction::Load:
00865     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
00866       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
00867     break;
00868   case Instruction::And: {
00869     // If either the LHS or the RHS are Zero, the result is zero.
00870     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
00871     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00872 
00873     // Output known-1 bits are only known if set in both the LHS & RHS.
00874     KnownOne &= KnownOne2;
00875     // Output known-0 are known to be clear if zero in either the LHS | RHS.
00876     KnownZero |= KnownZero2;
00877     break;
00878   }
00879   case Instruction::Or: {
00880     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
00881     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00882 
00883     // Output known-0 bits are only known if clear in both the LHS & RHS.
00884     KnownZero &= KnownZero2;
00885     // Output known-1 are known to be set if set in either the LHS | RHS.
00886     KnownOne |= KnownOne2;
00887     break;
00888   }
00889   case Instruction::Xor: {
00890     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
00891     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00892 
00893     // Output known-0 bits are known if clear or set in both the LHS & RHS.
00894     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
00895     // Output known-1 are known to be set if set in only one of the LHS, RHS.
00896     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
00897     KnownZero = KnownZeroOut;
00898     break;
00899   }
00900   case Instruction::Mul: {
00901     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
00902     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW,
00903                          KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
00904                          Depth, Q);
00905     break;
00906   }
00907   case Instruction::UDiv: {
00908     // For the purposes of computing leading zeros we can conservatively
00909     // treat a udiv as a logical right shift by the power of 2 known to
00910     // be less than the denominator.
00911     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00912     unsigned LeadZ = KnownZero2.countLeadingOnes();
00913 
00914     KnownOne2.clearAllBits();
00915     KnownZero2.clearAllBits();
00916     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
00917     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
00918     if (RHSUnknownLeadingOnes != BitWidth)
00919       LeadZ = std::min(BitWidth,
00920                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
00921 
00922     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
00923     break;
00924   }
00925   case Instruction::Select:
00926     computeKnownBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1, Q);
00927     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
00928 
00929     // Only known if known in both the LHS and RHS.
00930     KnownOne &= KnownOne2;
00931     KnownZero &= KnownZero2;
00932     break;
00933   case Instruction::FPTrunc:
00934   case Instruction::FPExt:
00935   case Instruction::FPToUI:
00936   case Instruction::FPToSI:
00937   case Instruction::SIToFP:
00938   case Instruction::UIToFP:
00939     break; // Can't work with floating point.
00940   case Instruction::PtrToInt:
00941   case Instruction::IntToPtr:
00942   case Instruction::AddrSpaceCast: // Pointers could be different sizes.
00943     // We can't handle these if we don't know the pointer size.
00944     if (!TD) break;
00945     // FALL THROUGH and handle them the same as zext/trunc.
00946   case Instruction::ZExt:
00947   case Instruction::Trunc: {
00948     Type *SrcTy = I->getOperand(0)->getType();
00949 
00950     unsigned SrcBitWidth;
00951     // Note that we handle pointer operands here because of inttoptr/ptrtoint
00952     // which fall through here.
00953     if(TD) {
00954       SrcBitWidth = TD->getTypeSizeInBits(SrcTy->getScalarType());
00955     } else {
00956       SrcBitWidth = SrcTy->getScalarSizeInBits();
00957       if (!SrcBitWidth) break;
00958     }
00959 
00960     assert(SrcBitWidth && "SrcBitWidth can't be zero");
00961     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
00962     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
00963     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
00964     KnownZero = KnownZero.zextOrTrunc(BitWidth);
00965     KnownOne = KnownOne.zextOrTrunc(BitWidth);
00966     // Any top bits are known to be zero.
00967     if (BitWidth > SrcBitWidth)
00968       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00969     break;
00970   }
00971   case Instruction::BitCast: {
00972     Type *SrcTy = I->getOperand(0)->getType();
00973     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
00974         // TODO: For now, not handling conversions like:
00975         // (bitcast i64 %x to <2 x i32>)
00976         !I->getType()->isVectorTy()) {
00977       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
00978       break;
00979     }
00980     break;
00981   }
00982   case Instruction::SExt: {
00983     // Compute the bits in the result that are not present in the input.
00984     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
00985 
00986     KnownZero = KnownZero.trunc(SrcBitWidth);
00987     KnownOne = KnownOne.trunc(SrcBitWidth);
00988     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
00989     KnownZero = KnownZero.zext(BitWidth);
00990     KnownOne = KnownOne.zext(BitWidth);
00991 
00992     // If the sign bit of the input is known set or clear, then we know the
00993     // top bits of the result.
00994     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
00995       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00996     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
00997       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00998     break;
00999   }
01000   case Instruction::Shl:
01001     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
01002     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01003       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
01004       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01005       KnownZero <<= ShiftAmt;
01006       KnownOne  <<= ShiftAmt;
01007       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
01008       break;
01009     }
01010     break;
01011   case Instruction::LShr:
01012     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
01013     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01014       // Compute the new bits that are at the top now.
01015       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
01016 
01017       // Unsigned shift right.
01018       computeKnownBits(I->getOperand(0), KnownZero,KnownOne, TD, Depth+1, Q);
01019       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
01020       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
01021       // high bits known zero.
01022       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
01023       break;
01024     }
01025     break;
01026   case Instruction::AShr:
01027     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
01028     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01029       // Compute the new bits that are at the top now.
01030       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
01031 
01032       // Signed shift right.
01033       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01034       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
01035       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
01036 
01037       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
01038       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
01039         KnownZero |= HighBits;
01040       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
01041         KnownOne |= HighBits;
01042       break;
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 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
01326 /// one.  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 /// isKnownToBeAPowerOfTwo - 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 = cast<ConstantInt>(Ranges->getOperand(2*i + 0));
01514     ConstantInt *Upper = cast<ConstantInt>(Ranges->getOperand(2*i + 1));
01515     ConstantRange Range(Lower->getValue(), Upper->getValue());
01516     if (Range.contains(Value))
01517       return false;
01518   }
01519   return true;
01520 }
01521 
01522 /// isKnownNonZero - Return true if the given value is known to be non-zero
01523 /// when defined.  For vectors return true if every element is known to be
01524 /// non-zero when defined.  Supports values with integer or pointer type and
01525 /// vectors of integers.
01526 bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
01527                     const Query &Q) {
01528   if (Constant *C = dyn_cast<Constant>(V)) {
01529     if (C->isNullValue())
01530       return false;
01531     if (isa<ConstantInt>(C))
01532       // Must be non-zero due to null test above.
01533       return true;
01534     // TODO: Handle vectors
01535     return false;
01536   }
01537 
01538   if (Instruction* I = dyn_cast<Instruction>(V)) {
01539     if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
01540       // If the possible ranges don't contain zero, then the value is
01541       // definitely non-zero.
01542       if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
01543         const APInt ZeroValue(Ty->getBitWidth(), 0);
01544         if (rangeMetadataExcludesValue(Ranges, ZeroValue))
01545           return true;
01546       }
01547     }
01548   }
01549 
01550   // The remaining tests are all recursive, so bail out if we hit the limit.
01551   if (Depth++ >= MaxDepth)
01552     return false;
01553 
01554   // Check for pointer simplifications.
01555   if (V->getType()->isPointerTy()) {
01556     if (isKnownNonNull(V))
01557       return true; 
01558     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
01559       if (isGEPKnownNonNull(GEP, TD, Depth, Q))
01560         return true;
01561   }
01562 
01563   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
01564 
01565   // X | Y != 0 if X != 0 or Y != 0.
01566   Value *X = nullptr, *Y = nullptr;
01567   if (match(V, m_Or(m_Value(X), m_Value(Y))))
01568     return isKnownNonZero(X, TD, Depth, Q) ||
01569            isKnownNonZero(Y, TD, Depth, Q);
01570 
01571   // ext X != 0 if X != 0.
01572   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
01573     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth, Q);
01574 
01575   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
01576   // if the lowest bit is shifted off the end.
01577   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
01578     // shl nuw can't remove any non-zero bits.
01579     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
01580     if (BO->hasNoUnsignedWrap())
01581       return isKnownNonZero(X, TD, Depth, Q);
01582 
01583     APInt KnownZero(BitWidth, 0);
01584     APInt KnownOne(BitWidth, 0);
01585     computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
01586     if (KnownOne[0])
01587       return true;
01588   }
01589   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
01590   // defined if the sign bit is shifted off the end.
01591   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
01592     // shr exact can only shift out zero bits.
01593     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
01594     if (BO->isExact())
01595       return isKnownNonZero(X, TD, Depth, Q);
01596 
01597     bool XKnownNonNegative, XKnownNegative;
01598     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
01599     if (XKnownNegative)
01600       return true;
01601   }
01602   // div exact can only produce a zero if the dividend is zero.
01603   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
01604     return isKnownNonZero(X, TD, Depth, Q);
01605   }
01606   // X + Y.
01607   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
01608     bool XKnownNonNegative, XKnownNegative;
01609     bool YKnownNonNegative, YKnownNegative;
01610     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
01611     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth, Q);
01612 
01613     // If X and Y are both non-negative (as signed values) then their sum is not
01614     // zero unless both X and Y are zero.
01615     if (XKnownNonNegative && YKnownNonNegative)
01616       if (isKnownNonZero(X, TD, Depth, Q) ||
01617           isKnownNonZero(Y, TD, Depth, Q))
01618         return true;
01619 
01620     // If X and Y are both negative (as signed values) then their sum is not
01621     // zero unless both X and Y equal INT_MIN.
01622     if (BitWidth && XKnownNegative && YKnownNegative) {
01623       APInt KnownZero(BitWidth, 0);
01624       APInt KnownOne(BitWidth, 0);
01625       APInt Mask = APInt::getSignedMaxValue(BitWidth);
01626       // The sign bit of X is set.  If some other bit is set then X is not equal
01627       // to INT_MIN.
01628       computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
01629       if ((KnownOne & Mask) != 0)
01630         return true;
01631       // The sign bit of Y is set.  If some other bit is set then Y is not equal
01632       // to INT_MIN.
01633       computeKnownBits(Y, KnownZero, KnownOne, TD, Depth, Q);
01634       if ((KnownOne & Mask) != 0)
01635         return true;
01636     }
01637 
01638     // The sum of a non-negative number and a power of two is not zero.
01639     if (XKnownNonNegative &&
01640         isKnownToBeAPowerOfTwo(Y, /*OrZero*/false, Depth, Q))
01641       return true;
01642     if (YKnownNonNegative &&
01643         isKnownToBeAPowerOfTwo(X, /*OrZero*/false, Depth, Q))
01644       return true;
01645   }
01646   // X * Y.
01647   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
01648     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
01649     // If X and Y are non-zero then so is X * Y as long as the multiplication
01650     // does not overflow.
01651     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
01652         isKnownNonZero(X, TD, Depth, Q) &&
01653         isKnownNonZero(Y, TD, Depth, Q))
01654       return true;
01655   }
01656   // (C ? X : Y) != 0 if X != 0 and Y != 0.
01657   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
01658     if (isKnownNonZero(SI->getTrueValue(), TD, Depth, Q) &&
01659         isKnownNonZero(SI->getFalseValue(), TD, Depth, Q))
01660       return true;
01661   }
01662 
01663   if (!BitWidth) return false;
01664   APInt KnownZero(BitWidth, 0);
01665   APInt KnownOne(BitWidth, 0);
01666   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
01667   return KnownOne != 0;
01668 }
01669 
01670 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
01671 /// this predicate to simplify operations downstream.  Mask is known to be zero
01672 /// for bits that V cannot have.
01673 ///
01674 /// This function is defined on values with integer type, values with pointer
01675 /// type (but only if TD is non-null), and vectors of integers.  In the case
01676 /// where V is a vector, the mask, known zero, and known one values are the
01677 /// same width as the vector element, and the bit is set only if it is true
01678 /// for all of the elements in the vector.
01679 bool MaskedValueIsZero(Value *V, const APInt &Mask,
01680                        const DataLayout *TD, unsigned Depth,
01681                        const Query &Q) {
01682   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
01683   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
01684   return (KnownZero & Mask) == Mask;
01685 }
01686 
01687 
01688 
01689 /// ComputeNumSignBits - Return the number of times the sign bit of the
01690 /// register is replicated into the other bits.  We know that at least 1 bit
01691 /// is always equal to the sign bit (itself), but other cases can give us
01692 /// information.  For example, immediately after an "ashr X, 2", we know that
01693 /// the top 3 bits are all equal to each other, so we return 3.
01694 ///
01695 /// 'Op' must have a scalar integer type.
01696 ///
01697 unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
01698                             unsigned Depth, const Query &Q) {
01699   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
01700          "ComputeNumSignBits requires a DataLayout object to operate "
01701          "on non-integer values!");
01702   Type *Ty = V->getType();
01703   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
01704                          Ty->getScalarSizeInBits();
01705   unsigned Tmp, Tmp2;
01706   unsigned FirstAnswer = 1;
01707 
01708   // Note that ConstantInt is handled by the general computeKnownBits case
01709   // below.
01710 
01711   if (Depth == 6)
01712     return 1;  // Limit search depth.
01713 
01714   Operator *U = dyn_cast<Operator>(V);
01715   switch (Operator::getOpcode(V)) {
01716   default: break;
01717   case Instruction::SExt:
01718     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
01719     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q) + Tmp;
01720 
01721   case Instruction::AShr: {
01722     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01723     // ashr X, C   -> adds C sign bits.  Vectors too.
01724     const APInt *ShAmt;
01725     if (match(U->getOperand(1), m_APInt(ShAmt))) {
01726       Tmp += ShAmt->getZExtValue();
01727       if (Tmp > TyBits) Tmp = TyBits;
01728     }
01729     return Tmp;
01730   }
01731   case Instruction::Shl: {
01732     const APInt *ShAmt;
01733     if (match(U->getOperand(1), m_APInt(ShAmt))) {
01734       // shl destroys sign bits.
01735       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01736       Tmp2 = ShAmt->getZExtValue();
01737       if (Tmp2 >= TyBits ||      // Bad shift.
01738           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
01739       return Tmp - Tmp2;
01740     }
01741     break;
01742   }
01743   case Instruction::And:
01744   case Instruction::Or:
01745   case Instruction::Xor:    // NOT is handled here.
01746     // Logical binary ops preserve the number of sign bits at the worst.
01747     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01748     if (Tmp != 1) {
01749       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01750       FirstAnswer = std::min(Tmp, Tmp2);
01751       // We computed what we know about the sign bits as our first
01752       // answer. Now proceed to the generic code that uses
01753       // computeKnownBits, and pick whichever answer is better.
01754     }
01755     break;
01756 
01757   case Instruction::Select:
01758     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01759     if (Tmp == 1) return 1;  // Early out.
01760     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1, Q);
01761     return std::min(Tmp, Tmp2);
01762 
01763   case Instruction::Add:
01764     // Add can have at most one carry bit.  Thus we know that the output
01765     // is, at worst, one more bit than the inputs.
01766     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01767     if (Tmp == 1) return 1;  // Early out.
01768 
01769     // Special case decrementing a value (ADD X, -1):
01770     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
01771       if (CRHS->isAllOnesValue()) {
01772         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01773         computeKnownBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01774 
01775         // If the input is known to be 0 or 1, the output is 0/-1, which is all
01776         // sign bits set.
01777         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
01778           return TyBits;
01779 
01780         // If we are subtracting one from a positive number, there is no carry
01781         // out of the result.
01782         if (KnownZero.isNegative())
01783           return Tmp;
01784       }
01785 
01786     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01787     if (Tmp2 == 1) return 1;
01788     return std::min(Tmp, Tmp2)-1;
01789 
01790   case Instruction::Sub:
01791     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01792     if (Tmp2 == 1) return 1;
01793 
01794     // Handle NEG.
01795     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
01796       if (CLHS->isNullValue()) {
01797         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01798         computeKnownBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
01799         // If the input is known to be 0 or 1, the output is 0/-1, which is all
01800         // sign bits set.
01801         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
01802           return TyBits;
01803 
01804         // If the input is known to be positive (the sign bit is known clear),
01805         // the output of the NEG has the same number of sign bits as the input.
01806         if (KnownZero.isNegative())
01807           return Tmp2;
01808 
01809         // Otherwise, we treat this like a SUB.
01810       }
01811 
01812     // Sub can have at most one carry bit.  Thus we know that the output
01813     // is, at worst, one more bit than the inputs.
01814     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01815     if (Tmp == 1) return 1;  // Early out.
01816     return std::min(Tmp, Tmp2)-1;
01817 
01818   case Instruction::PHI: {
01819     PHINode *PN = cast<PHINode>(U);
01820     // Don't analyze large in-degree PHIs.
01821     if (PN->getNumIncomingValues() > 4) break;
01822 
01823     // Take the minimum of all incoming values.  This can't infinitely loop
01824     // because of our depth threshold.
01825     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1, Q);
01826     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
01827       if (Tmp == 1) return Tmp;
01828       Tmp = std::min(Tmp,
01829                      ComputeNumSignBits(PN->getIncomingValue(i), TD,
01830                                         Depth+1, Q));
01831     }
01832     return Tmp;
01833   }
01834 
01835   case Instruction::Trunc:
01836     // FIXME: it's tricky to do anything useful for this, but it is an important
01837     // case for targets like X86.
01838     break;
01839   }
01840 
01841   // Finally, if we can prove that the top bits of the result are 0's or 1's,
01842   // use this information.
01843   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01844   APInt Mask;
01845   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
01846 
01847   if (KnownZero.isNegative()) {        // sign bit is 0
01848     Mask = KnownZero;
01849   } else if (KnownOne.isNegative()) {  // sign bit is 1;
01850     Mask = KnownOne;
01851   } else {
01852     // Nothing known.
01853     return FirstAnswer;
01854   }
01855 
01856   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
01857   // the number of identical bits in the top of the input value.
01858   Mask = ~Mask;
01859   Mask <<= Mask.getBitWidth()-TyBits;
01860   // Return # leading zeros.  We use 'min' here in case Val was zero before
01861   // shifting.  We don't want to return '64' as for an i32 "0".
01862   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
01863 }
01864 
01865 /// ComputeMultiple - This function computes the integer multiple of Base that
01866 /// equals V.  If successful, it returns true and returns the multiple in
01867 /// Multiple.  If unsuccessful, it returns false. It looks
01868 /// through SExt instructions only if LookThroughSExt is true.
01869 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
01870                            bool LookThroughSExt, unsigned Depth) {
01871   const unsigned MaxDepth = 6;
01872 
01873   assert(V && "No Value?");
01874   assert(Depth <= MaxDepth && "Limit Search Depth");
01875   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
01876 
01877   Type *T = V->getType();
01878 
01879   ConstantInt *CI = dyn_cast<ConstantInt>(V);
01880 
01881   if (Base == 0)
01882     return false;
01883 
01884   if (Base == 1) {
01885     Multiple = V;
01886     return true;
01887   }
01888 
01889   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
01890   Constant *BaseVal = ConstantInt::get(T, Base);
01891   if (CO && CO == BaseVal) {
01892     // Multiple is 1.
01893     Multiple = ConstantInt::get(T, 1);
01894     return true;
01895   }
01896 
01897   if (CI && CI->getZExtValue() % Base == 0) {
01898     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
01899     return true;
01900   }
01901 
01902   if (Depth == MaxDepth) return false;  // Limit search depth.
01903 
01904   Operator *I = dyn_cast<Operator>(V);
01905   if (!I) return false;
01906 
01907   switch (I->getOpcode()) {
01908   default: break;
01909   case Instruction::SExt:
01910     if (!LookThroughSExt) return false;
01911     // otherwise fall through to ZExt
01912   case Instruction::ZExt:
01913     return ComputeMultiple(I->getOperand(0), Base, Multiple,
01914                            LookThroughSExt, Depth+1);
01915   case Instruction::Shl:
01916   case Instruction::Mul: {
01917     Value *Op0 = I->getOperand(0);
01918     Value *Op1 = I->getOperand(1);
01919 
01920     if (I->getOpcode() == Instruction::Shl) {
01921       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
01922       if (!Op1CI) return false;
01923       // Turn Op0 << Op1 into Op0 * 2^Op1
01924       APInt Op1Int = Op1CI->getValue();
01925       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
01926       APInt API(Op1Int.getBitWidth(), 0);
01927       API.setBit(BitToSet);
01928       Op1 = ConstantInt::get(V->getContext(), API);
01929     }
01930 
01931     Value *Mul0 = nullptr;
01932     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
01933       if (Constant *Op1C = dyn_cast<Constant>(Op1))
01934         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
01935           if (Op1C->getType()->getPrimitiveSizeInBits() <
01936               MulC->getType()->getPrimitiveSizeInBits())
01937             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
01938           if (Op1C->getType()->getPrimitiveSizeInBits() >
01939               MulC->getType()->getPrimitiveSizeInBits())
01940             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
01941 
01942           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
01943           Multiple = ConstantExpr::getMul(MulC, Op1C);
01944           return true;
01945         }
01946 
01947       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
01948         if (Mul0CI->getValue() == 1) {
01949           // V == Base * Op1, so return Op1
01950           Multiple = Op1;
01951           return true;
01952         }
01953     }
01954 
01955     Value *Mul1 = nullptr;
01956     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
01957       if (Constant *Op0C = dyn_cast<Constant>(Op0))
01958         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
01959           if (Op0C->getType()->getPrimitiveSizeInBits() <
01960               MulC->getType()->getPrimitiveSizeInBits())
01961             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
01962           if (Op0C->getType()->getPrimitiveSizeInBits() >
01963               MulC->getType()->getPrimitiveSizeInBits())
01964             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
01965 
01966           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
01967           Multiple = ConstantExpr::getMul(MulC, Op0C);
01968           return true;
01969         }
01970 
01971       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
01972         if (Mul1CI->getValue() == 1) {
01973           // V == Base * Op0, so return Op0
01974           Multiple = Op0;
01975           return true;
01976         }
01977     }
01978   }
01979   }
01980 
01981   // We could not determine if V is a multiple of Base.
01982   return false;
01983 }
01984 
01985 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
01986 /// value is never equal to -0.0.
01987 ///
01988 /// NOTE: this function will need to be revisited when we support non-default
01989 /// rounding modes!
01990 ///
01991 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
01992   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
01993     return !CFP->getValueAPF().isNegZero();
01994 
01995   if (Depth == 6)
01996     return 1;  // Limit search depth.
01997 
01998   const Operator *I = dyn_cast<Operator>(V);
01999   if (!I) return false;
02000 
02001   // Check if the nsz fast-math flag is set
02002   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
02003     if (FPO->hasNoSignedZeros())
02004       return true;
02005 
02006   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
02007   if (I->getOpcode() == Instruction::FAdd)
02008     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
02009       if (CFP->isNullValue())
02010         return true;
02011 
02012   // sitofp and uitofp turn into +0.0 for zero.
02013   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
02014     return true;
02015 
02016   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
02017     // sqrt(-0.0) = -0.0, no other negative results are possible.
02018     if (II->getIntrinsicID() == Intrinsic::sqrt)
02019       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
02020 
02021   if (const CallInst *CI = dyn_cast<CallInst>(I))
02022     if (const Function *F = CI->getCalledFunction()) {
02023       if (F->isDeclaration()) {
02024         // abs(x) != -0.0
02025         if (F->getName() == "abs") return true;
02026         // fabs[lf](x) != -0.0
02027         if (F->getName() == "fabs") return true;
02028         if (F->getName() == "fabsf") return true;
02029         if (F->getName() == "fabsl") return true;
02030         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
02031             F->getName() == "sqrtl")
02032           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
02033       }
02034     }
02035 
02036   return false;
02037 }
02038 
02039 /// isBytewiseValue - If the specified value can be set by repeating the same
02040 /// byte in memory, return the i8 value that it is represented with.  This is
02041 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
02042 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
02043 /// byte store (e.g. i16 0x1234), return null.
02044 Value *llvm::isBytewiseValue(Value *V) {
02045   // All byte-wide stores are splatable, even of arbitrary variables.
02046   if (V->getType()->isIntegerTy(8)) return V;
02047 
02048   // Handle 'null' ConstantArrayZero etc.
02049   if (Constant *C = dyn_cast<Constant>(V))
02050     if (C->isNullValue())
02051       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
02052 
02053   // Constant float and double values can be handled as integer values if the
02054   // corresponding integer value is "byteable".  An important case is 0.0.
02055   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
02056     if (CFP->getType()->isFloatTy())
02057       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
02058     if (CFP->getType()->isDoubleTy())
02059       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
02060     // Don't handle long double formats, which have strange constraints.
02061   }
02062 
02063   // We can handle constant integers that are power of two in size and a
02064   // multiple of 8 bits.
02065   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
02066     unsigned Width = CI->getBitWidth();
02067     if (isPowerOf2_32(Width) && Width > 8) {
02068       // We can handle this value if the recursive binary decomposition is the
02069       // same at all levels.
02070       APInt Val = CI->getValue();
02071       APInt Val2;
02072       while (Val.getBitWidth() != 8) {
02073         unsigned NextWidth = Val.getBitWidth()/2;
02074         Val2  = Val.lshr(NextWidth);
02075         Val2 = Val2.trunc(Val.getBitWidth()/2);
02076         Val = Val.trunc(Val.getBitWidth()/2);
02077 
02078         // If the top/bottom halves aren't the same, reject it.
02079         if (Val != Val2)
02080           return nullptr;
02081       }
02082       return ConstantInt::get(V->getContext(), Val);
02083     }
02084   }
02085 
02086   // A ConstantDataArray/Vector is splatable if all its members are equal and
02087   // also splatable.
02088   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
02089     Value *Elt = CA->getElementAsConstant(0);
02090     Value *Val = isBytewiseValue(Elt);
02091     if (!Val)
02092       return nullptr;
02093 
02094     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
02095       if (CA->getElementAsConstant(I) != Elt)
02096         return nullptr;
02097 
02098     return Val;
02099   }
02100 
02101   // Conceptually, we could handle things like:
02102   //   %a = zext i8 %X to i16
02103   //   %b = shl i16 %a, 8
02104   //   %c = or i16 %a, %b
02105   // but until there is an example that actually needs this, it doesn't seem
02106   // worth worrying about.
02107   return nullptr;
02108 }
02109 
02110 
02111 // This is the recursive version of BuildSubAggregate. It takes a few different
02112 // arguments. Idxs is the index within the nested struct From that we are
02113 // looking at now (which is of type IndexedType). IdxSkip is the number of
02114 // indices from Idxs that should be left out when inserting into the resulting
02115 // struct. To is the result struct built so far, new insertvalue instructions
02116 // build on that.
02117 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
02118                                 SmallVectorImpl<unsigned> &Idxs,
02119                                 unsigned IdxSkip,
02120                                 Instruction *InsertBefore) {
02121   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
02122   if (STy) {
02123     // Save the original To argument so we can modify it
02124     Value *OrigTo = To;
02125     // General case, the type indexed by Idxs is a struct
02126     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
02127       // Process each struct element recursively
02128       Idxs.push_back(i);
02129       Value *PrevTo = To;
02130       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
02131                              InsertBefore);
02132       Idxs.pop_back();
02133       if (!To) {
02134         // Couldn't find any inserted value for this index? Cleanup
02135         while (PrevTo != OrigTo) {
02136           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
02137           PrevTo = Del->getAggregateOperand();
02138           Del->eraseFromParent();
02139         }
02140         // Stop processing elements
02141         break;
02142       }
02143     }
02144     // If we successfully found a value for each of our subaggregates
02145     if (To)
02146       return To;
02147   }
02148   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
02149   // the struct's elements had a value that was inserted directly. In the latter
02150   // case, perhaps we can't determine each of the subelements individually, but
02151   // we might be able to find the complete struct somewhere.
02152 
02153   // Find the value that is at that particular spot
02154   Value *V = FindInsertedValue(From, Idxs);
02155 
02156   if (!V)
02157     return nullptr;
02158 
02159   // Insert the value in the new (sub) aggregrate
02160   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
02161                                        "tmp", InsertBefore);
02162 }
02163 
02164 // This helper takes a nested struct and extracts a part of it (which is again a
02165 // struct) into a new value. For example, given the struct:
02166 // { a, { b, { c, d }, e } }
02167 // and the indices "1, 1" this returns
02168 // { c, d }.
02169 //
02170 // It does this by inserting an insertvalue for each element in the resulting
02171 // struct, as opposed to just inserting a single struct. This will only work if
02172 // each of the elements of the substruct are known (ie, inserted into From by an
02173 // insertvalue instruction somewhere).
02174 //
02175 // All inserted insertvalue instructions are inserted before InsertBefore
02176 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
02177                                 Instruction *InsertBefore) {
02178   assert(InsertBefore && "Must have someplace to insert!");
02179   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
02180                                                              idx_range);
02181   Value *To = UndefValue::get(IndexedType);
02182   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
02183   unsigned IdxSkip = Idxs.size();
02184 
02185   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
02186 }
02187 
02188 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
02189 /// the scalar value indexed is already around as a register, for example if it
02190 /// were inserted directly into the aggregrate.
02191 ///
02192 /// If InsertBefore is not null, this function will duplicate (modified)
02193 /// insertvalues when a part of a nested struct is extracted.
02194 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
02195                                Instruction *InsertBefore) {
02196   // Nothing to index? Just return V then (this is useful at the end of our
02197   // recursion).
02198   if (idx_range.empty())
02199     return V;
02200   // We have indices, so V should have an indexable type.
02201   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
02202          "Not looking at a struct or array?");
02203   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
02204          "Invalid indices for type?");
02205 
02206   if (Constant *C = dyn_cast<Constant>(V)) {
02207     C = C->getAggregateElement(idx_range[0]);
02208     if (!C) return nullptr;
02209     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
02210   }
02211 
02212   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
02213     // Loop the indices for the insertvalue instruction in parallel with the
02214     // requested indices
02215     const unsigned *req_idx = idx_range.begin();
02216     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
02217          i != e; ++i, ++req_idx) {
02218       if (req_idx == idx_range.end()) {
02219         // We can't handle this without inserting insertvalues
02220         if (!InsertBefore)
02221           return nullptr;
02222 
02223         // The requested index identifies a part of a nested aggregate. Handle
02224         // this specially. For example,
02225         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
02226         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
02227         // %C = extractvalue {i32, { i32, i32 } } %B, 1
02228         // This can be changed into
02229         // %A = insertvalue {i32, i32 } undef, i32 10, 0
02230         // %C = insertvalue {i32, i32 } %A, i32 11, 1
02231         // which allows the unused 0,0 element from the nested struct to be
02232         // removed.
02233         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
02234                                  InsertBefore);
02235       }
02236 
02237       // This insert value inserts something else than what we are looking for.
02238       // See if the (aggregrate) value inserted into has the value we are
02239       // looking for, then.
02240       if (*req_idx != *i)
02241         return FindInsertedValue(I->getAggregateOperand(), idx_range,
02242                                  InsertBefore);
02243     }
02244     // If we end up here, the indices of the insertvalue match with those
02245     // requested (though possibly only partially). Now we recursively look at
02246     // the inserted value, passing any remaining indices.
02247     return FindInsertedValue(I->getInsertedValueOperand(),
02248                              makeArrayRef(req_idx, idx_range.end()),
02249                              InsertBefore);
02250   }
02251 
02252   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
02253     // If we're extracting a value from an aggregrate that was extracted from
02254     // something else, we can extract from that something else directly instead.
02255     // However, we will need to chain I's indices with the requested indices.
02256 
02257     // Calculate the number of indices required
02258     unsigned size = I->getNumIndices() + idx_range.size();
02259     // Allocate some space to put the new indices in
02260     SmallVector<unsigned, 5> Idxs;
02261     Idxs.reserve(size);
02262     // Add indices from the extract value instruction
02263     Idxs.append(I->idx_begin(), I->idx_end());
02264 
02265     // Add requested indices
02266     Idxs.append(idx_range.begin(), idx_range.end());
02267 
02268     assert(Idxs.size() == size
02269            && "Number of indices added not correct?");
02270 
02271     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
02272   }
02273   // Otherwise, we don't know (such as, extracting from a function return value
02274   // or load instruction)
02275   return nullptr;
02276 }
02277 
02278 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
02279 /// it can be expressed as a base pointer plus a constant offset.  Return the
02280 /// base and offset to the caller.
02281 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
02282                                               const DataLayout *DL) {
02283   // Without DataLayout, conservatively assume 64-bit offsets, which is
02284   // the widest we support.
02285   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(Ptr->getType()) : 64;
02286   APInt ByteOffset(BitWidth, 0);
02287   while (1) {
02288     if (Ptr->getType()->isVectorTy())
02289       break;
02290 
02291     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
02292       if (DL) {
02293         APInt GEPOffset(BitWidth, 0);
02294         if (!GEP->accumulateConstantOffset(*DL, GEPOffset))
02295           break;
02296 
02297         ByteOffset += GEPOffset;
02298       }
02299 
02300       Ptr = GEP->getPointerOperand();
02301     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
02302                Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
02303       Ptr = cast<Operator>(Ptr)->getOperand(0);
02304     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
02305       if (GA->mayBeOverridden())
02306         break;
02307       Ptr = GA->getAliasee();
02308     } else {
02309       break;
02310     }
02311   }
02312   Offset = ByteOffset.getSExtValue();
02313   return Ptr;
02314 }
02315 
02316 
02317 /// getConstantStringInfo - This function computes the length of a
02318 /// null-terminated C string pointed to by V.  If successful, it returns true
02319 /// and returns the string in Str.  If unsuccessful, it returns false.
02320 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
02321                                  uint64_t Offset, bool TrimAtNul) {
02322   assert(V);
02323 
02324   // Look through bitcast instructions and geps.
02325   V = V->stripPointerCasts();
02326 
02327   // If the value is a GEP instructionor  constant expression, treat it as an
02328   // offset.
02329   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
02330     // Make sure the GEP has exactly three arguments.
02331     if (GEP->getNumOperands() != 3)
02332       return false;
02333 
02334     // Make sure the index-ee is a pointer to array of i8.
02335     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
02336     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
02337     if (!AT || !AT->getElementType()->isIntegerTy(8))
02338       return false;
02339 
02340     // Check to make sure that the first operand of the GEP is an integer and
02341     // has value 0 so that we are sure we're indexing into the initializer.
02342     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
02343     if (!FirstIdx || !FirstIdx->isZero())
02344       return false;
02345 
02346     // If the second index isn't a ConstantInt, then this is a variable index
02347     // into the array.  If this occurs, we can't say anything meaningful about
02348     // the string.
02349     uint64_t StartIdx = 0;
02350     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
02351       StartIdx = CI->getZExtValue();
02352     else
02353       return false;
02354     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
02355   }
02356 
02357   // The GEP instruction, constant or instruction, must reference a global
02358   // variable that is a constant and is initialized. The referenced constant
02359   // initializer is the array that we'll use for optimization.
02360   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
02361   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
02362     return false;
02363 
02364   // Handle the all-zeros case
02365   if (GV->getInitializer()->isNullValue()) {
02366     // This is a degenerate case. The initializer is constant zero so the
02367     // length of the string must be zero.
02368     Str = "";
02369     return true;
02370   }
02371 
02372   // Must be a Constant Array
02373   const ConstantDataArray *Array =
02374     dyn_cast<ConstantDataArray>(GV->getInitializer());
02375   if (!Array || !Array->isString())
02376     return false;
02377 
02378   // Get the number of elements in the array
02379   uint64_t NumElts = Array->getType()->getArrayNumElements();
02380 
02381   // Start out with the entire array in the StringRef.
02382   Str = Array->getAsString();
02383 
02384   if (Offset > NumElts)
02385     return false;
02386 
02387   // Skip over 'offset' bytes.
02388   Str = Str.substr(Offset);
02389 
02390   if (TrimAtNul) {
02391     // Trim off the \0 and anything after it.  If the array is not nul
02392     // terminated, we just return the whole end of string.  The client may know
02393     // some other way that the string is length-bound.
02394     Str = Str.substr(0, Str.find('\0'));
02395   }
02396   return true;
02397 }
02398 
02399 // These next two are very similar to the above, but also look through PHI
02400 // nodes.
02401 // TODO: See if we can integrate these two together.
02402 
02403 /// GetStringLengthH - If we can compute the length of the string pointed to by
02404 /// the specified pointer, return 'len+1'.  If we can't, return 0.
02405 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
02406   // Look through noop bitcast instructions.
02407   V = V->stripPointerCasts();
02408 
02409   // If this is a PHI node, there are two cases: either we have already seen it
02410   // or we haven't.
02411   if (PHINode *PN = dyn_cast<PHINode>(V)) {
02412     if (!PHIs.insert(PN))
02413       return ~0ULL;  // already in the set.
02414 
02415     // If it was new, see if all the input strings are the same length.
02416     uint64_t LenSoFar = ~0ULL;
02417     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
02418       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
02419       if (Len == 0) return 0; // Unknown length -> unknown.
02420 
02421       if (Len == ~0ULL) continue;
02422 
02423       if (Len != LenSoFar && LenSoFar != ~0ULL)
02424         return 0;    // Disagree -> unknown.
02425       LenSoFar = Len;
02426     }
02427 
02428     // Success, all agree.
02429     return LenSoFar;
02430   }
02431 
02432   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
02433   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
02434     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
02435     if (Len1 == 0) return 0;
02436     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
02437     if (Len2 == 0) return 0;
02438     if (Len1 == ~0ULL) return Len2;
02439     if (Len2 == ~0ULL) return Len1;
02440     if (Len1 != Len2) return 0;
02441     return Len1;
02442   }
02443 
02444   // Otherwise, see if we can read the string.
02445   StringRef StrData;
02446   if (!getConstantStringInfo(V, StrData))
02447     return 0;
02448 
02449   return StrData.size()+1;
02450 }
02451 
02452 /// GetStringLength - If we can compute the length of the string pointed to by
02453 /// the specified pointer, return 'len+1'.  If we can't, return 0.
02454 uint64_t llvm::GetStringLength(Value *V) {
02455   if (!V->getType()->isPointerTy()) return 0;
02456 
02457   SmallPtrSet<PHINode*, 32> PHIs;
02458   uint64_t Len = GetStringLengthH(V, PHIs);
02459   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
02460   // an empty string as a length.
02461   return Len == ~0ULL ? 1 : Len;
02462 }
02463 
02464 Value *
02465 llvm::GetUnderlyingObject(Value *V, const DataLayout *TD, unsigned MaxLookup) {
02466   if (!V->getType()->isPointerTy())
02467     return V;
02468   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
02469     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
02470       V = GEP->getPointerOperand();
02471     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
02472                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
02473       V = cast<Operator>(V)->getOperand(0);
02474     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
02475       if (GA->mayBeOverridden())
02476         return V;
02477       V = GA->getAliasee();
02478     } else {
02479       // See if InstructionSimplify knows any relevant tricks.
02480       if (Instruction *I = dyn_cast<Instruction>(V))
02481         // TODO: Acquire a DominatorTree and AssumptionTracker and use them.
02482         if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
02483           V = Simplified;
02484           continue;
02485         }
02486 
02487       return V;
02488     }
02489     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
02490   }
02491   return V;
02492 }
02493 
02494 void
02495 llvm::GetUnderlyingObjects(Value *V,
02496                            SmallVectorImpl<Value *> &Objects,
02497                            const DataLayout *TD,
02498                            unsigned MaxLookup) {
02499   SmallPtrSet<Value *, 4> Visited;
02500   SmallVector<Value *, 4> Worklist;
02501   Worklist.push_back(V);
02502   do {
02503     Value *P = Worklist.pop_back_val();
02504     P = GetUnderlyingObject(P, TD, MaxLookup);
02505 
02506     if (!Visited.insert(P))
02507       continue;
02508 
02509     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
02510       Worklist.push_back(SI->getTrueValue());
02511       Worklist.push_back(SI->getFalseValue());
02512       continue;
02513     }
02514 
02515     if (PHINode *PN = dyn_cast<PHINode>(P)) {
02516       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
02517         Worklist.push_back(PN->getIncomingValue(i));
02518       continue;
02519     }
02520 
02521     Objects.push_back(P);
02522   } while (!Worklist.empty());
02523 }
02524 
02525 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
02526 /// are lifetime markers.
02527 ///
02528 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
02529   for (const User *U : V->users()) {
02530     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
02531     if (!II) return false;
02532 
02533     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
02534         II->getIntrinsicID() != Intrinsic::lifetime_end)
02535       return false;
02536   }
02537   return true;
02538 }
02539 
02540 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
02541                                         const DataLayout *TD) {
02542   const Operator *Inst = dyn_cast<Operator>(V);
02543   if (!Inst)
02544     return false;
02545 
02546   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
02547     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
02548       if (C->canTrap())
02549         return false;
02550 
02551   switch (Inst->getOpcode()) {
02552   default:
02553     return true;
02554   case Instruction::UDiv:
02555   case Instruction::URem:
02556     // x / y is undefined if y == 0, but calculations like x / 3 are safe.
02557     return isKnownNonZero(Inst->getOperand(1), TD);
02558   case Instruction::SDiv:
02559   case Instruction::SRem: {
02560     Value *Op = Inst->getOperand(1);
02561     // x / y is undefined if y == 0
02562     if (!isKnownNonZero(Op, TD))
02563       return false;
02564     // x / y might be undefined if y == -1
02565     unsigned BitWidth = getBitWidth(Op->getType(), TD);
02566     if (BitWidth == 0)
02567       return false;
02568     APInt KnownZero(BitWidth, 0);
02569     APInt KnownOne(BitWidth, 0);
02570     computeKnownBits(Op, KnownZero, KnownOne, TD);
02571     return !!KnownZero;
02572   }
02573   case Instruction::Load: {
02574     const LoadInst *LI = cast<LoadInst>(Inst);
02575     if (!LI->isUnordered() ||
02576         // Speculative load may create a race that did not exist in the source.
02577         LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
02578       return false;
02579     return LI->getPointerOperand()->isDereferenceablePointer(TD);
02580   }
02581   case Instruction::Call: {
02582    if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
02583      switch (II->getIntrinsicID()) {
02584        // These synthetic intrinsics have no side-effects and just mark
02585        // information about their operands.
02586        // FIXME: There are other no-op synthetic instructions that potentially
02587        // should be considered at least *safe* to speculate...
02588        case Intrinsic::dbg_declare:
02589        case Intrinsic::dbg_value:
02590          return true;
02591 
02592        case Intrinsic::bswap:
02593        case Intrinsic::ctlz:
02594        case Intrinsic::ctpop:
02595        case Intrinsic::cttz:
02596        case Intrinsic::objectsize:
02597        case Intrinsic::sadd_with_overflow:
02598        case Intrinsic::smul_with_overflow:
02599        case Intrinsic::ssub_with_overflow:
02600        case Intrinsic::uadd_with_overflow:
02601        case Intrinsic::umul_with_overflow:
02602        case Intrinsic::usub_with_overflow:
02603          return true;
02604        // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
02605        // errno like libm sqrt would.
02606        case Intrinsic::sqrt:
02607        case Intrinsic::fma:
02608        case Intrinsic::fmuladd:
02609        case Intrinsic::fabs:
02610        case Intrinsic::minnum:
02611        case Intrinsic::maxnum:
02612          return true;
02613        // TODO: some fp intrinsics are marked as having the same error handling
02614        // as libm. They're safe to speculate when they won't error.
02615        // TODO: are convert_{from,to}_fp16 safe?
02616        // TODO: can we list target-specific intrinsics here?
02617        default: break;
02618      }
02619    }
02620     return false; // The called function could have undefined behavior or
02621                   // side-effects, even if marked readnone nounwind.
02622   }
02623   case Instruction::VAArg:
02624   case Instruction::Alloca:
02625   case Instruction::Invoke:
02626   case Instruction::PHI:
02627   case Instruction::Store:
02628   case Instruction::Ret:
02629   case Instruction::Br:
02630   case Instruction::IndirectBr:
02631   case Instruction::Switch:
02632   case Instruction::Unreachable:
02633   case Instruction::Fence:
02634   case Instruction::LandingPad:
02635   case Instruction::AtomicRMW:
02636   case Instruction::AtomicCmpXchg:
02637   case Instruction::Resume:
02638     return false; // Misc instructions which have effects
02639   }
02640 }
02641 
02642 /// isKnownNonNull - Return true if we know that the specified value is never
02643 /// null.
02644 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
02645   // Alloca never returns null, malloc might.
02646   if (isa<AllocaInst>(V)) return true;
02647 
02648   // A byval, inalloca, or nonnull argument is never null.
02649   if (const Argument *A = dyn_cast<Argument>(V))
02650     return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
02651 
02652   // Global values are not null unless extern weak.
02653   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
02654     return !GV->hasExternalWeakLinkage();
02655 
02656   // A Load tagged w/nonnull metadata is never null. 
02657   if (const LoadInst *LI = dyn_cast<LoadInst>(V))
02658     return LI->getMetadata(LLVMContext::MD_nonnull);
02659 
02660   if (ImmutableCallSite CS = V)
02661     if (CS.isReturnNonNull())
02662       return true;
02663 
02664   // operator new never returns null.
02665   if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
02666     return true;
02667 
02668   return false;
02669 }