Add computeMaskedBitsLoad back, as it was the change to instsimplify that
[oota-llvm.git] / lib / Analysis / ValueTracking.cpp
1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines that help analyze properties that chains of
11 // computations have.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/GlobalAlias.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Metadata.h"
24 #include "llvm/Operator.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Support/ConstantRange.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/PatternMatch.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include <cstring>
32 using namespace llvm;
33 using namespace llvm::PatternMatch;
34
35 const unsigned MaxDepth = 6;
36
37 /// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
38 /// unknown returns 0).  For vector types, returns the element type's bitwidth.
39 static unsigned getBitWidth(Type *Ty, const TargetData *TD) {
40   if (unsigned BitWidth = Ty->getScalarSizeInBits())
41     return BitWidth;
42   assert(isa<PointerType>(Ty) && "Expected a pointer type!");
43   return TD ? TD->getPointerSizeInBits() : 0;
44 }
45
46 static void ComputeMaskedBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
47                                     const APInt &Mask,
48                                     APInt &KnownZero, APInt &KnownOne,
49                                     APInt &KnownZero2, APInt &KnownOne2,
50                                     const TargetData *TD, unsigned Depth) {
51   if (!Add) {
52     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
53       // We know that the top bits of C-X are clear if X contains less bits
54       // than C (i.e. no wrap-around can happen).  For example, 20-X is
55       // positive if we can prove that X is >= 0 and < 16.
56       if (!CLHS->getValue().isNegative()) {
57         unsigned BitWidth = Mask.getBitWidth();
58         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
59         // NLZ can't be BitWidth with no sign bit
60         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
61         llvm::ComputeMaskedBits(Op1, MaskV, KnownZero2, KnownOne2, TD, Depth+1);
62     
63         // If all of the MaskV bits are known to be zero, then we know the
64         // output top bits are zero, because we now know that the output is
65         // from [0-C].
66         if ((KnownZero2 & MaskV) == MaskV) {
67           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
68           // Top bits known zero.
69           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
70         }
71       }
72     }
73   }
74
75   unsigned BitWidth = Mask.getBitWidth();
76
77   // If one of the operands has trailing zeros, then the bits that the
78   // other operand has in those bit positions will be preserved in the
79   // result. For an add, this works with either operand. For a subtract,
80   // this only works if the known zeros are in the right operand.
81   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
82   APInt Mask2 = APInt::getLowBitsSet(BitWidth,
83                                      BitWidth - Mask.countLeadingZeros());
84   llvm::ComputeMaskedBits(Op0, Mask2, LHSKnownZero, LHSKnownOne, TD, Depth+1);
85   assert((LHSKnownZero & LHSKnownOne) == 0 &&
86          "Bits known to be one AND zero?");
87   unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
88
89   llvm::ComputeMaskedBits(Op1, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
90   assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
91   unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
92
93   // Determine which operand has more trailing zeros, and use that
94   // many bits from the other operand.
95   if (LHSKnownZeroOut > RHSKnownZeroOut) {
96     if (Add) {
97       APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
98       KnownZero |= KnownZero2 & Mask;
99       KnownOne  |= KnownOne2 & Mask;
100     } else {
101       // If the known zeros are in the left operand for a subtract,
102       // fall back to the minimum known zeros in both operands.
103       KnownZero |= APInt::getLowBitsSet(BitWidth,
104                                         std::min(LHSKnownZeroOut,
105                                                  RHSKnownZeroOut));
106     }
107   } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
108     APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
109     KnownZero |= LHSKnownZero & Mask;
110     KnownOne  |= LHSKnownOne & Mask;
111   }
112
113   // Are we still trying to solve for the sign bit?
114   if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()) {
115     if (NSW) {
116       if (Add) {
117         // Adding two positive numbers can't wrap into negative
118         if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
119           KnownZero |= APInt::getSignBit(BitWidth);
120         // and adding two negative numbers can't wrap into positive.
121         else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
122           KnownOne |= APInt::getSignBit(BitWidth);
123       } else {
124         // Subtracting a negative number from a positive one can't wrap
125         if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
126           KnownZero |= APInt::getSignBit(BitWidth);
127         // neither can subtracting a positive number from a negative one.
128         else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
129           KnownOne |= APInt::getSignBit(BitWidth);
130       }
131     }
132   }
133 }
134
135 static void ComputeMaskedBitsMul(Value *Op0, Value *Op1, bool NSW,
136                                  const APInt &Mask,
137                                  APInt &KnownZero, APInt &KnownOne,
138                                  APInt &KnownZero2, APInt &KnownOne2,
139                                  const TargetData *TD, unsigned Depth) {
140   unsigned BitWidth = Mask.getBitWidth();
141   APInt Mask2 = APInt::getAllOnesValue(BitWidth);
142   ComputeMaskedBits(Op1, Mask2, KnownZero, KnownOne, TD, Depth+1);
143   ComputeMaskedBits(Op0, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
144   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
145   assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
146
147   bool isKnownNegative = false;
148   bool isKnownNonNegative = false;
149   // If the multiplication is known not to overflow, compute the sign bit.
150   if (Mask.isNegative() && NSW) {
151     if (Op0 == Op1) {
152       // The product of a number with itself is non-negative.
153       isKnownNonNegative = true;
154     } else {
155       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
156       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
157       bool isKnownNegativeOp1 = KnownOne.isNegative();
158       bool isKnownNegativeOp0 = KnownOne2.isNegative();
159       // The product of two numbers with the same sign is non-negative.
160       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
161         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
162       // The product of a negative number and a non-negative number is either
163       // negative or zero.
164       if (!isKnownNonNegative)
165         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
166                            isKnownNonZero(Op0, TD, Depth)) ||
167                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
168                            isKnownNonZero(Op1, TD, Depth));
169     }
170   }
171
172   // If low bits are zero in either operand, output low known-0 bits.
173   // Also compute a conserative estimate for high known-0 bits.
174   // More trickiness is possible, but this is sufficient for the
175   // interesting case of alignment computation.
176   KnownOne.clearAllBits();
177   unsigned TrailZ = KnownZero.countTrailingOnes() +
178                     KnownZero2.countTrailingOnes();
179   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
180                              KnownZero2.countLeadingOnes(),
181                              BitWidth) - BitWidth;
182
183   TrailZ = std::min(TrailZ, BitWidth);
184   LeadZ = std::min(LeadZ, BitWidth);
185   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
186               APInt::getHighBitsSet(BitWidth, LeadZ);
187   KnownZero &= Mask;
188
189   // Only make use of no-wrap flags if we failed to compute the sign bit
190   // directly.  This matters if the multiplication always overflows, in
191   // which case we prefer to follow the result of the direct computation,
192   // though as the program is invoking undefined behaviour we can choose
193   // whatever we like here.
194   if (isKnownNonNegative && !KnownOne.isNegative())
195     KnownZero.setBit(BitWidth - 1);
196   else if (isKnownNegative && !KnownZero.isNegative())
197     KnownOne.setBit(BitWidth - 1);
198 }
199
200 static void computeMaskedBitsLoad(const MDNode &Ranges, const APInt &Mask,
201                                   APInt &KnownZero) {
202   unsigned BitWidth = Mask.getBitWidth();
203   unsigned NumRanges = Ranges.getNumOperands() / 2;
204   assert(NumRanges >= 1);
205
206   // Use the high end of the ranges to find leading zeros.
207   unsigned MinLeadingZeros = BitWidth;
208   for (unsigned i = 0; i < NumRanges; ++i) {
209     ConstantInt *Lower = cast<ConstantInt>(Ranges.getOperand(2*i + 0));
210     ConstantInt *Upper = cast<ConstantInt>(Ranges.getOperand(2*i + 1));
211     ConstantRange Range(Lower->getValue(), Upper->getValue());
212     if (Range.isWrappedSet())
213       MinLeadingZeros = 0; // -1 has no zeros
214     unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
215     MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
216   }
217
218   KnownZero = Mask & APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
219 }
220 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
221 /// known to be either zero or one and return them in the KnownZero/KnownOne
222 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
223 /// processing.
224 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
225 /// we cannot optimize based on the assumption that it is zero without changing
226 /// it to be an explicit zero.  If we don't change it to zero, other code could
227 /// optimized based on the contradictory assumption that it is non-zero.
228 /// Because instcombine aggressively folds operations with undef args anyway,
229 /// this won't lose us code quality.
230 ///
231 /// This function is defined on values with integer type, values with pointer
232 /// type (but only if TD is non-null), and vectors of integers.  In the case
233 /// where V is a vector, the mask, known zero, and known one values are the
234 /// same width as the vector element, and the bit is set only if it is true
235 /// for all of the elements in the vector.
236 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
237                              APInt &KnownZero, APInt &KnownOne,
238                              const TargetData *TD, unsigned Depth) {
239   assert(V && "No Value?");
240   assert(Depth <= MaxDepth && "Limit Search Depth");
241   unsigned BitWidth = Mask.getBitWidth();
242   assert((V->getType()->isIntOrIntVectorTy() ||
243           V->getType()->getScalarType()->isPointerTy()) &&
244          "Not integer or pointer type!");
245   assert((!TD ||
246           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
247          (!V->getType()->isIntOrIntVectorTy() ||
248           V->getType()->getScalarSizeInBits() == BitWidth) &&
249          KnownZero.getBitWidth() == BitWidth &&
250          KnownOne.getBitWidth() == BitWidth &&
251          "V, Mask, KnownOne and KnownZero should have same BitWidth");
252
253   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
254     // We know all of the bits for a constant!
255     KnownOne = CI->getValue() & Mask;
256     KnownZero = ~KnownOne & Mask;
257     return;
258   }
259   // Null and aggregate-zero are all-zeros.
260   if (isa<ConstantPointerNull>(V) ||
261       isa<ConstantAggregateZero>(V)) {
262     KnownOne.clearAllBits();
263     KnownZero = Mask;
264     return;
265   }
266   // Handle a constant vector by taking the intersection of the known bits of
267   // each element.  There is no real need to handle ConstantVector here, because
268   // we don't handle undef in any particularly useful way.
269   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
270     // We know that CDS must be a vector of integers. Take the intersection of
271     // each element.
272     KnownZero.setAllBits(); KnownOne.setAllBits();
273     APInt Elt(KnownZero.getBitWidth(), 0);
274     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
275       Elt = CDS->getElementAsInteger(i);
276       KnownZero &= ~Elt;
277       KnownOne &= Elt;      
278     }
279     return;
280   }
281   
282   // The address of an aligned GlobalValue has trailing zeros.
283   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
284     unsigned Align = GV->getAlignment();
285     if (Align == 0 && TD) {
286       if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
287         Type *ObjectType = GVar->getType()->getElementType();
288         if (ObjectType->isSized()) {
289           // If the object is defined in the current Module, we'll be giving
290           // it the preferred alignment. Otherwise, we have to assume that it
291           // may only have the minimum ABI alignment.
292           if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
293             Align = TD->getPreferredAlignment(GVar);
294           else
295             Align = TD->getABITypeAlignment(ObjectType);
296         }
297       }
298     }
299     if (Align > 0)
300       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
301                                               CountTrailingZeros_32(Align));
302     else
303       KnownZero.clearAllBits();
304     KnownOne.clearAllBits();
305     return;
306   }
307   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
308   // the bits of its aliasee.
309   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
310     if (GA->mayBeOverridden()) {
311       KnownZero.clearAllBits(); KnownOne.clearAllBits();
312     } else {
313       ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
314                         TD, Depth+1);
315     }
316     return;
317   }
318   
319   if (Argument *A = dyn_cast<Argument>(V)) {
320     // Get alignment information off byval arguments if specified in the IR.
321     if (A->hasByValAttr())
322       if (unsigned Align = A->getParamAlignment())
323         KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
324                                                 CountTrailingZeros_32(Align));
325     return;
326   }
327
328   // Start out not knowing anything.
329   KnownZero.clearAllBits(); KnownOne.clearAllBits();
330
331   if (Depth == MaxDepth || Mask == 0)
332     return;  // Limit search depth.
333
334   Operator *I = dyn_cast<Operator>(V);
335   if (!I) return;
336
337   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
338   switch (I->getOpcode()) {
339   default: break;
340   case Instruction::Load:
341     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
342       computeMaskedBitsLoad(*MD, Mask, KnownZero);
343     return;
344   case Instruction::And: {
345     // If either the LHS or the RHS are Zero, the result is zero.
346     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
347     APInt Mask2(Mask & ~KnownZero);
348     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
349                       Depth+1);
350     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
351     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
352     
353     // Output known-1 bits are only known if set in both the LHS & RHS.
354     KnownOne &= KnownOne2;
355     // Output known-0 are known to be clear if zero in either the LHS | RHS.
356     KnownZero |= KnownZero2;
357     return;
358   }
359   case Instruction::Or: {
360     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
361     APInt Mask2(Mask & ~KnownOne);
362     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
363                       Depth+1);
364     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
365     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
366     
367     // Output known-0 bits are only known if clear in both the LHS & RHS.
368     KnownZero &= KnownZero2;
369     // Output known-1 are known to be set if set in either the LHS | RHS.
370     KnownOne |= KnownOne2;
371     return;
372   }
373   case Instruction::Xor: {
374     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
375     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
376                       Depth+1);
377     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
378     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
379     
380     // Output known-0 bits are known if clear or set in both the LHS & RHS.
381     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
382     // Output known-1 are known to be set if set in only one of the LHS, RHS.
383     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
384     KnownZero = KnownZeroOut;
385     return;
386   }
387   case Instruction::Mul: {
388     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
389     ComputeMaskedBitsMul(I->getOperand(0), I->getOperand(1), NSW,
390                          Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
391                          TD, Depth);
392     break;
393   }
394   case Instruction::UDiv: {
395     // For the purposes of computing leading zeros we can conservatively
396     // treat a udiv as a logical right shift by the power of 2 known to
397     // be less than the denominator.
398     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
399     ComputeMaskedBits(I->getOperand(0),
400                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
401     unsigned LeadZ = KnownZero2.countLeadingOnes();
402
403     KnownOne2.clearAllBits();
404     KnownZero2.clearAllBits();
405     ComputeMaskedBits(I->getOperand(1),
406                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
407     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
408     if (RHSUnknownLeadingOnes != BitWidth)
409       LeadZ = std::min(BitWidth,
410                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
411
412     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
413     return;
414   }
415   case Instruction::Select:
416     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
417     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
418                       Depth+1);
419     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
420     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
421
422     // Only known if known in both the LHS and RHS.
423     KnownOne &= KnownOne2;
424     KnownZero &= KnownZero2;
425     return;
426   case Instruction::FPTrunc:
427   case Instruction::FPExt:
428   case Instruction::FPToUI:
429   case Instruction::FPToSI:
430   case Instruction::SIToFP:
431   case Instruction::UIToFP:
432     return; // Can't work with floating point.
433   case Instruction::PtrToInt:
434   case Instruction::IntToPtr:
435     // We can't handle these if we don't know the pointer size.
436     if (!TD) return;
437     // FALL THROUGH and handle them the same as zext/trunc.
438   case Instruction::ZExt:
439   case Instruction::Trunc: {
440     Type *SrcTy = I->getOperand(0)->getType();
441     
442     unsigned SrcBitWidth;
443     // Note that we handle pointer operands here because of inttoptr/ptrtoint
444     // which fall through here.
445     if (SrcTy->isPointerTy())
446       SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
447     else
448       SrcBitWidth = SrcTy->getScalarSizeInBits();
449     
450     APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
451     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
452     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
453     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
454                       Depth+1);
455     KnownZero = KnownZero.zextOrTrunc(BitWidth);
456     KnownOne = KnownOne.zextOrTrunc(BitWidth);
457     // Any top bits are known to be zero.
458     if (BitWidth > SrcBitWidth)
459       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
460     return;
461   }
462   case Instruction::BitCast: {
463     Type *SrcTy = I->getOperand(0)->getType();
464     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
465         // TODO: For now, not handling conversions like:
466         // (bitcast i64 %x to <2 x i32>)
467         !I->getType()->isVectorTy()) {
468       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
469                         Depth+1);
470       return;
471     }
472     break;
473   }
474   case Instruction::SExt: {
475     // Compute the bits in the result that are not present in the input.
476     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
477       
478     APInt MaskIn = Mask.trunc(SrcBitWidth);
479     KnownZero = KnownZero.trunc(SrcBitWidth);
480     KnownOne = KnownOne.trunc(SrcBitWidth);
481     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
482                       Depth+1);
483     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
484     KnownZero = KnownZero.zext(BitWidth);
485     KnownOne = KnownOne.zext(BitWidth);
486
487     // If the sign bit of the input is known set or clear, then we know the
488     // top bits of the result.
489     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
490       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
491     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
492       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
493     return;
494   }
495   case Instruction::Shl:
496     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
497     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
498       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
499       APInt Mask2(Mask.lshr(ShiftAmt));
500       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
501                         Depth+1);
502       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
503       KnownZero <<= ShiftAmt;
504       KnownOne  <<= ShiftAmt;
505       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
506       return;
507     }
508     break;
509   case Instruction::LShr:
510     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
511     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
512       // Compute the new bits that are at the top now.
513       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
514       
515       // Unsigned shift right.
516       APInt Mask2(Mask.shl(ShiftAmt));
517       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
518                         Depth+1);
519       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
520       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
521       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
522       // high bits known zero.
523       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
524       return;
525     }
526     break;
527   case Instruction::AShr:
528     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
529     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
530       // Compute the new bits that are at the top now.
531       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
532       
533       // Signed shift right.
534       APInt Mask2(Mask.shl(ShiftAmt));
535       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
536                         Depth+1);
537       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
538       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
539       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
540         
541       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
542       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
543         KnownZero |= HighBits;
544       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
545         KnownOne |= HighBits;
546       return;
547     }
548     break;
549   case Instruction::Sub: {
550     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
551     ComputeMaskedBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
552                             Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
553                             TD, Depth);
554     break;
555   }
556   case Instruction::Add: {
557     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
558     ComputeMaskedBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
559                             Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
560                             TD, Depth);
561     break;
562   }
563   case Instruction::SRem:
564     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
565       APInt RA = Rem->getValue().abs();
566       if (RA.isPowerOf2()) {
567         APInt LowBits = RA - 1;
568         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
569         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 
570                           Depth+1);
571
572         // The low bits of the first operand are unchanged by the srem.
573         KnownZero = KnownZero2 & LowBits;
574         KnownOne = KnownOne2 & LowBits;
575
576         // If the first operand is non-negative or has all low bits zero, then
577         // the upper bits are all zero.
578         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
579           KnownZero |= ~LowBits;
580
581         // If the first operand is negative and not all low bits are zero, then
582         // the upper bits are all one.
583         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
584           KnownOne |= ~LowBits;
585
586         KnownZero &= Mask;
587         KnownOne &= Mask;
588
589         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
590       }
591     }
592
593     // The sign bit is the LHS's sign bit, except when the result of the
594     // remainder is zero.
595     if (Mask.isNegative() && KnownZero.isNonNegative()) {
596       APInt Mask2 = APInt::getSignBit(BitWidth);
597       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
598       ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
599                         Depth+1);
600       // If it's known zero, our sign bit is also zero.
601       if (LHSKnownZero.isNegative())
602         KnownZero |= LHSKnownZero;
603     }
604
605     break;
606   case Instruction::URem: {
607     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
608       APInt RA = Rem->getValue();
609       if (RA.isPowerOf2()) {
610         APInt LowBits = (RA - 1);
611         APInt Mask2 = LowBits & Mask;
612         KnownZero |= ~LowBits & Mask;
613         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
614                           Depth+1);
615         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
616         break;
617       }
618     }
619
620     // Since the result is less than or equal to either operand, any leading
621     // zero bits in either operand must also exist in the result.
622     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
623     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
624                       TD, Depth+1);
625     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
626                       TD, Depth+1);
627
628     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
629                                 KnownZero2.countLeadingOnes());
630     KnownOne.clearAllBits();
631     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
632     break;
633   }
634
635   case Instruction::Alloca: {
636     AllocaInst *AI = cast<AllocaInst>(V);
637     unsigned Align = AI->getAlignment();
638     if (Align == 0 && TD)
639       Align = TD->getABITypeAlignment(AI->getType()->getElementType());
640     
641     if (Align > 0)
642       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
643                                               CountTrailingZeros_32(Align));
644     break;
645   }
646   case Instruction::GetElementPtr: {
647     // Analyze all of the subscripts of this getelementptr instruction
648     // to determine if we can prove known low zero bits.
649     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
650     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
651     ComputeMaskedBits(I->getOperand(0), LocalMask,
652                       LocalKnownZero, LocalKnownOne, TD, Depth+1);
653     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
654
655     gep_type_iterator GTI = gep_type_begin(I);
656     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
657       Value *Index = I->getOperand(i);
658       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
659         // Handle struct member offset arithmetic.
660         if (!TD) return;
661         const StructLayout *SL = TD->getStructLayout(STy);
662         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
663         uint64_t Offset = SL->getElementOffset(Idx);
664         TrailZ = std::min(TrailZ,
665                           CountTrailingZeros_64(Offset));
666       } else {
667         // Handle array index arithmetic.
668         Type *IndexedTy = GTI.getIndexedType();
669         if (!IndexedTy->isSized()) return;
670         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
671         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
672         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
673         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
674         ComputeMaskedBits(Index, LocalMask,
675                           LocalKnownZero, LocalKnownOne, TD, Depth+1);
676         TrailZ = std::min(TrailZ,
677                           unsigned(CountTrailingZeros_64(TypeSize) +
678                                    LocalKnownZero.countTrailingOnes()));
679       }
680     }
681     
682     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
683     break;
684   }
685   case Instruction::PHI: {
686     PHINode *P = cast<PHINode>(I);
687     // Handle the case of a simple two-predecessor recurrence PHI.
688     // There's a lot more that could theoretically be done here, but
689     // this is sufficient to catch some interesting cases.
690     if (P->getNumIncomingValues() == 2) {
691       for (unsigned i = 0; i != 2; ++i) {
692         Value *L = P->getIncomingValue(i);
693         Value *R = P->getIncomingValue(!i);
694         Operator *LU = dyn_cast<Operator>(L);
695         if (!LU)
696           continue;
697         unsigned Opcode = LU->getOpcode();
698         // Check for operations that have the property that if
699         // both their operands have low zero bits, the result
700         // will have low zero bits.
701         if (Opcode == Instruction::Add ||
702             Opcode == Instruction::Sub ||
703             Opcode == Instruction::And ||
704             Opcode == Instruction::Or ||
705             Opcode == Instruction::Mul) {
706           Value *LL = LU->getOperand(0);
707           Value *LR = LU->getOperand(1);
708           // Find a recurrence.
709           if (LL == I)
710             L = LR;
711           else if (LR == I)
712             L = LL;
713           else
714             break;
715           // Ok, we have a PHI of the form L op= R. Check for low
716           // zero bits.
717           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
718           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
719           Mask2 = APInt::getLowBitsSet(BitWidth,
720                                        KnownZero2.countTrailingOnes());
721
722           // We need to take the minimum number of known bits
723           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
724           ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
725
726           KnownZero = Mask &
727                       APInt::getLowBitsSet(BitWidth,
728                                            std::min(KnownZero2.countTrailingOnes(),
729                                                     KnownZero3.countTrailingOnes()));
730           break;
731         }
732       }
733     }
734
735     // Unreachable blocks may have zero-operand PHI nodes.
736     if (P->getNumIncomingValues() == 0)
737       return;
738
739     // Otherwise take the unions of the known bit sets of the operands,
740     // taking conservative care to avoid excessive recursion.
741     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
742       // Skip if every incoming value references to ourself.
743       if (P->hasConstantValue() == P)
744         break;
745
746       KnownZero = Mask;
747       KnownOne = Mask;
748       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
749         // Skip direct self references.
750         if (P->getIncomingValue(i) == P) continue;
751
752         KnownZero2 = APInt(BitWidth, 0);
753         KnownOne2 = APInt(BitWidth, 0);
754         // Recurse, but cap the recursion to one level, because we don't
755         // want to waste time spinning around in loops.
756         ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
757                           KnownZero2, KnownOne2, TD, MaxDepth-1);
758         KnownZero &= KnownZero2;
759         KnownOne &= KnownOne2;
760         // If all bits have been ruled out, there's no need to check
761         // more operands.
762         if (!KnownZero && !KnownOne)
763           break;
764       }
765     }
766     break;
767   }
768   case Instruction::Call:
769     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
770       switch (II->getIntrinsicID()) {
771       default: break;
772       case Intrinsic::ctlz:
773       case Intrinsic::cttz: {
774         unsigned LowBits = Log2_32(BitWidth)+1;
775         // If this call is undefined for 0, the result will be less than 2^n.
776         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
777           LowBits -= 1;
778         KnownZero = Mask & APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
779         break;
780       }
781       case Intrinsic::ctpop: {
782         unsigned LowBits = Log2_32(BitWidth)+1;
783         KnownZero = Mask & APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
784         break;
785       }
786       case Intrinsic::x86_sse42_crc32_64_8:
787       case Intrinsic::x86_sse42_crc32_64_64:
788         KnownZero = Mask & APInt::getHighBitsSet(64, 32);
789         break;
790       }
791     }
792     break;
793   case Instruction::ExtractValue:
794     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
795       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
796       if (EVI->getNumIndices() != 1) break;
797       if (EVI->getIndices()[0] == 0) {
798         switch (II->getIntrinsicID()) {
799         default: break;
800         case Intrinsic::uadd_with_overflow:
801         case Intrinsic::sadd_with_overflow:
802           ComputeMaskedBitsAddSub(true, II->getArgOperand(0),
803                                   II->getArgOperand(1), false, Mask,
804                                   KnownZero, KnownOne, KnownZero2, KnownOne2,
805                                   TD, Depth);
806           break;
807         case Intrinsic::usub_with_overflow:
808         case Intrinsic::ssub_with_overflow:
809           ComputeMaskedBitsAddSub(false, II->getArgOperand(0),
810                                   II->getArgOperand(1), false, Mask,
811                                   KnownZero, KnownOne, KnownZero2, KnownOne2,
812                                   TD, Depth);
813           break;
814         case Intrinsic::umul_with_overflow:
815         case Intrinsic::smul_with_overflow:
816           ComputeMaskedBitsMul(II->getArgOperand(0), II->getArgOperand(1),
817                                false, Mask, KnownZero, KnownOne,
818                                KnownZero2, KnownOne2, TD, Depth);
819           break;
820         }
821       }
822     }
823   }
824 }
825
826 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
827 /// one.  Convenience wrapper around ComputeMaskedBits.
828 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
829                           const TargetData *TD, unsigned Depth) {
830   unsigned BitWidth = getBitWidth(V->getType(), TD);
831   if (!BitWidth) {
832     KnownZero = false;
833     KnownOne = false;
834     return;
835   }
836   APInt ZeroBits(BitWidth, 0);
837   APInt OneBits(BitWidth, 0);
838   ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
839                     Depth);
840   KnownOne = OneBits[BitWidth - 1];
841   KnownZero = ZeroBits[BitWidth - 1];
842 }
843
844 /// isPowerOfTwo - Return true if the given value is known to have exactly one
845 /// bit set when defined. For vectors return true if every element is known to
846 /// be a power of two when defined.  Supports values with integer or pointer
847 /// types and vectors of integers.
848 bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero,
849                         unsigned Depth) {
850   if (Constant *C = dyn_cast<Constant>(V)) {
851     if (C->isNullValue())
852       return OrZero;
853     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
854       return CI->getValue().isPowerOf2();
855     // TODO: Handle vector constants.
856   }
857
858   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
859   // it is shifted off the end then the result is undefined.
860   if (match(V, m_Shl(m_One(), m_Value())))
861     return true;
862
863   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
864   // bottom.  If it is shifted off the bottom then the result is undefined.
865   if (match(V, m_LShr(m_SignBit(), m_Value())))
866     return true;
867
868   // The remaining tests are all recursive, so bail out if we hit the limit.
869   if (Depth++ == MaxDepth)
870     return false;
871
872   Value *X = 0, *Y = 0;
873   // A shift of a power of two is a power of two or zero.
874   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
875                  match(V, m_Shr(m_Value(X), m_Value()))))
876     return isPowerOfTwo(X, TD, /*OrZero*/true, Depth);
877
878   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
879     return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth);
880
881   if (SelectInst *SI = dyn_cast<SelectInst>(V))
882     return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) &&
883       isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth);
884
885   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
886     // A power of two and'd with anything is a power of two or zero.
887     if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) ||
888         isPowerOfTwo(Y, TD, /*OrZero*/true, Depth))
889       return true;
890     // X & (-X) is always a power of two or zero.
891     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
892       return true;
893     return false;
894   }
895
896   // An exact divide or right shift can only shift off zero bits, so the result
897   // is a power of two only if the first operand is a power of two and not
898   // copying a sign bit (sdiv int_min, 2).
899   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
900       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
901     return isPowerOfTwo(cast<Operator>(V)->getOperand(0), TD, OrZero, Depth);
902   }
903
904   return false;
905 }
906
907 /// isKnownNonZero - Return true if the given value is known to be non-zero
908 /// when defined.  For vectors return true if every element is known to be
909 /// non-zero when defined.  Supports values with integer or pointer type and
910 /// vectors of integers.
911 bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
912   if (Constant *C = dyn_cast<Constant>(V)) {
913     if (C->isNullValue())
914       return false;
915     if (isa<ConstantInt>(C))
916       // Must be non-zero due to null test above.
917       return true;
918     // TODO: Handle vectors
919     return false;
920   }
921
922   // The remaining tests are all recursive, so bail out if we hit the limit.
923   if (Depth++ >= MaxDepth)
924     return false;
925
926   unsigned BitWidth = getBitWidth(V->getType(), TD);
927
928   // X | Y != 0 if X != 0 or Y != 0.
929   Value *X = 0, *Y = 0;
930   if (match(V, m_Or(m_Value(X), m_Value(Y))))
931     return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
932
933   // ext X != 0 if X != 0.
934   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
935     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
936
937   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
938   // if the lowest bit is shifted off the end.
939   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
940     // shl nuw can't remove any non-zero bits.
941     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
942     if (BO->hasNoUnsignedWrap())
943       return isKnownNonZero(X, TD, Depth);
944
945     APInt KnownZero(BitWidth, 0);
946     APInt KnownOne(BitWidth, 0);
947     ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
948     if (KnownOne[0])
949       return true;
950   }
951   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
952   // defined if the sign bit is shifted off the end.
953   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
954     // shr exact can only shift out zero bits.
955     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
956     if (BO->isExact())
957       return isKnownNonZero(X, TD, Depth);
958
959     bool XKnownNonNegative, XKnownNegative;
960     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
961     if (XKnownNegative)
962       return true;
963   }
964   // div exact can only produce a zero if the dividend is zero.
965   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
966     return isKnownNonZero(X, TD, Depth);
967   }
968   // X + Y.
969   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
970     bool XKnownNonNegative, XKnownNegative;
971     bool YKnownNonNegative, YKnownNegative;
972     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
973     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
974
975     // If X and Y are both non-negative (as signed values) then their sum is not
976     // zero unless both X and Y are zero.
977     if (XKnownNonNegative && YKnownNonNegative)
978       if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
979         return true;
980
981     // If X and Y are both negative (as signed values) then their sum is not
982     // zero unless both X and Y equal INT_MIN.
983     if (BitWidth && XKnownNegative && YKnownNegative) {
984       APInt KnownZero(BitWidth, 0);
985       APInt KnownOne(BitWidth, 0);
986       APInt Mask = APInt::getSignedMaxValue(BitWidth);
987       // The sign bit of X is set.  If some other bit is set then X is not equal
988       // to INT_MIN.
989       ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
990       if ((KnownOne & Mask) != 0)
991         return true;
992       // The sign bit of Y is set.  If some other bit is set then Y is not equal
993       // to INT_MIN.
994       ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
995       if ((KnownOne & Mask) != 0)
996         return true;
997     }
998
999     // The sum of a non-negative number and a power of two is not zero.
1000     if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth))
1001       return true;
1002     if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth))
1003       return true;
1004   }
1005   // X * Y.
1006   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1007     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1008     // If X and Y are non-zero then so is X * Y as long as the multiplication
1009     // does not overflow.
1010     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1011         isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
1012       return true;
1013   }
1014   // (C ? X : Y) != 0 if X != 0 and Y != 0.
1015   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1016     if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
1017         isKnownNonZero(SI->getFalseValue(), TD, Depth))
1018       return true;
1019   }
1020
1021   if (!BitWidth) return false;
1022   APInt KnownZero(BitWidth, 0);
1023   APInt KnownOne(BitWidth, 0);
1024   ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
1025                     TD, Depth);
1026   return KnownOne != 0;
1027 }
1028
1029 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1030 /// this predicate to simplify operations downstream.  Mask is known to be zero
1031 /// for bits that V cannot have.
1032 ///
1033 /// This function is defined on values with integer type, values with pointer
1034 /// type (but only if TD is non-null), and vectors of integers.  In the case
1035 /// where V is a vector, the mask, known zero, and known one values are the
1036 /// same width as the vector element, and the bit is set only if it is true
1037 /// for all of the elements in the vector.
1038 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
1039                              const TargetData *TD, unsigned Depth) {
1040   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1041   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1042   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1043   return (KnownZero & Mask) == Mask;
1044 }
1045
1046
1047
1048 /// ComputeNumSignBits - Return the number of times the sign bit of the
1049 /// register is replicated into the other bits.  We know that at least 1 bit
1050 /// is always equal to the sign bit (itself), but other cases can give us
1051 /// information.  For example, immediately after an "ashr X, 2", we know that
1052 /// the top 3 bits are all equal to each other, so we return 3.
1053 ///
1054 /// 'Op' must have a scalar integer type.
1055 ///
1056 unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
1057                                   unsigned Depth) {
1058   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
1059          "ComputeNumSignBits requires a TargetData object to operate "
1060          "on non-integer values!");
1061   Type *Ty = V->getType();
1062   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
1063                          Ty->getScalarSizeInBits();
1064   unsigned Tmp, Tmp2;
1065   unsigned FirstAnswer = 1;
1066
1067   // Note that ConstantInt is handled by the general ComputeMaskedBits case
1068   // below.
1069
1070   if (Depth == 6)
1071     return 1;  // Limit search depth.
1072   
1073   Operator *U = dyn_cast<Operator>(V);
1074   switch (Operator::getOpcode(V)) {
1075   default: break;
1076   case Instruction::SExt:
1077     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
1078     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
1079     
1080   case Instruction::AShr: {
1081     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1082     // ashr X, C   -> adds C sign bits.  Vectors too.
1083     const APInt *ShAmt;
1084     if (match(U->getOperand(1), m_APInt(ShAmt))) {
1085       Tmp += ShAmt->getZExtValue();
1086       if (Tmp > TyBits) Tmp = TyBits;
1087     }
1088     return Tmp;
1089   }
1090   case Instruction::Shl: {
1091     const APInt *ShAmt;
1092     if (match(U->getOperand(1), m_APInt(ShAmt))) {
1093       // shl destroys sign bits.
1094       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1095       Tmp2 = ShAmt->getZExtValue();
1096       if (Tmp2 >= TyBits ||      // Bad shift.
1097           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
1098       return Tmp - Tmp2;
1099     }
1100     break;
1101   }
1102   case Instruction::And:
1103   case Instruction::Or:
1104   case Instruction::Xor:    // NOT is handled here.
1105     // Logical binary ops preserve the number of sign bits at the worst.
1106     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1107     if (Tmp != 1) {
1108       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1109       FirstAnswer = std::min(Tmp, Tmp2);
1110       // We computed what we know about the sign bits as our first
1111       // answer. Now proceed to the generic code that uses
1112       // ComputeMaskedBits, and pick whichever answer is better.
1113     }
1114     break;
1115
1116   case Instruction::Select:
1117     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1118     if (Tmp == 1) return 1;  // Early out.
1119     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1120     return std::min(Tmp, Tmp2);
1121     
1122   case Instruction::Add:
1123     // Add can have at most one carry bit.  Thus we know that the output
1124     // is, at worst, one more bit than the inputs.
1125     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1126     if (Tmp == 1) return 1;  // Early out.
1127       
1128     // Special case decrementing a value (ADD X, -1):
1129     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
1130       if (CRHS->isAllOnesValue()) {
1131         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1132         APInt Mask = APInt::getAllOnesValue(TyBits);
1133         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
1134                           Depth+1);
1135         
1136         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1137         // sign bits set.
1138         if ((KnownZero | APInt(TyBits, 1)) == Mask)
1139           return TyBits;
1140         
1141         // If we are subtracting one from a positive number, there is no carry
1142         // out of the result.
1143         if (KnownZero.isNegative())
1144           return Tmp;
1145       }
1146       
1147     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1148     if (Tmp2 == 1) return 1;
1149     return std::min(Tmp, Tmp2)-1;
1150     
1151   case Instruction::Sub:
1152     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1153     if (Tmp2 == 1) return 1;
1154       
1155     // Handle NEG.
1156     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1157       if (CLHS->isNullValue()) {
1158         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1159         APInt Mask = APInt::getAllOnesValue(TyBits);
1160         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, 
1161                           TD, Depth+1);
1162         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1163         // sign bits set.
1164         if ((KnownZero | APInt(TyBits, 1)) == Mask)
1165           return TyBits;
1166         
1167         // If the input is known to be positive (the sign bit is known clear),
1168         // the output of the NEG has the same number of sign bits as the input.
1169         if (KnownZero.isNegative())
1170           return Tmp2;
1171         
1172         // Otherwise, we treat this like a SUB.
1173       }
1174     
1175     // Sub can have at most one carry bit.  Thus we know that the output
1176     // is, at worst, one more bit than the inputs.
1177     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1178     if (Tmp == 1) return 1;  // Early out.
1179     return std::min(Tmp, Tmp2)-1;
1180       
1181   case Instruction::PHI: {
1182     PHINode *PN = cast<PHINode>(U);
1183     // Don't analyze large in-degree PHIs.
1184     if (PN->getNumIncomingValues() > 4) break;
1185     
1186     // Take the minimum of all incoming values.  This can't infinitely loop
1187     // because of our depth threshold.
1188     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1189     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1190       if (Tmp == 1) return Tmp;
1191       Tmp = std::min(Tmp,
1192                      ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
1193     }
1194     return Tmp;
1195   }
1196
1197   case Instruction::Trunc:
1198     // FIXME: it's tricky to do anything useful for this, but it is an important
1199     // case for targets like X86.
1200     break;
1201   }
1202   
1203   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1204   // use this information.
1205   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1206   APInt Mask = APInt::getAllOnesValue(TyBits);
1207   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1208   
1209   if (KnownZero.isNegative()) {        // sign bit is 0
1210     Mask = KnownZero;
1211   } else if (KnownOne.isNegative()) {  // sign bit is 1;
1212     Mask = KnownOne;
1213   } else {
1214     // Nothing known.
1215     return FirstAnswer;
1216   }
1217   
1218   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1219   // the number of identical bits in the top of the input value.
1220   Mask = ~Mask;
1221   Mask <<= Mask.getBitWidth()-TyBits;
1222   // Return # leading zeros.  We use 'min' here in case Val was zero before
1223   // shifting.  We don't want to return '64' as for an i32 "0".
1224   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1225 }
1226
1227 /// ComputeMultiple - This function computes the integer multiple of Base that
1228 /// equals V.  If successful, it returns true and returns the multiple in
1229 /// Multiple.  If unsuccessful, it returns false. It looks
1230 /// through SExt instructions only if LookThroughSExt is true.
1231 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
1232                            bool LookThroughSExt, unsigned Depth) {
1233   const unsigned MaxDepth = 6;
1234
1235   assert(V && "No Value?");
1236   assert(Depth <= MaxDepth && "Limit Search Depth");
1237   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
1238
1239   Type *T = V->getType();
1240
1241   ConstantInt *CI = dyn_cast<ConstantInt>(V);
1242
1243   if (Base == 0)
1244     return false;
1245     
1246   if (Base == 1) {
1247     Multiple = V;
1248     return true;
1249   }
1250
1251   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1252   Constant *BaseVal = ConstantInt::get(T, Base);
1253   if (CO && CO == BaseVal) {
1254     // Multiple is 1.
1255     Multiple = ConstantInt::get(T, 1);
1256     return true;
1257   }
1258
1259   if (CI && CI->getZExtValue() % Base == 0) {
1260     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1261     return true;  
1262   }
1263   
1264   if (Depth == MaxDepth) return false;  // Limit search depth.
1265         
1266   Operator *I = dyn_cast<Operator>(V);
1267   if (!I) return false;
1268
1269   switch (I->getOpcode()) {
1270   default: break;
1271   case Instruction::SExt:
1272     if (!LookThroughSExt) return false;
1273     // otherwise fall through to ZExt
1274   case Instruction::ZExt:
1275     return ComputeMultiple(I->getOperand(0), Base, Multiple,
1276                            LookThroughSExt, Depth+1);
1277   case Instruction::Shl:
1278   case Instruction::Mul: {
1279     Value *Op0 = I->getOperand(0);
1280     Value *Op1 = I->getOperand(1);
1281
1282     if (I->getOpcode() == Instruction::Shl) {
1283       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1284       if (!Op1CI) return false;
1285       // Turn Op0 << Op1 into Op0 * 2^Op1
1286       APInt Op1Int = Op1CI->getValue();
1287       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
1288       APInt API(Op1Int.getBitWidth(), 0);
1289       API.setBit(BitToSet);
1290       Op1 = ConstantInt::get(V->getContext(), API);
1291     }
1292
1293     Value *Mul0 = NULL;
1294     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1295       if (Constant *Op1C = dyn_cast<Constant>(Op1))
1296         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1297           if (Op1C->getType()->getPrimitiveSizeInBits() < 
1298               MulC->getType()->getPrimitiveSizeInBits())
1299             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1300           if (Op1C->getType()->getPrimitiveSizeInBits() > 
1301               MulC->getType()->getPrimitiveSizeInBits())
1302             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1303           
1304           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1305           Multiple = ConstantExpr::getMul(MulC, Op1C);
1306           return true;
1307         }
1308
1309       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1310         if (Mul0CI->getValue() == 1) {
1311           // V == Base * Op1, so return Op1
1312           Multiple = Op1;
1313           return true;
1314         }
1315     }
1316
1317     Value *Mul1 = NULL;
1318     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1319       if (Constant *Op0C = dyn_cast<Constant>(Op0))
1320         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1321           if (Op0C->getType()->getPrimitiveSizeInBits() < 
1322               MulC->getType()->getPrimitiveSizeInBits())
1323             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1324           if (Op0C->getType()->getPrimitiveSizeInBits() > 
1325               MulC->getType()->getPrimitiveSizeInBits())
1326             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1327           
1328           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1329           Multiple = ConstantExpr::getMul(MulC, Op0C);
1330           return true;
1331         }
1332
1333       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1334         if (Mul1CI->getValue() == 1) {
1335           // V == Base * Op0, so return Op0
1336           Multiple = Op0;
1337           return true;
1338         }
1339     }
1340   }
1341   }
1342
1343   // We could not determine if V is a multiple of Base.
1344   return false;
1345 }
1346
1347 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
1348 /// value is never equal to -0.0.
1349 ///
1350 /// NOTE: this function will need to be revisited when we support non-default
1351 /// rounding modes!
1352 ///
1353 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1354   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1355     return !CFP->getValueAPF().isNegZero();
1356   
1357   if (Depth == 6)
1358     return 1;  // Limit search depth.
1359
1360   const Operator *I = dyn_cast<Operator>(V);
1361   if (I == 0) return false;
1362   
1363   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1364   if (I->getOpcode() == Instruction::FAdd &&
1365       isa<ConstantFP>(I->getOperand(1)) && 
1366       cast<ConstantFP>(I->getOperand(1))->isNullValue())
1367     return true;
1368     
1369   // sitofp and uitofp turn into +0.0 for zero.
1370   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1371     return true;
1372   
1373   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1374     // sqrt(-0.0) = -0.0, no other negative results are possible.
1375     if (II->getIntrinsicID() == Intrinsic::sqrt)
1376       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
1377   
1378   if (const CallInst *CI = dyn_cast<CallInst>(I))
1379     if (const Function *F = CI->getCalledFunction()) {
1380       if (F->isDeclaration()) {
1381         // abs(x) != -0.0
1382         if (F->getName() == "abs") return true;
1383         // fabs[lf](x) != -0.0
1384         if (F->getName() == "fabs") return true;
1385         if (F->getName() == "fabsf") return true;
1386         if (F->getName() == "fabsl") return true;
1387         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1388             F->getName() == "sqrtl")
1389           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
1390       }
1391     }
1392   
1393   return false;
1394 }
1395
1396 /// isBytewiseValue - If the specified value can be set by repeating the same
1397 /// byte in memory, return the i8 value that it is represented with.  This is
1398 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1399 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
1400 /// byte store (e.g. i16 0x1234), return null.
1401 Value *llvm::isBytewiseValue(Value *V) {
1402   // All byte-wide stores are splatable, even of arbitrary variables.
1403   if (V->getType()->isIntegerTy(8)) return V;
1404
1405   // Handle 'null' ConstantArrayZero etc.
1406   if (Constant *C = dyn_cast<Constant>(V))
1407     if (C->isNullValue())
1408       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
1409   
1410   // Constant float and double values can be handled as integer values if the
1411   // corresponding integer value is "byteable".  An important case is 0.0. 
1412   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1413     if (CFP->getType()->isFloatTy())
1414       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1415     if (CFP->getType()->isDoubleTy())
1416       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1417     // Don't handle long double formats, which have strange constraints.
1418   }
1419   
1420   // We can handle constant integers that are power of two in size and a 
1421   // multiple of 8 bits.
1422   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1423     unsigned Width = CI->getBitWidth();
1424     if (isPowerOf2_32(Width) && Width > 8) {
1425       // We can handle this value if the recursive binary decomposition is the
1426       // same at all levels.
1427       APInt Val = CI->getValue();
1428       APInt Val2;
1429       while (Val.getBitWidth() != 8) {
1430         unsigned NextWidth = Val.getBitWidth()/2;
1431         Val2  = Val.lshr(NextWidth);
1432         Val2 = Val2.trunc(Val.getBitWidth()/2);
1433         Val = Val.trunc(Val.getBitWidth()/2);
1434         
1435         // If the top/bottom halves aren't the same, reject it.
1436         if (Val != Val2)
1437           return 0;
1438       }
1439       return ConstantInt::get(V->getContext(), Val);
1440     }
1441   }
1442   
1443   // A ConstantDataArray/Vector is splatable if all its members are equal and
1444   // also splatable.
1445   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
1446     Value *Elt = CA->getElementAsConstant(0);
1447     Value *Val = isBytewiseValue(Elt);
1448     if (!Val)
1449       return 0;
1450     
1451     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
1452       if (CA->getElementAsConstant(I) != Elt)
1453         return 0;
1454     
1455     return Val;
1456   }
1457
1458   // Conceptually, we could handle things like:
1459   //   %a = zext i8 %X to i16
1460   //   %b = shl i16 %a, 8
1461   //   %c = or i16 %a, %b
1462   // but until there is an example that actually needs this, it doesn't seem
1463   // worth worrying about.
1464   return 0;
1465 }
1466
1467
1468 // This is the recursive version of BuildSubAggregate. It takes a few different
1469 // arguments. Idxs is the index within the nested struct From that we are
1470 // looking at now (which is of type IndexedType). IdxSkip is the number of
1471 // indices from Idxs that should be left out when inserting into the resulting
1472 // struct. To is the result struct built so far, new insertvalue instructions
1473 // build on that.
1474 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
1475                                 SmallVector<unsigned, 10> &Idxs,
1476                                 unsigned IdxSkip,
1477                                 Instruction *InsertBefore) {
1478   llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
1479   if (STy) {
1480     // Save the original To argument so we can modify it
1481     Value *OrigTo = To;
1482     // General case, the type indexed by Idxs is a struct
1483     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1484       // Process each struct element recursively
1485       Idxs.push_back(i);
1486       Value *PrevTo = To;
1487       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
1488                              InsertBefore);
1489       Idxs.pop_back();
1490       if (!To) {
1491         // Couldn't find any inserted value for this index? Cleanup
1492         while (PrevTo != OrigTo) {
1493           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1494           PrevTo = Del->getAggregateOperand();
1495           Del->eraseFromParent();
1496         }
1497         // Stop processing elements
1498         break;
1499       }
1500     }
1501     // If we successfully found a value for each of our subaggregates
1502     if (To)
1503       return To;
1504   }
1505   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1506   // the struct's elements had a value that was inserted directly. In the latter
1507   // case, perhaps we can't determine each of the subelements individually, but
1508   // we might be able to find the complete struct somewhere.
1509   
1510   // Find the value that is at that particular spot
1511   Value *V = FindInsertedValue(From, Idxs);
1512
1513   if (!V)
1514     return NULL;
1515
1516   // Insert the value in the new (sub) aggregrate
1517   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
1518                                        "tmp", InsertBefore);
1519 }
1520
1521 // This helper takes a nested struct and extracts a part of it (which is again a
1522 // struct) into a new value. For example, given the struct:
1523 // { a, { b, { c, d }, e } }
1524 // and the indices "1, 1" this returns
1525 // { c, d }.
1526 //
1527 // It does this by inserting an insertvalue for each element in the resulting
1528 // struct, as opposed to just inserting a single struct. This will only work if
1529 // each of the elements of the substruct are known (ie, inserted into From by an
1530 // insertvalue instruction somewhere).
1531 //
1532 // All inserted insertvalue instructions are inserted before InsertBefore
1533 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
1534                                 Instruction *InsertBefore) {
1535   assert(InsertBefore && "Must have someplace to insert!");
1536   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1537                                                              idx_range);
1538   Value *To = UndefValue::get(IndexedType);
1539   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
1540   unsigned IdxSkip = Idxs.size();
1541
1542   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
1543 }
1544
1545 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1546 /// the scalar value indexed is already around as a register, for example if it
1547 /// were inserted directly into the aggregrate.
1548 ///
1549 /// If InsertBefore is not null, this function will duplicate (modified)
1550 /// insertvalues when a part of a nested struct is extracted.
1551 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1552                                Instruction *InsertBefore) {
1553   // Nothing to index? Just return V then (this is useful at the end of our
1554   // recursion).
1555   if (idx_range.empty())
1556     return V;
1557   // We have indices, so V should have an indexable type.
1558   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
1559          "Not looking at a struct or array?");
1560   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
1561          "Invalid indices for type?");
1562
1563   if (Constant *C = dyn_cast<Constant>(V)) {
1564     C = C->getAggregateElement(idx_range[0]);
1565     if (C == 0) return 0;
1566     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
1567   }
1568     
1569   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1570     // Loop the indices for the insertvalue instruction in parallel with the
1571     // requested indices
1572     const unsigned *req_idx = idx_range.begin();
1573     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1574          i != e; ++i, ++req_idx) {
1575       if (req_idx == idx_range.end()) {
1576         // We can't handle this without inserting insertvalues
1577         if (!InsertBefore)
1578           return 0;
1579
1580         // The requested index identifies a part of a nested aggregate. Handle
1581         // this specially. For example,
1582         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1583         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1584         // %C = extractvalue {i32, { i32, i32 } } %B, 1
1585         // This can be changed into
1586         // %A = insertvalue {i32, i32 } undef, i32 10, 0
1587         // %C = insertvalue {i32, i32 } %A, i32 11, 1
1588         // which allows the unused 0,0 element from the nested struct to be
1589         // removed.
1590         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
1591                                  InsertBefore);
1592       }
1593       
1594       // This insert value inserts something else than what we are looking for.
1595       // See if the (aggregrate) value inserted into has the value we are
1596       // looking for, then.
1597       if (*req_idx != *i)
1598         return FindInsertedValue(I->getAggregateOperand(), idx_range,
1599                                  InsertBefore);
1600     }
1601     // If we end up here, the indices of the insertvalue match with those
1602     // requested (though possibly only partially). Now we recursively look at
1603     // the inserted value, passing any remaining indices.
1604     return FindInsertedValue(I->getInsertedValueOperand(),
1605                              makeArrayRef(req_idx, idx_range.end()),
1606                              InsertBefore);
1607   }
1608   
1609   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1610     // If we're extracting a value from an aggregrate that was extracted from
1611     // something else, we can extract from that something else directly instead.
1612     // However, we will need to chain I's indices with the requested indices.
1613    
1614     // Calculate the number of indices required 
1615     unsigned size = I->getNumIndices() + idx_range.size();
1616     // Allocate some space to put the new indices in
1617     SmallVector<unsigned, 5> Idxs;
1618     Idxs.reserve(size);
1619     // Add indices from the extract value instruction
1620     Idxs.append(I->idx_begin(), I->idx_end());
1621     
1622     // Add requested indices
1623     Idxs.append(idx_range.begin(), idx_range.end());
1624
1625     assert(Idxs.size() == size 
1626            && "Number of indices added not correct?");
1627     
1628     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
1629   }
1630   // Otherwise, we don't know (such as, extracting from a function return value
1631   // or load instruction)
1632   return 0;
1633 }
1634
1635 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1636 /// it can be expressed as a base pointer plus a constant offset.  Return the
1637 /// base and offset to the caller.
1638 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1639                                               const TargetData &TD) {
1640   Operator *PtrOp = dyn_cast<Operator>(Ptr);
1641   if (PtrOp == 0 || Ptr->getType()->isVectorTy())
1642     return Ptr;
1643   
1644   // Just look through bitcasts.
1645   if (PtrOp->getOpcode() == Instruction::BitCast)
1646     return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1647   
1648   // If this is a GEP with constant indices, we can look through it.
1649   GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1650   if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1651   
1652   gep_type_iterator GTI = gep_type_begin(GEP);
1653   for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1654        ++I, ++GTI) {
1655     ConstantInt *OpC = cast<ConstantInt>(*I);
1656     if (OpC->isZero()) continue;
1657     
1658     // Handle a struct and array indices which add their offset to the pointer.
1659     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1660       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1661     } else {
1662       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1663       Offset += OpC->getSExtValue()*Size;
1664     }
1665   }
1666   
1667   // Re-sign extend from the pointer size if needed to get overflow edge cases
1668   // right.
1669   unsigned PtrSize = TD.getPointerSizeInBits();
1670   if (PtrSize < 64)
1671     Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1672   
1673   return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1674 }
1675
1676
1677 /// getConstantStringInfo - This function computes the length of a
1678 /// null-terminated C string pointed to by V.  If successful, it returns true
1679 /// and returns the string in Str.  If unsuccessful, it returns false.
1680 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
1681                                  uint64_t Offset, bool TrimAtNul) {
1682   assert(V);
1683
1684   // Look through bitcast instructions and geps.
1685   V = V->stripPointerCasts();
1686   
1687   // If the value is a GEP instructionor  constant expression, treat it as an
1688   // offset.
1689   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1690     // Make sure the GEP has exactly three arguments.
1691     if (GEP->getNumOperands() != 3)
1692       return false;
1693     
1694     // Make sure the index-ee is a pointer to array of i8.
1695     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1696     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1697     if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
1698       return false;
1699     
1700     // Check to make sure that the first operand of the GEP is an integer and
1701     // has value 0 so that we are sure we're indexing into the initializer.
1702     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1703     if (FirstIdx == 0 || !FirstIdx->isZero())
1704       return false;
1705     
1706     // If the second index isn't a ConstantInt, then this is a variable index
1707     // into the array.  If this occurs, we can't say anything meaningful about
1708     // the string.
1709     uint64_t StartIdx = 0;
1710     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1711       StartIdx = CI->getZExtValue();
1712     else
1713       return false;
1714     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
1715   }
1716
1717   // The GEP instruction, constant or instruction, must reference a global
1718   // variable that is a constant and is initialized. The referenced constant
1719   // initializer is the array that we'll use for optimization.
1720   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
1721   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1722     return false;
1723
1724   // Handle the all-zeros case
1725   if (GV->getInitializer()->isNullValue()) {
1726     // This is a degenerate case. The initializer is constant zero so the
1727     // length of the string must be zero.
1728     Str = "";
1729     return true;
1730   }
1731   
1732   // Must be a Constant Array
1733   const ConstantDataArray *Array =
1734     dyn_cast<ConstantDataArray>(GV->getInitializer());
1735   if (Array == 0 || !Array->isString())
1736     return false;
1737   
1738   // Get the number of elements in the array
1739   uint64_t NumElts = Array->getType()->getArrayNumElements();
1740
1741   // Start out with the entire array in the StringRef.
1742   Str = Array->getAsString();
1743
1744   if (Offset > NumElts)
1745     return false;
1746   
1747   // Skip over 'offset' bytes.
1748   Str = Str.substr(Offset);
1749   
1750   if (TrimAtNul) {
1751     // Trim off the \0 and anything after it.  If the array is not nul
1752     // terminated, we just return the whole end of string.  The client may know
1753     // some other way that the string is length-bound.
1754     Str = Str.substr(0, Str.find('\0'));
1755   }
1756   return true;
1757 }
1758
1759 // These next two are very similar to the above, but also look through PHI
1760 // nodes.
1761 // TODO: See if we can integrate these two together.
1762
1763 /// GetStringLengthH - If we can compute the length of the string pointed to by
1764 /// the specified pointer, return 'len+1'.  If we can't, return 0.
1765 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1766   // Look through noop bitcast instructions.
1767   V = V->stripPointerCasts();
1768
1769   // If this is a PHI node, there are two cases: either we have already seen it
1770   // or we haven't.
1771   if (PHINode *PN = dyn_cast<PHINode>(V)) {
1772     if (!PHIs.insert(PN))
1773       return ~0ULL;  // already in the set.
1774
1775     // If it was new, see if all the input strings are the same length.
1776     uint64_t LenSoFar = ~0ULL;
1777     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1778       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1779       if (Len == 0) return 0; // Unknown length -> unknown.
1780
1781       if (Len == ~0ULL) continue;
1782
1783       if (Len != LenSoFar && LenSoFar != ~0ULL)
1784         return 0;    // Disagree -> unknown.
1785       LenSoFar = Len;
1786     }
1787
1788     // Success, all agree.
1789     return LenSoFar;
1790   }
1791
1792   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1793   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1794     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1795     if (Len1 == 0) return 0;
1796     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1797     if (Len2 == 0) return 0;
1798     if (Len1 == ~0ULL) return Len2;
1799     if (Len2 == ~0ULL) return Len1;
1800     if (Len1 != Len2) return 0;
1801     return Len1;
1802   }
1803   
1804   // Otherwise, see if we can read the string.
1805   StringRef StrData;
1806   if (!getConstantStringInfo(V, StrData))
1807     return 0;
1808
1809   return StrData.size()+1;
1810 }
1811
1812 /// GetStringLength - If we can compute the length of the string pointed to by
1813 /// the specified pointer, return 'len+1'.  If we can't, return 0.
1814 uint64_t llvm::GetStringLength(Value *V) {
1815   if (!V->getType()->isPointerTy()) return 0;
1816
1817   SmallPtrSet<PHINode*, 32> PHIs;
1818   uint64_t Len = GetStringLengthH(V, PHIs);
1819   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1820   // an empty string as a length.
1821   return Len == ~0ULL ? 1 : Len;
1822 }
1823
1824 Value *
1825 llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
1826   if (!V->getType()->isPointerTy())
1827     return V;
1828   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1829     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1830       V = GEP->getPointerOperand();
1831     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1832       V = cast<Operator>(V)->getOperand(0);
1833     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1834       if (GA->mayBeOverridden())
1835         return V;
1836       V = GA->getAliasee();
1837     } else {
1838       // See if InstructionSimplify knows any relevant tricks.
1839       if (Instruction *I = dyn_cast<Instruction>(V))
1840         // TODO: Acquire a DominatorTree and use it.
1841         if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
1842           V = Simplified;
1843           continue;
1844         }
1845
1846       return V;
1847     }
1848     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1849   }
1850   return V;
1851 }
1852
1853 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1854 /// are lifetime markers.
1855 ///
1856 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1857   for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1858        UI != UE; ++UI) {
1859     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1860     if (!II) return false;
1861
1862     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1863         II->getIntrinsicID() != Intrinsic::lifetime_end)
1864       return false;
1865   }
1866   return true;
1867 }
1868
1869 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
1870                                         const TargetData *TD) {
1871   const Operator *Inst = dyn_cast<Operator>(V);
1872   if (!Inst)
1873     return false;
1874
1875   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
1876     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
1877       if (C->canTrap())
1878         return false;
1879
1880   switch (Inst->getOpcode()) {
1881   default:
1882     return true;
1883   case Instruction::UDiv:
1884   case Instruction::URem:
1885     // x / y is undefined if y == 0, but calcuations like x / 3 are safe.
1886     return isKnownNonZero(Inst->getOperand(1), TD);
1887   case Instruction::SDiv:
1888   case Instruction::SRem: {
1889     Value *Op = Inst->getOperand(1);
1890     // x / y is undefined if y == 0
1891     if (!isKnownNonZero(Op, TD))
1892       return false;
1893     // x / y might be undefined if y == -1
1894     unsigned BitWidth = getBitWidth(Op->getType(), TD);
1895     if (BitWidth == 0)
1896       return false;
1897     APInt KnownZero(BitWidth, 0);
1898     APInt KnownOne(BitWidth, 0);
1899     ComputeMaskedBits(Op, APInt::getAllOnesValue(BitWidth),
1900                       KnownZero, KnownOne, TD);
1901     return !!KnownZero;
1902   }
1903   case Instruction::Load: {
1904     const LoadInst *LI = cast<LoadInst>(Inst);
1905     if (!LI->isUnordered())
1906       return false;
1907     return LI->getPointerOperand()->isDereferenceablePointer();
1908   }
1909   case Instruction::Call: {
1910    if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
1911      switch (II->getIntrinsicID()) {
1912        case Intrinsic::bswap:
1913        case Intrinsic::ctlz:
1914        case Intrinsic::ctpop:
1915        case Intrinsic::cttz:
1916        case Intrinsic::objectsize:
1917        case Intrinsic::sadd_with_overflow:
1918        case Intrinsic::smul_with_overflow:
1919        case Intrinsic::ssub_with_overflow:
1920        case Intrinsic::uadd_with_overflow:
1921        case Intrinsic::umul_with_overflow:
1922        case Intrinsic::usub_with_overflow:
1923          return true;
1924        // TODO: some fp intrinsics are marked as having the same error handling
1925        // as libm. They're safe to speculate when they won't error.
1926        // TODO: are convert_{from,to}_fp16 safe?
1927        // TODO: can we list target-specific intrinsics here?
1928        default: break;
1929      }
1930    }
1931     return false; // The called function could have undefined behavior or
1932                   // side-effects, even if marked readnone nounwind.
1933   }
1934   case Instruction::VAArg:
1935   case Instruction::Alloca:
1936   case Instruction::Invoke:
1937   case Instruction::PHI:
1938   case Instruction::Store:
1939   case Instruction::Ret:
1940   case Instruction::Br:
1941   case Instruction::IndirectBr:
1942   case Instruction::Switch:
1943   case Instruction::Unreachable:
1944   case Instruction::Fence:
1945   case Instruction::LandingPad:
1946   case Instruction::AtomicRMW:
1947   case Instruction::AtomicCmpXchg:
1948   case Instruction::Resume:
1949     return false; // Misc instructions which have effects
1950   }
1951 }