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