Don't assume that external global variables are aligned at their preferred
[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/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Support/GetElementPtrTypeIterator.h"
24 #include "llvm/Support/MathExtras.h"
25 #include <cstring>
26 using namespace llvm;
27
28 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
29 /// known to be either zero or one and return them in the KnownZero/KnownOne
30 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
31 /// processing.
32 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
33 /// we cannot optimize based on the assumption that it is zero without changing
34 /// it to be an explicit zero.  If we don't change it to zero, other code could
35 /// optimized based on the contradictory assumption that it is non-zero.
36 /// Because instcombine aggressively folds operations with undef args anyway,
37 /// this won't lose us code quality.
38 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
39                              APInt &KnownZero, APInt &KnownOne,
40                              TargetData *TD, unsigned Depth) {
41   const unsigned MaxDepth = 6;
42   assert(V && "No Value?");
43   assert(Depth <= MaxDepth && "Limit Search Depth");
44   unsigned BitWidth = Mask.getBitWidth();
45   assert((V->getType()->isIntOrIntVector() || isa<PointerType>(V->getType())) &&
46          "Not integer or pointer type!");
47   assert((!TD ||
48           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
49          (!V->getType()->isIntOrIntVector() ||
50           V->getType()->getScalarSizeInBits() == BitWidth) &&
51          KnownZero.getBitWidth() == BitWidth && 
52          KnownOne.getBitWidth() == BitWidth &&
53          "V, Mask, KnownOne and KnownZero should have same BitWidth");
54
55   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
56     // We know all of the bits for a constant!
57     KnownOne = CI->getValue() & Mask;
58     KnownZero = ~KnownOne & Mask;
59     return;
60   }
61   // Null and aggregate-zero are all-zeros.
62   if (isa<ConstantPointerNull>(V) ||
63       isa<ConstantAggregateZero>(V)) {
64     KnownOne.clear();
65     KnownZero = Mask;
66     return;
67   }
68   // Handle a constant vector by taking the intersection of the known bits of
69   // each element.
70   if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
71     KnownZero.set(); KnownOne.set();
72     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
73       APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
74       ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
75                         TD, Depth);
76       KnownZero &= KnownZero2;
77       KnownOne &= KnownOne2;
78     }
79     return;
80   }
81   // The address of an aligned GlobalValue has trailing zeros.
82   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
83     unsigned Align = GV->getAlignment();
84     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
85       const Type *ObjectType = GV->getType()->getElementType();
86       // If the object is defined in the current Module, we'll be giving
87       // it the preferred alignment. Otherwise, we have to assume that it
88       // may only have the minimum ABI alignment.
89       if (!GV->isDeclaration() && !GV->mayBeOverridden())
90         Align = TD->getPrefTypeAlignment(ObjectType);
91       else
92         Align = TD->getABITypeAlignment(ObjectType);
93     }
94     if (Align > 0)
95       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
96                                               CountTrailingZeros_32(Align));
97     else
98       KnownZero.clear();
99     KnownOne.clear();
100     return;
101   }
102
103   KnownZero.clear(); KnownOne.clear();   // Start out not knowing anything.
104
105   if (Depth == MaxDepth || Mask == 0)
106     return;  // Limit search depth.
107
108   Operator *I = dyn_cast<Operator>(V);
109   if (!I) return;
110
111   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
112   switch (I->getOpcode()) {
113   default: break;
114   case Instruction::And: {
115     // If either the LHS or the RHS are Zero, the result is zero.
116     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
117     APInt Mask2(Mask & ~KnownZero);
118     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
119                       Depth+1);
120     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
121     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
122     
123     // Output known-1 bits are only known if set in both the LHS & RHS.
124     KnownOne &= KnownOne2;
125     // Output known-0 are known to be clear if zero in either the LHS | RHS.
126     KnownZero |= KnownZero2;
127     return;
128   }
129   case Instruction::Or: {
130     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
131     APInt Mask2(Mask & ~KnownOne);
132     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
133                       Depth+1);
134     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
135     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
136     
137     // Output known-0 bits are only known if clear in both the LHS & RHS.
138     KnownZero &= KnownZero2;
139     // Output known-1 are known to be set if set in either the LHS | RHS.
140     KnownOne |= KnownOne2;
141     return;
142   }
143   case Instruction::Xor: {
144     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
145     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
146                       Depth+1);
147     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
148     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
149     
150     // Output known-0 bits are known if clear or set in both the LHS & RHS.
151     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
152     // Output known-1 are known to be set if set in only one of the LHS, RHS.
153     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
154     KnownZero = KnownZeroOut;
155     return;
156   }
157   case Instruction::Mul: {
158     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
159     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
160     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
161                       Depth+1);
162     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
163     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
164     
165     // If low bits are zero in either operand, output low known-0 bits.
166     // Also compute a conserative estimate for high known-0 bits.
167     // More trickiness is possible, but this is sufficient for the
168     // interesting case of alignment computation.
169     KnownOne.clear();
170     unsigned TrailZ = KnownZero.countTrailingOnes() +
171                       KnownZero2.countTrailingOnes();
172     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
173                                KnownZero2.countLeadingOnes(),
174                                BitWidth) - BitWidth;
175
176     TrailZ = std::min(TrailZ, BitWidth);
177     LeadZ = std::min(LeadZ, BitWidth);
178     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
179                 APInt::getHighBitsSet(BitWidth, LeadZ);
180     KnownZero &= Mask;
181     return;
182   }
183   case Instruction::UDiv: {
184     // For the purposes of computing leading zeros we can conservatively
185     // treat a udiv as a logical right shift by the power of 2 known to
186     // be less than the denominator.
187     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
188     ComputeMaskedBits(I->getOperand(0),
189                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
190     unsigned LeadZ = KnownZero2.countLeadingOnes();
191
192     KnownOne2.clear();
193     KnownZero2.clear();
194     ComputeMaskedBits(I->getOperand(1),
195                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
196     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
197     if (RHSUnknownLeadingOnes != BitWidth)
198       LeadZ = std::min(BitWidth,
199                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
200
201     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
202     return;
203   }
204   case Instruction::Select:
205     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
206     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
207                       Depth+1);
208     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
209     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
210
211     // Only known if known in both the LHS and RHS.
212     KnownOne &= KnownOne2;
213     KnownZero &= KnownZero2;
214     return;
215   case Instruction::FPTrunc:
216   case Instruction::FPExt:
217   case Instruction::FPToUI:
218   case Instruction::FPToSI:
219   case Instruction::SIToFP:
220   case Instruction::UIToFP:
221     return; // Can't work with floating point.
222   case Instruction::PtrToInt:
223   case Instruction::IntToPtr:
224     // We can't handle these if we don't know the pointer size.
225     if (!TD) return;
226     // FALL THROUGH and handle them the same as zext/trunc.
227   case Instruction::ZExt:
228   case Instruction::Trunc: {
229     // Note that we handle pointer operands here because of inttoptr/ptrtoint
230     // which fall through here.
231     const Type *SrcTy = I->getOperand(0)->getType();
232     unsigned SrcBitWidth = TD ?
233       TD->getTypeSizeInBits(SrcTy) :
234       SrcTy->getScalarSizeInBits();
235     APInt MaskIn(Mask);
236     MaskIn.zextOrTrunc(SrcBitWidth);
237     KnownZero.zextOrTrunc(SrcBitWidth);
238     KnownOne.zextOrTrunc(SrcBitWidth);
239     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
240                       Depth+1);
241     KnownZero.zextOrTrunc(BitWidth);
242     KnownOne.zextOrTrunc(BitWidth);
243     // Any top bits are known to be zero.
244     if (BitWidth > SrcBitWidth)
245       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
246     return;
247   }
248   case Instruction::BitCast: {
249     const Type *SrcTy = I->getOperand(0)->getType();
250     if ((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
251         // TODO: For now, not handling conversions like:
252         // (bitcast i64 %x to <2 x i32>)
253         !isa<VectorType>(I->getType())) {
254       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
255                         Depth+1);
256       return;
257     }
258     break;
259   }
260   case Instruction::SExt: {
261     // Compute the bits in the result that are not present in the input.
262     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
263     unsigned SrcBitWidth = SrcTy->getBitWidth();
264       
265     APInt MaskIn(Mask); 
266     MaskIn.trunc(SrcBitWidth);
267     KnownZero.trunc(SrcBitWidth);
268     KnownOne.trunc(SrcBitWidth);
269     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
270                       Depth+1);
271     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
272     KnownZero.zext(BitWidth);
273     KnownOne.zext(BitWidth);
274
275     // If the sign bit of the input is known set or clear, then we know the
276     // top bits of the result.
277     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
278       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
279     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
280       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
281     return;
282   }
283   case Instruction::Shl:
284     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
285     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
286       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
287       APInt Mask2(Mask.lshr(ShiftAmt));
288       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
289                         Depth+1);
290       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
291       KnownZero <<= ShiftAmt;
292       KnownOne  <<= ShiftAmt;
293       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
294       return;
295     }
296     break;
297   case Instruction::LShr:
298     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
299     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
300       // Compute the new bits that are at the top now.
301       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
302       
303       // Unsigned shift right.
304       APInt Mask2(Mask.shl(ShiftAmt));
305       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
306                         Depth+1);
307       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
308       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
309       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
310       // high bits known zero.
311       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
312       return;
313     }
314     break;
315   case Instruction::AShr:
316     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
317     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
318       // Compute the new bits that are at the top now.
319       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
320       
321       // Signed shift right.
322       APInt Mask2(Mask.shl(ShiftAmt));
323       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
324                         Depth+1);
325       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
326       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
327       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
328         
329       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
330       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
331         KnownZero |= HighBits;
332       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
333         KnownOne |= HighBits;
334       return;
335     }
336     break;
337   case Instruction::Sub: {
338     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
339       // We know that the top bits of C-X are clear if X contains less bits
340       // than C (i.e. no wrap-around can happen).  For example, 20-X is
341       // positive if we can prove that X is >= 0 and < 16.
342       if (!CLHS->getValue().isNegative()) {
343         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
344         // NLZ can't be BitWidth with no sign bit
345         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
346         ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
347                           TD, Depth+1);
348     
349         // If all of the MaskV bits are known to be zero, then we know the
350         // output top bits are zero, because we now know that the output is
351         // from [0-C].
352         if ((KnownZero2 & MaskV) == MaskV) {
353           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
354           // Top bits known zero.
355           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
356         }
357       }        
358     }
359   }
360   // fall through
361   case Instruction::Add: {
362     // If one of the operands has trailing zeros, than the bits that the
363     // other operand has in those bit positions will be preserved in the
364     // result. For an add, this works with either operand. For a subtract,
365     // this only works if the known zeros are in the right operand.
366     APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
367     APInt Mask2 = APInt::getLowBitsSet(BitWidth,
368                                        BitWidth - Mask.countLeadingZeros());
369     ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
370                       Depth+1);
371     assert((LHSKnownZero & LHSKnownOne) == 0 &&
372            "Bits known to be one AND zero?");
373     unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
374
375     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD, 
376                       Depth+1);
377     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
378     unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
379
380     // Determine which operand has more trailing zeros, and use that
381     // many bits from the other operand.
382     if (LHSKnownZeroOut > RHSKnownZeroOut) {
383       if (I->getOpcode() == Instruction::Add) {
384         APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
385         KnownZero |= KnownZero2 & Mask;
386         KnownOne  |= KnownOne2 & Mask;
387       } else {
388         // If the known zeros are in the left operand for a subtract,
389         // fall back to the minimum known zeros in both operands.
390         KnownZero |= APInt::getLowBitsSet(BitWidth,
391                                           std::min(LHSKnownZeroOut,
392                                                    RHSKnownZeroOut));
393       }
394     } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
395       APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
396       KnownZero |= LHSKnownZero & Mask;
397       KnownOne  |= LHSKnownOne & Mask;
398     }
399     return;
400   }
401   case Instruction::SRem:
402     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
403       APInt RA = Rem->getValue();
404       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
405         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
406         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
407         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 
408                           Depth+1);
409
410         // If the sign bit of the first operand is zero, the sign bit of
411         // the result is zero. If the first operand has no one bits below
412         // the second operand's single 1 bit, its sign will be zero.
413         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
414           KnownZero2 |= ~LowBits;
415
416         KnownZero |= KnownZero2 & Mask;
417
418         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
419       }
420     }
421     break;
422   case Instruction::URem: {
423     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
424       APInt RA = Rem->getValue();
425       if (RA.isPowerOf2()) {
426         APInt LowBits = (RA - 1);
427         APInt Mask2 = LowBits & Mask;
428         KnownZero |= ~LowBits & Mask;
429         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
430                           Depth+1);
431         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
432         break;
433       }
434     }
435
436     // Since the result is less than or equal to either operand, any leading
437     // zero bits in either operand must also exist in the result.
438     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
439     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
440                       TD, Depth+1);
441     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
442                       TD, Depth+1);
443
444     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
445                                 KnownZero2.countLeadingOnes());
446     KnownOne.clear();
447     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
448     break;
449   }
450
451   case Instruction::Alloca:
452   case Instruction::Malloc: {
453     AllocationInst *AI = cast<AllocationInst>(V);
454     unsigned Align = AI->getAlignment();
455     if (Align == 0 && TD) {
456       if (isa<AllocaInst>(AI))
457         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
458       else if (isa<MallocInst>(AI)) {
459         // Malloc returns maximally aligned memory.
460         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
461         Align =
462           std::max(Align,
463                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
464         Align =
465           std::max(Align,
466                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
467       }
468     }
469     
470     if (Align > 0)
471       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
472                                               CountTrailingZeros_32(Align));
473     break;
474   }
475   case Instruction::GetElementPtr: {
476     // Analyze all of the subscripts of this getelementptr instruction
477     // to determine if we can prove known low zero bits.
478     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
479     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
480     ComputeMaskedBits(I->getOperand(0), LocalMask,
481                       LocalKnownZero, LocalKnownOne, TD, Depth+1);
482     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
483
484     gep_type_iterator GTI = gep_type_begin(I);
485     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
486       Value *Index = I->getOperand(i);
487       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
488         // Handle struct member offset arithmetic.
489         if (!TD) return;
490         const StructLayout *SL = TD->getStructLayout(STy);
491         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
492         uint64_t Offset = SL->getElementOffset(Idx);
493         TrailZ = std::min(TrailZ,
494                           CountTrailingZeros_64(Offset));
495       } else {
496         // Handle array index arithmetic.
497         const Type *IndexedTy = GTI.getIndexedType();
498         if (!IndexedTy->isSized()) return;
499         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
500         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
501         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
502         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
503         ComputeMaskedBits(Index, LocalMask,
504                           LocalKnownZero, LocalKnownOne, TD, Depth+1);
505         TrailZ = std::min(TrailZ,
506                           unsigned(CountTrailingZeros_64(TypeSize) +
507                                    LocalKnownZero.countTrailingOnes()));
508       }
509     }
510     
511     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
512     break;
513   }
514   case Instruction::PHI: {
515     PHINode *P = cast<PHINode>(I);
516     // Handle the case of a simple two-predecessor recurrence PHI.
517     // There's a lot more that could theoretically be done here, but
518     // this is sufficient to catch some interesting cases.
519     if (P->getNumIncomingValues() == 2) {
520       for (unsigned i = 0; i != 2; ++i) {
521         Value *L = P->getIncomingValue(i);
522         Value *R = P->getIncomingValue(!i);
523         Operator *LU = dyn_cast<Operator>(L);
524         if (!LU)
525           continue;
526         unsigned Opcode = LU->getOpcode();
527         // Check for operations that have the property that if
528         // both their operands have low zero bits, the result
529         // will have low zero bits.
530         if (Opcode == Instruction::Add ||
531             Opcode == Instruction::Sub ||
532             Opcode == Instruction::And ||
533             Opcode == Instruction::Or ||
534             Opcode == Instruction::Mul) {
535           Value *LL = LU->getOperand(0);
536           Value *LR = LU->getOperand(1);
537           // Find a recurrence.
538           if (LL == I)
539             L = LR;
540           else if (LR == I)
541             L = LL;
542           else
543             break;
544           // Ok, we have a PHI of the form L op= R. Check for low
545           // zero bits.
546           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
547           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
548           Mask2 = APInt::getLowBitsSet(BitWidth,
549                                        KnownZero2.countTrailingOnes());
550
551           // We need to take the minimum number of known bits
552           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
553           ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
554
555           KnownZero = Mask &
556                       APInt::getLowBitsSet(BitWidth,
557                                            std::min(KnownZero2.countTrailingOnes(),
558                                                     KnownZero3.countTrailingOnes()));
559           break;
560         }
561       }
562     }
563
564     // Otherwise take the unions of the known bit sets of the operands,
565     // taking conservative care to avoid excessive recursion.
566     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
567       KnownZero = APInt::getAllOnesValue(BitWidth);
568       KnownOne = APInt::getAllOnesValue(BitWidth);
569       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
570         // Skip direct self references.
571         if (P->getIncomingValue(i) == P) continue;
572
573         KnownZero2 = APInt(BitWidth, 0);
574         KnownOne2 = APInt(BitWidth, 0);
575         // Recurse, but cap the recursion to one level, because we don't
576         // want to waste time spinning around in loops.
577         ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
578                           KnownZero2, KnownOne2, TD, MaxDepth-1);
579         KnownZero &= KnownZero2;
580         KnownOne &= KnownOne2;
581         // If all bits have been ruled out, there's no need to check
582         // more operands.
583         if (!KnownZero && !KnownOne)
584           break;
585       }
586     }
587     break;
588   }
589   case Instruction::Call:
590     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
591       switch (II->getIntrinsicID()) {
592       default: break;
593       case Intrinsic::ctpop:
594       case Intrinsic::ctlz:
595       case Intrinsic::cttz: {
596         unsigned LowBits = Log2_32(BitWidth)+1;
597         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
598         break;
599       }
600       }
601     }
602     break;
603   }
604 }
605
606 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
607 /// this predicate to simplify operations downstream.  Mask is known to be zero
608 /// for bits that V cannot have.
609 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
610                              TargetData *TD, unsigned Depth) {
611   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
612   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
613   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
614   return (KnownZero & Mask) == Mask;
615 }
616
617
618
619 /// ComputeNumSignBits - Return the number of times the sign bit of the
620 /// register is replicated into the other bits.  We know that at least 1 bit
621 /// is always equal to the sign bit (itself), but other cases can give us
622 /// information.  For example, immediately after an "ashr X, 2", we know that
623 /// the top 3 bits are all equal to each other, so we return 3.
624 ///
625 /// 'Op' must have a scalar integer type.
626 ///
627 unsigned llvm::ComputeNumSignBits(Value *V, TargetData *TD, unsigned Depth) {
628   assert((TD || V->getType()->isIntOrIntVector()) &&
629          "ComputeNumSignBits requires a TargetData object to operate "
630          "on non-integer values!");
631   const Type *Ty = V->getType();
632   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
633                          Ty->getScalarSizeInBits();
634   unsigned Tmp, Tmp2;
635   unsigned FirstAnswer = 1;
636
637   // Note that ConstantInt is handled by the general ComputeMaskedBits case
638   // below.
639
640   if (Depth == 6)
641     return 1;  // Limit search depth.
642   
643   Operator *U = dyn_cast<Operator>(V);
644   switch (Operator::getOpcode(V)) {
645   default: break;
646   case Instruction::SExt:
647     Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
648     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
649     
650   case Instruction::AShr:
651     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
652     // ashr X, C   -> adds C sign bits.
653     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
654       Tmp += C->getZExtValue();
655       if (Tmp > TyBits) Tmp = TyBits;
656     }
657     return Tmp;
658   case Instruction::Shl:
659     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
660       // shl destroys sign bits.
661       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
662       if (C->getZExtValue() >= TyBits ||      // Bad shift.
663           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
664       return Tmp - C->getZExtValue();
665     }
666     break;
667   case Instruction::And:
668   case Instruction::Or:
669   case Instruction::Xor:    // NOT is handled here.
670     // Logical binary ops preserve the number of sign bits at the worst.
671     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
672     if (Tmp != 1) {
673       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
674       FirstAnswer = std::min(Tmp, Tmp2);
675       // We computed what we know about the sign bits as our first
676       // answer. Now proceed to the generic code that uses
677       // ComputeMaskedBits, and pick whichever answer is better.
678     }
679     break;
680
681   case Instruction::Select:
682     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
683     if (Tmp == 1) return 1;  // Early out.
684     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
685     return std::min(Tmp, Tmp2);
686     
687   case Instruction::Add:
688     // Add can have at most one carry bit.  Thus we know that the output
689     // is, at worst, one more bit than the inputs.
690     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
691     if (Tmp == 1) return 1;  // Early out.
692       
693     // Special case decrementing a value (ADD X, -1):
694     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
695       if (CRHS->isAllOnesValue()) {
696         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
697         APInt Mask = APInt::getAllOnesValue(TyBits);
698         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
699                           Depth+1);
700         
701         // If the input is known to be 0 or 1, the output is 0/-1, which is all
702         // sign bits set.
703         if ((KnownZero | APInt(TyBits, 1)) == Mask)
704           return TyBits;
705         
706         // If we are subtracting one from a positive number, there is no carry
707         // out of the result.
708         if (KnownZero.isNegative())
709           return Tmp;
710       }
711       
712     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
713     if (Tmp2 == 1) return 1;
714       return std::min(Tmp, Tmp2)-1;
715     break;
716     
717   case Instruction::Sub:
718     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
719     if (Tmp2 == 1) return 1;
720       
721     // Handle NEG.
722     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
723       if (CLHS->isNullValue()) {
724         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
725         APInt Mask = APInt::getAllOnesValue(TyBits);
726         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, 
727                           TD, Depth+1);
728         // If the input is known to be 0 or 1, the output is 0/-1, which is all
729         // sign bits set.
730         if ((KnownZero | APInt(TyBits, 1)) == Mask)
731           return TyBits;
732         
733         // If the input is known to be positive (the sign bit is known clear),
734         // the output of the NEG has the same number of sign bits as the input.
735         if (KnownZero.isNegative())
736           return Tmp2;
737         
738         // Otherwise, we treat this like a SUB.
739       }
740     
741     // Sub can have at most one carry bit.  Thus we know that the output
742     // is, at worst, one more bit than the inputs.
743     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
744     if (Tmp == 1) return 1;  // Early out.
745       return std::min(Tmp, Tmp2)-1;
746     break;
747   case Instruction::Trunc:
748     // FIXME: it's tricky to do anything useful for this, but it is an important
749     // case for targets like X86.
750     break;
751   }
752   
753   // Finally, if we can prove that the top bits of the result are 0's or 1's,
754   // use this information.
755   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
756   APInt Mask = APInt::getAllOnesValue(TyBits);
757   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
758   
759   if (KnownZero.isNegative()) {        // sign bit is 0
760     Mask = KnownZero;
761   } else if (KnownOne.isNegative()) {  // sign bit is 1;
762     Mask = KnownOne;
763   } else {
764     // Nothing known.
765     return FirstAnswer;
766   }
767   
768   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
769   // the number of identical bits in the top of the input value.
770   Mask = ~Mask;
771   Mask <<= Mask.getBitWidth()-TyBits;
772   // Return # leading zeros.  We use 'min' here in case Val was zero before
773   // shifting.  We don't want to return '64' as for an i32 "0".
774   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
775 }
776
777 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
778 /// value is never equal to -0.0.
779 ///
780 /// NOTE: this function will need to be revisited when we support non-default
781 /// rounding modes!
782 ///
783 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
784   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
785     return !CFP->getValueAPF().isNegZero();
786   
787   if (Depth == 6)
788     return 1;  // Limit search depth.
789
790   const Operator *I = dyn_cast<Operator>(V);
791   if (I == 0) return false;
792   
793   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
794   if (I->getOpcode() == Instruction::FAdd &&
795       isa<ConstantFP>(I->getOperand(1)) && 
796       cast<ConstantFP>(I->getOperand(1))->isNullValue())
797     return true;
798     
799   // sitofp and uitofp turn into +0.0 for zero.
800   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
801     return true;
802   
803   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
804     // sqrt(-0.0) = -0.0, no other negative results are possible.
805     if (II->getIntrinsicID() == Intrinsic::sqrt)
806       return CannotBeNegativeZero(II->getOperand(1), Depth+1);
807   
808   if (const CallInst *CI = dyn_cast<CallInst>(I))
809     if (const Function *F = CI->getCalledFunction()) {
810       if (F->isDeclaration()) {
811         // abs(x) != -0.0
812         if (F->getName() == "abs") return true;
813         // abs[lf](x) != -0.0
814         if (F->getName() == "absf") return true;
815         if (F->getName() == "absl") return true;
816       }
817     }
818   
819   return false;
820 }
821
822 // This is the recursive version of BuildSubAggregate. It takes a few different
823 // arguments. Idxs is the index within the nested struct From that we are
824 // looking at now (which is of type IndexedType). IdxSkip is the number of
825 // indices from Idxs that should be left out when inserting into the resulting
826 // struct. To is the result struct built so far, new insertvalue instructions
827 // build on that.
828 static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
829                                 SmallVector<unsigned, 10> &Idxs,
830                                 unsigned IdxSkip,
831                                 LLVMContext &Context,
832                                 Instruction *InsertBefore) {
833   const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
834   if (STy) {
835     // Save the original To argument so we can modify it
836     Value *OrigTo = To;
837     // General case, the type indexed by Idxs is a struct
838     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
839       // Process each struct element recursively
840       Idxs.push_back(i);
841       Value *PrevTo = To;
842       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
843                              Context, InsertBefore);
844       Idxs.pop_back();
845       if (!To) {
846         // Couldn't find any inserted value for this index? Cleanup
847         while (PrevTo != OrigTo) {
848           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
849           PrevTo = Del->getAggregateOperand();
850           Del->eraseFromParent();
851         }
852         // Stop processing elements
853         break;
854       }
855     }
856     // If we succesfully found a value for each of our subaggregates 
857     if (To)
858       return To;
859   }
860   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
861   // the struct's elements had a value that was inserted directly. In the latter
862   // case, perhaps we can't determine each of the subelements individually, but
863   // we might be able to find the complete struct somewhere.
864   
865   // Find the value that is at that particular spot
866   Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end(), Context);
867
868   if (!V)
869     return NULL;
870
871   // Insert the value in the new (sub) aggregrate
872   return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
873                                        Idxs.end(), "tmp", InsertBefore);
874 }
875
876 // This helper takes a nested struct and extracts a part of it (which is again a
877 // struct) into a new value. For example, given the struct:
878 // { a, { b, { c, d }, e } }
879 // and the indices "1, 1" this returns
880 // { c, d }.
881 //
882 // It does this by inserting an insertvalue for each element in the resulting
883 // struct, as opposed to just inserting a single struct. This will only work if
884 // each of the elements of the substruct are known (ie, inserted into From by an
885 // insertvalue instruction somewhere).
886 //
887 // All inserted insertvalue instructions are inserted before InsertBefore
888 static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
889                                 const unsigned *idx_end, LLVMContext &Context,
890                                 Instruction *InsertBefore) {
891   assert(InsertBefore && "Must have someplace to insert!");
892   const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
893                                                              idx_begin,
894                                                              idx_end);
895   Value *To = UndefValue::get(IndexedType);
896   SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
897   unsigned IdxSkip = Idxs.size();
898
899   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip,
900                            Context, InsertBefore);
901 }
902
903 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
904 /// the scalar value indexed is already around as a register, for example if it
905 /// were inserted directly into the aggregrate.
906 ///
907 /// If InsertBefore is not null, this function will duplicate (modified)
908 /// insertvalues when a part of a nested struct is extracted.
909 Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
910                          const unsigned *idx_end, LLVMContext &Context,
911                          Instruction *InsertBefore) {
912   // Nothing to index? Just return V then (this is useful at the end of our
913   // recursion)
914   if (idx_begin == idx_end)
915     return V;
916   // We have indices, so V should have an indexable type
917   assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
918          && "Not looking at a struct or array?");
919   assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
920          && "Invalid indices for type?");
921   const CompositeType *PTy = cast<CompositeType>(V->getType());
922
923   if (isa<UndefValue>(V))
924     return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
925                                                               idx_begin,
926                                                               idx_end));
927   else if (isa<ConstantAggregateZero>(V))
928     return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy, 
929                                                                   idx_begin,
930                                                                   idx_end));
931   else if (Constant *C = dyn_cast<Constant>(V)) {
932     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
933       // Recursively process this constant
934       return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
935                                idx_end, Context, InsertBefore);
936   } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
937     // Loop the indices for the insertvalue instruction in parallel with the
938     // requested indices
939     const unsigned *req_idx = idx_begin;
940     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
941          i != e; ++i, ++req_idx) {
942       if (req_idx == idx_end) {
943         if (InsertBefore)
944           // The requested index identifies a part of a nested aggregate. Handle
945           // this specially. For example,
946           // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
947           // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
948           // %C = extractvalue {i32, { i32, i32 } } %B, 1
949           // This can be changed into
950           // %A = insertvalue {i32, i32 } undef, i32 10, 0
951           // %C = insertvalue {i32, i32 } %A, i32 11, 1
952           // which allows the unused 0,0 element from the nested struct to be
953           // removed.
954           return BuildSubAggregate(V, idx_begin, req_idx,
955                                    Context, InsertBefore);
956         else
957           // We can't handle this without inserting insertvalues
958           return 0;
959       }
960       
961       // This insert value inserts something else than what we are looking for.
962       // See if the (aggregrate) value inserted into has the value we are
963       // looking for, then.
964       if (*req_idx != *i)
965         return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
966                                  Context, InsertBefore);
967     }
968     // If we end up here, the indices of the insertvalue match with those
969     // requested (though possibly only partially). Now we recursively look at
970     // the inserted value, passing any remaining indices.
971     return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
972                              Context, InsertBefore);
973   } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
974     // If we're extracting a value from an aggregrate that was extracted from
975     // something else, we can extract from that something else directly instead.
976     // However, we will need to chain I's indices with the requested indices.
977    
978     // Calculate the number of indices required 
979     unsigned size = I->getNumIndices() + (idx_end - idx_begin);
980     // Allocate some space to put the new indices in
981     SmallVector<unsigned, 5> Idxs;
982     Idxs.reserve(size);
983     // Add indices from the extract value instruction
984     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
985          i != e; ++i)
986       Idxs.push_back(*i);
987     
988     // Add requested indices
989     for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
990       Idxs.push_back(*i);
991
992     assert(Idxs.size() == size 
993            && "Number of indices added not correct?");
994     
995     return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
996                              Context, InsertBefore);
997   }
998   // Otherwise, we don't know (such as, extracting from a function return value
999   // or load instruction)
1000   return 0;
1001 }
1002
1003 /// GetConstantStringInfo - This function computes the length of a
1004 /// null-terminated C string pointed to by V.  If successful, it returns true
1005 /// and returns the string in Str.  If unsuccessful, it returns false.
1006 bool llvm::GetConstantStringInfo(Value *V, std::string &Str, uint64_t Offset,
1007                                  bool StopAtNul) {
1008   // If V is NULL then return false;
1009   if (V == NULL) return false;
1010
1011   // Look through bitcast instructions.
1012   if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1013     return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1014   
1015   // If the value is not a GEP instruction nor a constant expression with a
1016   // GEP instruction, then return false because ConstantArray can't occur
1017   // any other way
1018   User *GEP = 0;
1019   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1020     GEP = GEPI;
1021   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1022     if (CE->getOpcode() == Instruction::BitCast)
1023       return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1024     if (CE->getOpcode() != Instruction::GetElementPtr)
1025       return false;
1026     GEP = CE;
1027   }
1028   
1029   if (GEP) {
1030     // Make sure the GEP has exactly three arguments.
1031     if (GEP->getNumOperands() != 3)
1032       return false;
1033     
1034     // Make sure the index-ee is a pointer to array of i8.
1035     const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1036     const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1037     if (AT == 0 || AT->getElementType() != Type::Int8Ty)
1038       return false;
1039     
1040     // Check to make sure that the first operand of the GEP is an integer and
1041     // has value 0 so that we are sure we're indexing into the initializer.
1042     ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1043     if (FirstIdx == 0 || !FirstIdx->isZero())
1044       return false;
1045     
1046     // If the second index isn't a ConstantInt, then this is a variable index
1047     // into the array.  If this occurs, we can't say anything meaningful about
1048     // the string.
1049     uint64_t StartIdx = 0;
1050     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1051       StartIdx = CI->getZExtValue();
1052     else
1053       return false;
1054     return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
1055                                  StopAtNul);
1056   }
1057   
1058   // The GEP instruction, constant or instruction, must reference a global
1059   // variable that is a constant and is initialized. The referenced constant
1060   // initializer is the array that we'll use for optimization.
1061   GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
1062   if (!GV || !GV->isConstant() || !GV->hasInitializer())
1063     return false;
1064   Constant *GlobalInit = GV->getInitializer();
1065   
1066   // Handle the ConstantAggregateZero case
1067   if (isa<ConstantAggregateZero>(GlobalInit)) {
1068     // This is a degenerate case. The initializer is constant zero so the
1069     // length of the string must be zero.
1070     Str.clear();
1071     return true;
1072   }
1073   
1074   // Must be a Constant Array
1075   ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1076   if (Array == 0 || Array->getType()->getElementType() != Type::Int8Ty)
1077     return false;
1078   
1079   // Get the number of elements in the array
1080   uint64_t NumElts = Array->getType()->getNumElements();
1081   
1082   if (Offset > NumElts)
1083     return false;
1084   
1085   // Traverse the constant array from 'Offset' which is the place the GEP refers
1086   // to in the array.
1087   Str.reserve(NumElts-Offset);
1088   for (unsigned i = Offset; i != NumElts; ++i) {
1089     Constant *Elt = Array->getOperand(i);
1090     ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1091     if (!CI) // This array isn't suitable, non-int initializer.
1092       return false;
1093     if (StopAtNul && CI->isZero())
1094       return true; // we found end of string, success!
1095     Str += (char)CI->getZExtValue();
1096   }
1097   
1098   // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
1099   return true;
1100 }