LLVM API Documentation

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