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