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