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