LLVM API Documentation

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