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