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