Generalize target-independent folding rules for sizeof to handle more
[oota-llvm.git] / lib / VMCore / ConstantFold.cpp
1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
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 implements folding of constants for LLVM.  This implements the
11 // (internal) ConstantFold.h interface, which is used by the
12 // ConstantExpr::get* methods to automatically fold constants when possible.
13 //
14 // The current constant folding implementation is implemented in two pieces: the
15 // pieces that don't need TargetData, and the pieces that do. This is to avoid
16 // a dependence in VMCore on Target.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "ConstantFold.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include <limits>
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 //                ConstantFold*Instruction Implementations
39 //===----------------------------------------------------------------------===//
40
41 /// BitCastConstantVector - Convert the specified ConstantVector node to the
42 /// specified vector type.  At this point, we know that the elements of the
43 /// input vector constant are all simple integer or FP values.
44 static Constant *BitCastConstantVector(LLVMContext &Context, ConstantVector *CV,
45                                        const VectorType *DstTy) {
46   // If this cast changes element count then we can't handle it here:
47   // doing so requires endianness information.  This should be handled by
48   // Analysis/ConstantFolding.cpp
49   unsigned NumElts = DstTy->getNumElements();
50   if (NumElts != CV->getNumOperands())
51     return 0;
52
53   // Check to verify that all elements of the input are simple.
54   for (unsigned i = 0; i != NumElts; ++i) {
55     if (!isa<ConstantInt>(CV->getOperand(i)) &&
56         !isa<ConstantFP>(CV->getOperand(i)))
57       return 0;
58   }
59
60   // Bitcast each element now.
61   std::vector<Constant*> Result;
62   const Type *DstEltTy = DstTy->getElementType();
63   for (unsigned i = 0; i != NumElts; ++i)
64     Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i),
65                                                     DstEltTy));
66   return ConstantVector::get(Result);
67 }
68
69 /// This function determines which opcode to use to fold two constant cast 
70 /// expressions together. It uses CastInst::isEliminableCastPair to determine
71 /// the opcode. Consequently its just a wrapper around that function.
72 /// @brief Determine if it is valid to fold a cast of a cast
73 static unsigned
74 foldConstantCastPair(
75   unsigned opc,          ///< opcode of the second cast constant expression
76   ConstantExpr *Op,      ///< the first cast constant expression
77   const Type *DstTy      ///< desintation type of the first cast
78 ) {
79   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
80   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
81   assert(CastInst::isCast(opc) && "Invalid cast opcode");
82
83   // The the types and opcodes for the two Cast constant expressions
84   const Type *SrcTy = Op->getOperand(0)->getType();
85   const Type *MidTy = Op->getType();
86   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
87   Instruction::CastOps secondOp = Instruction::CastOps(opc);
88
89   // Let CastInst::isEliminableCastPair do the heavy lifting.
90   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
91                                         Type::getInt64Ty(DstTy->getContext()));
92 }
93
94 static Constant *FoldBitCast(LLVMContext &Context, 
95                              Constant *V, const Type *DestTy) {
96   const Type *SrcTy = V->getType();
97   if (SrcTy == DestTy)
98     return V; // no-op cast
99
100   // Check to see if we are casting a pointer to an aggregate to a pointer to
101   // the first element.  If so, return the appropriate GEP instruction.
102   if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
103     if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
104       if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
105         SmallVector<Value*, 8> IdxList;
106         Value *Zero = Constant::getNullValue(Type::getInt32Ty(Context));
107         IdxList.push_back(Zero);
108         const Type *ElTy = PTy->getElementType();
109         while (ElTy != DPTy->getElementType()) {
110           if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
111             if (STy->getNumElements() == 0) break;
112             ElTy = STy->getElementType(0);
113             IdxList.push_back(Zero);
114           } else if (const SequentialType *STy = 
115                      dyn_cast<SequentialType>(ElTy)) {
116             if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
117             ElTy = STy->getElementType();
118             IdxList.push_back(Zero);
119           } else {
120             break;
121           }
122         }
123
124         if (ElTy == DPTy->getElementType())
125           // This GEP is inbounds because all indices are zero.
126           return ConstantExpr::getInBoundsGetElementPtr(V, &IdxList[0],
127                                                         IdxList.size());
128       }
129
130   // Handle casts from one vector constant to another.  We know that the src 
131   // and dest type have the same size (otherwise its an illegal cast).
132   if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
133     if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
134       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
135              "Not cast between same sized vectors!");
136       SrcTy = NULL;
137       // First, check for null.  Undef is already handled.
138       if (isa<ConstantAggregateZero>(V))
139         return Constant::getNullValue(DestTy);
140
141       if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
142         return BitCastConstantVector(Context, CV, DestPTy);
143     }
144
145     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
146     // This allows for other simplifications (although some of them
147     // can only be handled by Analysis/ConstantFolding.cpp).
148     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
149       return ConstantExpr::getBitCast(
150                                      ConstantVector::get(&V, 1), DestPTy);
151   }
152
153   // Finally, implement bitcast folding now.   The code below doesn't handle
154   // bitcast right.
155   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
156     return ConstantPointerNull::get(cast<PointerType>(DestTy));
157
158   // Handle integral constant input.
159   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
160     if (DestTy->isInteger())
161       // Integral -> Integral. This is a no-op because the bit widths must
162       // be the same. Consequently, we just fold to V.
163       return V;
164
165     if (DestTy->isFloatingPoint())
166       return ConstantFP::get(Context, APFloat(CI->getValue(),
167                                      DestTy != Type::getPPC_FP128Ty(Context)));
168
169     // Otherwise, can't fold this (vector?)
170     return 0;
171   }
172
173   // Handle ConstantFP input.
174   if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
175     // FP -> Integral.
176     return ConstantInt::get(Context, FP->getValueAPF().bitcastToAPInt());
177
178   return 0;
179 }
180
181
182 /// ExtractConstantBytes - V is an integer constant which only has a subset of
183 /// its bytes used.  The bytes used are indicated by ByteStart (which is the
184 /// first byte used, counting from the least significant byte) and ByteSize,
185 /// which is the number of bytes used.
186 ///
187 /// This function analyzes the specified constant to see if the specified byte
188 /// range can be returned as a simplified constant.  If so, the constant is
189 /// returned, otherwise null is returned.
190 /// 
191 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
192                                       unsigned ByteSize) {
193   assert(isa<IntegerType>(C->getType()) &&
194          (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
195          "Non-byte sized integer input");
196   unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
197   assert(ByteSize && "Must be accessing some piece");
198   assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
199   assert(ByteSize != CSize && "Should not extract everything");
200   
201   // Constant Integers are simple.
202   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
203     APInt V = CI->getValue();
204     if (ByteStart)
205       V = V.lshr(ByteStart*8);
206     V.trunc(ByteSize*8);
207     return ConstantInt::get(CI->getContext(), V);
208   }
209   
210   // In the input is a constant expr, we might be able to recursively simplify.
211   // If not, we definitely can't do anything.
212   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
213   if (CE == 0) return 0;
214   
215   switch (CE->getOpcode()) {
216   default: return 0;
217   case Instruction::Or: {
218     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
219     if (RHS == 0)
220       return 0;
221     
222     // X | -1 -> -1.
223     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
224       if (RHSC->isAllOnesValue())
225         return RHSC;
226     
227     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
228     if (LHS == 0)
229       return 0;
230     return ConstantExpr::getOr(LHS, RHS);
231   }
232   case Instruction::And: {
233     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
234     if (RHS == 0)
235       return 0;
236     
237     // X & 0 -> 0.
238     if (RHS->isNullValue())
239       return RHS;
240     
241     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
242     if (LHS == 0)
243       return 0;
244     return ConstantExpr::getAnd(LHS, RHS);
245   }
246   case Instruction::LShr: {
247     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
248     if (Amt == 0)
249       return 0;
250     unsigned ShAmt = Amt->getZExtValue();
251     // Cannot analyze non-byte shifts.
252     if ((ShAmt & 7) != 0)
253       return 0;
254     ShAmt >>= 3;
255     
256     // If the extract is known to be all zeros, return zero.
257     if (ByteStart >= CSize-ShAmt)
258       return Constant::getNullValue(IntegerType::get(CE->getContext(),
259                                                      ByteSize*8));
260     // If the extract is known to be fully in the input, extract it.
261     if (ByteStart+ByteSize+ShAmt <= CSize)
262       return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
263     
264     // TODO: Handle the 'partially zero' case.
265     return 0;
266   }
267     
268   case Instruction::Shl: {
269     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
270     if (Amt == 0)
271       return 0;
272     unsigned ShAmt = Amt->getZExtValue();
273     // Cannot analyze non-byte shifts.
274     if ((ShAmt & 7) != 0)
275       return 0;
276     ShAmt >>= 3;
277     
278     // If the extract is known to be all zeros, return zero.
279     if (ByteStart+ByteSize <= ShAmt)
280       return Constant::getNullValue(IntegerType::get(CE->getContext(),
281                                                      ByteSize*8));
282     // If the extract is known to be fully in the input, extract it.
283     if (ByteStart >= ShAmt)
284       return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
285     
286     // TODO: Handle the 'partially zero' case.
287     return 0;
288   }
289       
290   case Instruction::ZExt: {
291     unsigned SrcBitSize =
292       cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
293     
294     // If extracting something that is completely zero, return 0.
295     if (ByteStart*8 >= SrcBitSize)
296       return Constant::getNullValue(IntegerType::get(CE->getContext(),
297                                                      ByteSize*8));
298
299     // If exactly extracting the input, return it.
300     if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
301       return CE->getOperand(0);
302     
303     // If extracting something completely in the input, if if the input is a
304     // multiple of 8 bits, recurse.
305     if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
306       return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
307       
308     // Otherwise, if extracting a subset of the input, which is not multiple of
309     // 8 bits, do a shift and trunc to get the bits.
310     if ((ByteStart+ByteSize)*8 < SrcBitSize) {
311       assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
312       Constant *Res = CE->getOperand(0);
313       if (ByteStart)
314         Res = ConstantExpr::getLShr(Res, 
315                                  ConstantInt::get(Res->getType(), ByteStart*8));
316       return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
317                                                           ByteSize*8));
318     }
319     
320     // TODO: Handle the 'partially zero' case.
321     return 0;
322   }
323   }
324 }
325
326 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
327 /// on Ty, with any known factors factored out. If Folded is false,
328 /// return null if no factoring was possible, to avoid endlessly
329 /// bouncing an unfoldable expression back into the top-level folder.
330 ///
331 static Constant *getFoldedSizeOf(const Type *Ty, const Type *DestTy,
332                                  bool Folded) {
333   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
334     Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
335     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
336     return ConstantExpr::getNUWMul(E, N);
337   }
338   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
339     Constant *N = ConstantInt::get(DestTy, VTy->getNumElements());
340     Constant *E = getFoldedSizeOf(VTy->getElementType(), DestTy, true);
341     return ConstantExpr::getNUWMul(E, N);
342   }
343   if (const StructType *STy = dyn_cast<StructType>(Ty))
344     if (!STy->isPacked()) {
345       unsigned NumElems = STy->getNumElements();
346       // An empty struct has size zero.
347       if (NumElems == 0)
348         return ConstantExpr::getNullValue(DestTy);
349       // Check for a struct with all members having the same type.
350       const Type *MemberTy = STy->getElementType(0);
351       bool AllSame = true;
352       for (unsigned i = 1; i != NumElems; ++i)
353         if (MemberTy != STy->getElementType(i)) {
354           AllSame = false;
355           break;
356         }
357       if (AllSame) {
358         Constant *N = ConstantInt::get(DestTy, NumElems);
359         Constant *E = getFoldedSizeOf(MemberTy, DestTy, true);
360         return ConstantExpr::getNUWMul(E, N);
361       }
362     }
363
364   // If there's no interesting folding happening, bail so that we don't create
365   // a constant that looks like it needs folding but really doesn't.
366   if (!Folded)
367     return 0;
368
369   // Base case: Get a regular sizeof expression.
370   Constant *C = ConstantExpr::getSizeOf(Ty);
371   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
372                                                     DestTy, false),
373                             C, DestTy);
374   return C;
375 }
376
377 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
378 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
379 /// return null if no factoring was possible, to avoid endlessly
380 /// bouncing an unfoldable expression back into the top-level folder.
381 ///
382 static Constant *getFoldedOffsetOf(const Type *Ty, Constant *FieldNo,
383                                    const Type *DestTy,
384                                    bool Folded) {
385   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
386     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
387                                                                 DestTy, false),
388                                         FieldNo, DestTy);
389     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
390     return ConstantExpr::getNUWMul(E, N);
391   }
392   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
393     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
394                                                                 DestTy, false),
395                                         FieldNo, DestTy);
396     Constant *E = getFoldedSizeOf(VTy->getElementType(), DestTy, true);
397     return ConstantExpr::getNUWMul(E, N);
398   }
399   if (const StructType *STy = dyn_cast<StructType>(Ty))
400     if (!STy->isPacked()) {
401       unsigned NumElems = STy->getNumElements();
402       // An empty struct has no members.
403       if (NumElems == 0)
404         return 0;
405       // Check for a struct with all members having the same type.
406       const Type *MemberTy = STy->getElementType(0);
407       bool AllSame = true;
408       for (unsigned i = 1; i != NumElems; ++i)
409         if (MemberTy != STy->getElementType(i)) {
410           AllSame = false;
411           break;
412         }
413       if (AllSame) {
414         Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
415                                                                     false,
416                                                                     DestTy,
417                                                                     false),
418                                             FieldNo, DestTy);
419         Constant *E = getFoldedSizeOf(MemberTy, DestTy, true);
420         return ConstantExpr::getNUWMul(E, N);
421       }
422     }
423
424   // If there's no interesting folding happening, bail so that we don't create
425   // a constant that looks like it needs folding but really doesn't.
426   if (!Folded)
427     return 0;
428
429   // Base case: Get a regular offsetof expression.
430   Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
431   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
432                                                     DestTy, false),
433                             C, DestTy);
434   return C;
435 }
436
437 Constant *llvm::ConstantFoldCastInstruction(LLVMContext &Context, 
438                                             unsigned opc, Constant *V,
439                                             const Type *DestTy) {
440   if (isa<UndefValue>(V)) {
441     // zext(undef) = 0, because the top bits will be zero.
442     // sext(undef) = 0, because the top bits will all be the same.
443     // [us]itofp(undef) = 0, because the result value is bounded.
444     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
445         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
446       return Constant::getNullValue(DestTy);
447     return UndefValue::get(DestTy);
448   }
449   // No compile-time operations on this type yet.
450   if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
451     return 0;
452
453   // If the cast operand is a constant expression, there's a few things we can
454   // do to try to simplify it.
455   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
456     if (CE->isCast()) {
457       // Try hard to fold cast of cast because they are often eliminable.
458       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
459         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
460     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
461       // If all of the indexes in the GEP are null values, there is no pointer
462       // adjustment going on.  We might as well cast the source pointer.
463       bool isAllNull = true;
464       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
465         if (!CE->getOperand(i)->isNullValue()) {
466           isAllNull = false;
467           break;
468         }
469       if (isAllNull)
470         // This is casting one pointer type to another, always BitCast
471         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
472     }
473   }
474
475   // If the cast operand is a constant vector, perform the cast by
476   // operating on each element. In the cast of bitcasts, the element
477   // count may be mismatched; don't attempt to handle that here.
478   if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
479     if (isa<VectorType>(DestTy) &&
480         cast<VectorType>(DestTy)->getNumElements() ==
481         CV->getType()->getNumElements()) {
482       std::vector<Constant*> res;
483       const VectorType *DestVecTy = cast<VectorType>(DestTy);
484       const Type *DstEltTy = DestVecTy->getElementType();
485       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
486         res.push_back(ConstantExpr::getCast(opc,
487                                             CV->getOperand(i), DstEltTy));
488       return ConstantVector::get(DestVecTy, res);
489     }
490
491   // We actually have to do a cast now. Perform the cast according to the
492   // opcode specified.
493   switch (opc) {
494   default:
495     llvm_unreachable("Failed to cast constant expression");
496   case Instruction::FPTrunc:
497   case Instruction::FPExt:
498     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
499       bool ignored;
500       APFloat Val = FPC->getValueAPF();
501       Val.convert(DestTy->isFloatTy() ? APFloat::IEEEsingle :
502                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
503                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
504                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
505                   APFloat::Bogus,
506                   APFloat::rmNearestTiesToEven, &ignored);
507       return ConstantFP::get(Context, Val);
508     }
509     return 0; // Can't fold.
510   case Instruction::FPToUI: 
511   case Instruction::FPToSI:
512     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
513       const APFloat &V = FPC->getValueAPF();
514       bool ignored;
515       uint64_t x[2]; 
516       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
517       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
518                                 APFloat::rmTowardZero, &ignored);
519       APInt Val(DestBitWidth, 2, x);
520       return ConstantInt::get(Context, Val);
521     }
522     return 0; // Can't fold.
523   case Instruction::IntToPtr:   //always treated as unsigned
524     if (V->isNullValue())       // Is it an integral null value?
525       return ConstantPointerNull::get(cast<PointerType>(DestTy));
526     return 0;                   // Other pointer types cannot be casted
527   case Instruction::PtrToInt:   // always treated as unsigned
528     // Is it a null pointer value?
529     if (V->isNullValue())
530       return ConstantInt::get(DestTy, 0);
531     // If this is a sizeof-like expression, pull out multiplications by
532     // known factors to expose them to subsequent folding. If it's an
533     // alignof-like expression, factor out known factors.
534     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
535       if (CE->getOpcode() == Instruction::GetElementPtr &&
536           CE->getOperand(0)->isNullValue()) {
537         const Type *Ty =
538           cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
539         if (CE->getNumOperands() == 2) {
540           // Handle a sizeof-like expression.
541           Constant *Idx = CE->getOperand(1);
542           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
543           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
544             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
545                                                                 DestTy, false),
546                                         Idx, DestTy);
547             return ConstantExpr::getMul(C, Idx);
548           }
549         } else if (CE->getNumOperands() == 3 &&
550                    CE->getOperand(1)->isNullValue()) {
551           // Handle an alignof-like expression.
552           if (const StructType *STy = dyn_cast<StructType>(Ty))
553             if (!STy->isPacked()) {
554               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
555               if (CI->isOne() &&
556                   STy->getNumElements() == 2 &&
557                   STy->getElementType(0)->isInteger(1)) {
558                 // The alignment of an array is equal to the alignment of the
559                 // array element. Note that this is not always true for vectors.
560                 if (const ArrayType *ATy =
561                     dyn_cast<ArrayType>(STy->getElementType(1))) {
562                   Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
563                   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
564                                                                     DestTy,
565                                                                     false),
566                                             C, DestTy);
567                   return C;
568                 }
569                 // Packed structs always have an alignment of 1.
570                 if (const StructType *InnerSTy =
571                       dyn_cast<StructType>(STy->getElementType(1)))
572                   if (InnerSTy->isPacked())
573                     return ConstantInt::get(DestTy, 1);
574               }
575             }
576           // Handle an offsetof-like expression.
577           if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)){
578             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
579                                                 DestTy, false))
580               return C;
581           }
582         }
583       }
584     // Other pointer types cannot be casted
585     return 0;
586   case Instruction::UIToFP:
587   case Instruction::SIToFP:
588     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
589       APInt api = CI->getValue();
590       const uint64_t zero[] = {0, 0};
591       APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
592                                   2, zero));
593       (void)apf.convertFromAPInt(api, 
594                                  opc==Instruction::SIToFP,
595                                  APFloat::rmNearestTiesToEven);
596       return ConstantFP::get(Context, apf);
597     }
598     return 0;
599   case Instruction::ZExt:
600     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
601       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
602       APInt Result(CI->getValue());
603       Result.zext(BitWidth);
604       return ConstantInt::get(Context, Result);
605     }
606     return 0;
607   case Instruction::SExt:
608     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
609       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
610       APInt Result(CI->getValue());
611       Result.sext(BitWidth);
612       return ConstantInt::get(Context, Result);
613     }
614     return 0;
615   case Instruction::Trunc: {
616     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
617     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
618       APInt Result(CI->getValue());
619       Result.trunc(DestBitWidth);
620       return ConstantInt::get(Context, Result);
621     }
622     
623     // The input must be a constantexpr.  See if we can simplify this based on
624     // the bytes we are demanding.  Only do this if the source and dest are an
625     // even multiple of a byte.
626     if ((DestBitWidth & 7) == 0 &&
627         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
628       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
629         return Res;
630       
631     return 0;
632   }
633   case Instruction::BitCast:
634     return FoldBitCast(Context, V, DestTy);
635   }
636 }
637
638 Constant *llvm::ConstantFoldSelectInstruction(LLVMContext&,
639                                               Constant *Cond,
640                                               Constant *V1, Constant *V2) {
641   if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
642     return CB->getZExtValue() ? V1 : V2;
643
644   if (isa<UndefValue>(V1)) return V2;
645   if (isa<UndefValue>(V2)) return V1;
646   if (isa<UndefValue>(Cond)) return V1;
647   if (V1 == V2) return V1;
648   return 0;
649 }
650
651 Constant *llvm::ConstantFoldExtractElementInstruction(LLVMContext &Context,
652                                                       Constant *Val,
653                                                       Constant *Idx) {
654   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
655     return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
656   if (Val->isNullValue())  // ee(zero, x) -> zero
657     return Constant::getNullValue(
658                           cast<VectorType>(Val->getType())->getElementType());
659
660   if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
661     if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
662       return CVal->getOperand(CIdx->getZExtValue());
663     } else if (isa<UndefValue>(Idx)) {
664       // ee({w,x,y,z}, undef) -> w (an arbitrary value).
665       return CVal->getOperand(0);
666     }
667   }
668   return 0;
669 }
670
671 Constant *llvm::ConstantFoldInsertElementInstruction(LLVMContext &Context,
672                                                      Constant *Val,
673                                                      Constant *Elt,
674                                                      Constant *Idx) {
675   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
676   if (!CIdx) return 0;
677   APInt idxVal = CIdx->getValue();
678   if (isa<UndefValue>(Val)) { 
679     // Insertion of scalar constant into vector undef
680     // Optimize away insertion of undef
681     if (isa<UndefValue>(Elt))
682       return Val;
683     // Otherwise break the aggregate undef into multiple undefs and do
684     // the insertion
685     unsigned numOps = 
686       cast<VectorType>(Val->getType())->getNumElements();
687     std::vector<Constant*> Ops; 
688     Ops.reserve(numOps);
689     for (unsigned i = 0; i < numOps; ++i) {
690       Constant *Op =
691         (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
692       Ops.push_back(Op);
693     }
694     return ConstantVector::get(Ops);
695   }
696   if (isa<ConstantAggregateZero>(Val)) {
697     // Insertion of scalar constant into vector aggregate zero
698     // Optimize away insertion of zero
699     if (Elt->isNullValue())
700       return Val;
701     // Otherwise break the aggregate zero into multiple zeros and do
702     // the insertion
703     unsigned numOps = 
704       cast<VectorType>(Val->getType())->getNumElements();
705     std::vector<Constant*> Ops; 
706     Ops.reserve(numOps);
707     for (unsigned i = 0; i < numOps; ++i) {
708       Constant *Op =
709         (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
710       Ops.push_back(Op);
711     }
712     return ConstantVector::get(Ops);
713   }
714   if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
715     // Insertion of scalar constant into vector constant
716     std::vector<Constant*> Ops; 
717     Ops.reserve(CVal->getNumOperands());
718     for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
719       Constant *Op =
720         (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
721       Ops.push_back(Op);
722     }
723     return ConstantVector::get(Ops);
724   }
725
726   return 0;
727 }
728
729 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
730 /// return the specified element value.  Otherwise return null.
731 static Constant *GetVectorElement(LLVMContext &Context, Constant *C,
732                                   unsigned EltNo) {
733   if (ConstantVector *CV = dyn_cast<ConstantVector>(C))
734     return CV->getOperand(EltNo);
735
736   const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
737   if (isa<ConstantAggregateZero>(C))
738     return Constant::getNullValue(EltTy);
739   if (isa<UndefValue>(C))
740     return UndefValue::get(EltTy);
741   return 0;
742 }
743
744 Constant *llvm::ConstantFoldShuffleVectorInstruction(LLVMContext &Context,
745                                                      Constant *V1,
746                                                      Constant *V2,
747                                                      Constant *Mask) {
748   // Undefined shuffle mask -> undefined value.
749   if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
750
751   unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
752   unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
753   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
754
755   // Loop over the shuffle mask, evaluating each element.
756   SmallVector<Constant*, 32> Result;
757   for (unsigned i = 0; i != MaskNumElts; ++i) {
758     Constant *InElt = GetVectorElement(Context, Mask, i);
759     if (InElt == 0) return 0;
760
761     if (isa<UndefValue>(InElt))
762       InElt = UndefValue::get(EltTy);
763     else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
764       unsigned Elt = CI->getZExtValue();
765       if (Elt >= SrcNumElts*2)
766         InElt = UndefValue::get(EltTy);
767       else if (Elt >= SrcNumElts)
768         InElt = GetVectorElement(Context, V2, Elt - SrcNumElts);
769       else
770         InElt = GetVectorElement(Context, V1, Elt);
771       if (InElt == 0) return 0;
772     } else {
773       // Unknown value.
774       return 0;
775     }
776     Result.push_back(InElt);
777   }
778
779   return ConstantVector::get(&Result[0], Result.size());
780 }
781
782 Constant *llvm::ConstantFoldExtractValueInstruction(LLVMContext &Context,
783                                                     Constant *Agg,
784                                                     const unsigned *Idxs,
785                                                     unsigned NumIdx) {
786   // Base case: no indices, so return the entire value.
787   if (NumIdx == 0)
788     return Agg;
789
790   if (isa<UndefValue>(Agg))  // ev(undef, x) -> undef
791     return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
792                                                             Idxs,
793                                                             Idxs + NumIdx));
794
795   if (isa<ConstantAggregateZero>(Agg))  // ev(0, x) -> 0
796     return
797       Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
798                                                               Idxs,
799                                                               Idxs + NumIdx));
800
801   // Otherwise recurse.
802   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg))
803     return ConstantFoldExtractValueInstruction(Context, CS->getOperand(*Idxs),
804                                                Idxs+1, NumIdx-1);
805
806   if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg))
807     return ConstantFoldExtractValueInstruction(Context, CA->getOperand(*Idxs),
808                                                Idxs+1, NumIdx-1);
809   ConstantVector *CV = cast<ConstantVector>(Agg);
810   return ConstantFoldExtractValueInstruction(Context, CV->getOperand(*Idxs),
811                                              Idxs+1, NumIdx-1);
812 }
813
814 Constant *llvm::ConstantFoldInsertValueInstruction(LLVMContext &Context,
815                                                    Constant *Agg,
816                                                    Constant *Val,
817                                                    const unsigned *Idxs,
818                                                    unsigned NumIdx) {
819   // Base case: no indices, so replace the entire value.
820   if (NumIdx == 0)
821     return Val;
822
823   if (isa<UndefValue>(Agg)) {
824     // Insertion of constant into aggregate undef
825     // Optimize away insertion of undef.
826     if (isa<UndefValue>(Val))
827       return Agg;
828     
829     // Otherwise break the aggregate undef into multiple undefs and do
830     // the insertion.
831     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
832     unsigned numOps;
833     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
834       numOps = AR->getNumElements();
835     else
836       numOps = cast<StructType>(AggTy)->getNumElements();
837     
838     std::vector<Constant*> Ops(numOps); 
839     for (unsigned i = 0; i < numOps; ++i) {
840       const Type *MemberTy = AggTy->getTypeAtIndex(i);
841       Constant *Op =
842         (*Idxs == i) ?
843         ConstantFoldInsertValueInstruction(Context, UndefValue::get(MemberTy),
844                                            Val, Idxs+1, NumIdx-1) :
845         UndefValue::get(MemberTy);
846       Ops[i] = Op;
847     }
848     
849     if (const StructType* ST = dyn_cast<StructType>(AggTy))
850       return ConstantStruct::get(Context, Ops, ST->isPacked());
851     return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
852   }
853   
854   if (isa<ConstantAggregateZero>(Agg)) {
855     // Insertion of constant into aggregate zero
856     // Optimize away insertion of zero.
857     if (Val->isNullValue())
858       return Agg;
859     
860     // Otherwise break the aggregate zero into multiple zeros and do
861     // the insertion.
862     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
863     unsigned numOps;
864     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
865       numOps = AR->getNumElements();
866     else
867       numOps = cast<StructType>(AggTy)->getNumElements();
868     
869     std::vector<Constant*> Ops(numOps);
870     for (unsigned i = 0; i < numOps; ++i) {
871       const Type *MemberTy = AggTy->getTypeAtIndex(i);
872       Constant *Op =
873         (*Idxs == i) ?
874         ConstantFoldInsertValueInstruction(Context, 
875                                            Constant::getNullValue(MemberTy),
876                                            Val, Idxs+1, NumIdx-1) :
877         Constant::getNullValue(MemberTy);
878       Ops[i] = Op;
879     }
880     
881     if (const StructType* ST = dyn_cast<StructType>(AggTy))
882       return ConstantStruct::get(Context, Ops, ST->isPacked());
883     return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
884   }
885   
886   if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
887     // Insertion of constant into aggregate constant.
888     std::vector<Constant*> Ops(Agg->getNumOperands());
889     for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
890       Constant *Op = cast<Constant>(Agg->getOperand(i));
891       if (*Idxs == i)
892         Op = ConstantFoldInsertValueInstruction(Context, Op,
893                                                 Val, Idxs+1, NumIdx-1);
894       Ops[i] = Op;
895     }
896     
897     if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
898       return ConstantStruct::get(Context, Ops, ST->isPacked());
899     return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
900   }
901
902   return 0;
903 }
904
905
906 Constant *llvm::ConstantFoldBinaryInstruction(LLVMContext &Context,
907                                               unsigned Opcode,
908                                               Constant *C1, Constant *C2) {
909   // No compile-time operations on this type yet.
910   if (C1->getType()->isPPC_FP128Ty())
911     return 0;
912
913   // Handle UndefValue up front.
914   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
915     switch (Opcode) {
916     case Instruction::Xor:
917       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
918         // Handle undef ^ undef -> 0 special case. This is a common
919         // idiom (misuse).
920         return Constant::getNullValue(C1->getType());
921       // Fallthrough
922     case Instruction::Add:
923     case Instruction::Sub:
924       return UndefValue::get(C1->getType());
925     case Instruction::Mul:
926     case Instruction::And:
927       return Constant::getNullValue(C1->getType());
928     case Instruction::UDiv:
929     case Instruction::SDiv:
930     case Instruction::URem:
931     case Instruction::SRem:
932       if (!isa<UndefValue>(C2))                    // undef / X -> 0
933         return Constant::getNullValue(C1->getType());
934       return C2;                                   // X / undef -> undef
935     case Instruction::Or:                          // X | undef -> -1
936       if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
937         return Constant::getAllOnesValue(PTy);
938       return Constant::getAllOnesValue(C1->getType());
939     case Instruction::LShr:
940       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
941         return C1;                                  // undef lshr undef -> undef
942       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
943                                                     // undef lshr X -> 0
944     case Instruction::AShr:
945       if (!isa<UndefValue>(C2))
946         return C1;                                  // undef ashr X --> undef
947       else if (isa<UndefValue>(C1)) 
948         return C1;                                  // undef ashr undef -> undef
949       else
950         return C1;                                  // X ashr undef --> X
951     case Instruction::Shl:
952       // undef << X -> 0   or   X << undef -> 0
953       return Constant::getNullValue(C1->getType());
954     }
955   }
956
957   // Handle simplifications when the RHS is a constant int.
958   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
959     switch (Opcode) {
960     case Instruction::Add:
961       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
962       break;
963     case Instruction::Sub:
964       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
965       break;
966     case Instruction::Mul:
967       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
968       if (CI2->equalsInt(1))
969         return C1;                                              // X * 1 == X
970       break;
971     case Instruction::UDiv:
972     case Instruction::SDiv:
973       if (CI2->equalsInt(1))
974         return C1;                                            // X / 1 == X
975       if (CI2->equalsInt(0))
976         return UndefValue::get(CI2->getType());               // X / 0 == undef
977       break;
978     case Instruction::URem:
979     case Instruction::SRem:
980       if (CI2->equalsInt(1))
981         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
982       if (CI2->equalsInt(0))
983         return UndefValue::get(CI2->getType());               // X % 0 == undef
984       break;
985     case Instruction::And:
986       if (CI2->isZero()) return C2;                           // X & 0 == 0
987       if (CI2->isAllOnesValue())
988         return C1;                                            // X & -1 == X
989
990       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
991         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
992         if (CE1->getOpcode() == Instruction::ZExt) {
993           unsigned DstWidth = CI2->getType()->getBitWidth();
994           unsigned SrcWidth =
995             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
996           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
997           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
998             return C1;
999         }
1000
1001         // If and'ing the address of a global with a constant, fold it.
1002         if (CE1->getOpcode() == Instruction::PtrToInt && 
1003             isa<GlobalValue>(CE1->getOperand(0))) {
1004           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1005
1006           // Functions are at least 4-byte aligned.
1007           unsigned GVAlign = GV->getAlignment();
1008           if (isa<Function>(GV))
1009             GVAlign = std::max(GVAlign, 4U);
1010
1011           if (GVAlign > 1) {
1012             unsigned DstWidth = CI2->getType()->getBitWidth();
1013             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1014             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1015
1016             // If checking bits we know are clear, return zero.
1017             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1018               return Constant::getNullValue(CI2->getType());
1019           }
1020         }
1021       }
1022       break;
1023     case Instruction::Or:
1024       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
1025       if (CI2->isAllOnesValue())
1026         return C2;                         // X | -1 == -1
1027       break;
1028     case Instruction::Xor:
1029       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
1030
1031       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1032         switch (CE1->getOpcode()) {
1033         default: break;
1034         case Instruction::ICmp:
1035         case Instruction::FCmp:
1036           // cmp pred ^ true -> cmp !pred
1037           assert(CI2->equalsInt(1));
1038           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1039           pred = CmpInst::getInversePredicate(pred);
1040           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1041                                           CE1->getOperand(1));
1042         }
1043       }
1044       break;
1045     case Instruction::AShr:
1046       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1047       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1048         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1049           return ConstantExpr::getLShr(C1, C2);
1050       break;
1051     }
1052   }
1053
1054   // At this point we know neither constant is an UndefValue.
1055   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1056     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1057       using namespace APIntOps;
1058       const APInt &C1V = CI1->getValue();
1059       const APInt &C2V = CI2->getValue();
1060       switch (Opcode) {
1061       default:
1062         break;
1063       case Instruction::Add:     
1064         return ConstantInt::get(Context, C1V + C2V);
1065       case Instruction::Sub:     
1066         return ConstantInt::get(Context, C1V - C2V);
1067       case Instruction::Mul:     
1068         return ConstantInt::get(Context, C1V * C2V);
1069       case Instruction::UDiv:
1070         assert(!CI2->isNullValue() && "Div by zero handled above");
1071         return ConstantInt::get(Context, C1V.udiv(C2V));
1072       case Instruction::SDiv:
1073         assert(!CI2->isNullValue() && "Div by zero handled above");
1074         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1075           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1076         return ConstantInt::get(Context, C1V.sdiv(C2V));
1077       case Instruction::URem:
1078         assert(!CI2->isNullValue() && "Div by zero handled above");
1079         return ConstantInt::get(Context, C1V.urem(C2V));
1080       case Instruction::SRem:
1081         assert(!CI2->isNullValue() && "Div by zero handled above");
1082         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1083           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1084         return ConstantInt::get(Context, C1V.srem(C2V));
1085       case Instruction::And:
1086         return ConstantInt::get(Context, C1V & C2V);
1087       case Instruction::Or:
1088         return ConstantInt::get(Context, C1V | C2V);
1089       case Instruction::Xor:
1090         return ConstantInt::get(Context, C1V ^ C2V);
1091       case Instruction::Shl: {
1092         uint32_t shiftAmt = C2V.getZExtValue();
1093         if (shiftAmt < C1V.getBitWidth())
1094           return ConstantInt::get(Context, C1V.shl(shiftAmt));
1095         else
1096           return UndefValue::get(C1->getType()); // too big shift is undef
1097       }
1098       case Instruction::LShr: {
1099         uint32_t shiftAmt = C2V.getZExtValue();
1100         if (shiftAmt < C1V.getBitWidth())
1101           return ConstantInt::get(Context, C1V.lshr(shiftAmt));
1102         else
1103           return UndefValue::get(C1->getType()); // too big shift is undef
1104       }
1105       case Instruction::AShr: {
1106         uint32_t shiftAmt = C2V.getZExtValue();
1107         if (shiftAmt < C1V.getBitWidth())
1108           return ConstantInt::get(Context, C1V.ashr(shiftAmt));
1109         else
1110           return UndefValue::get(C1->getType()); // too big shift is undef
1111       }
1112       }
1113     }
1114
1115     switch (Opcode) {
1116     case Instruction::SDiv:
1117     case Instruction::UDiv:
1118     case Instruction::URem:
1119     case Instruction::SRem:
1120     case Instruction::LShr:
1121     case Instruction::AShr:
1122     case Instruction::Shl:
1123       if (CI1->equalsInt(0)) return C1;
1124       break;
1125     default:
1126       break;
1127     }
1128   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1129     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1130       APFloat C1V = CFP1->getValueAPF();
1131       APFloat C2V = CFP2->getValueAPF();
1132       APFloat C3V = C1V;  // copy for modification
1133       switch (Opcode) {
1134       default:                   
1135         break;
1136       case Instruction::FAdd:
1137         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1138         return ConstantFP::get(Context, C3V);
1139       case Instruction::FSub:
1140         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1141         return ConstantFP::get(Context, C3V);
1142       case Instruction::FMul:
1143         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1144         return ConstantFP::get(Context, C3V);
1145       case Instruction::FDiv:
1146         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1147         return ConstantFP::get(Context, C3V);
1148       case Instruction::FRem:
1149         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1150         return ConstantFP::get(Context, C3V);
1151       }
1152     }
1153   } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1154     ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
1155     ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
1156     if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
1157         (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
1158       std::vector<Constant*> Res;
1159       const Type* EltTy = VTy->getElementType();  
1160       Constant *C1 = 0;
1161       Constant *C2 = 0;
1162       switch (Opcode) {
1163       default:
1164         break;
1165       case Instruction::Add:
1166         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1167           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1168           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1169           Res.push_back(ConstantExpr::getAdd(C1, C2));
1170         }
1171         return ConstantVector::get(Res);
1172       case Instruction::FAdd:
1173         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1174           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1175           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1176           Res.push_back(ConstantExpr::getFAdd(C1, C2));
1177         }
1178         return ConstantVector::get(Res);
1179       case Instruction::Sub:
1180         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1181           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1182           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1183           Res.push_back(ConstantExpr::getSub(C1, C2));
1184         }
1185         return ConstantVector::get(Res);
1186       case Instruction::FSub:
1187         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1188           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1189           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1190           Res.push_back(ConstantExpr::getFSub(C1, C2));
1191         }
1192         return ConstantVector::get(Res);
1193       case Instruction::Mul:
1194         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1195           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1196           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1197           Res.push_back(ConstantExpr::getMul(C1, C2));
1198         }
1199         return ConstantVector::get(Res);
1200       case Instruction::FMul:
1201         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1202           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1203           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1204           Res.push_back(ConstantExpr::getFMul(C1, C2));
1205         }
1206         return ConstantVector::get(Res);
1207       case Instruction::UDiv:
1208         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1209           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1210           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1211           Res.push_back(ConstantExpr::getUDiv(C1, C2));
1212         }
1213         return ConstantVector::get(Res);
1214       case Instruction::SDiv:
1215         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1216           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1217           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1218           Res.push_back(ConstantExpr::getSDiv(C1, C2));
1219         }
1220         return ConstantVector::get(Res);
1221       case Instruction::FDiv:
1222         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1223           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1224           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1225           Res.push_back(ConstantExpr::getFDiv(C1, C2));
1226         }
1227         return ConstantVector::get(Res);
1228       case Instruction::URem:
1229         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1230           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1231           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1232           Res.push_back(ConstantExpr::getURem(C1, C2));
1233         }
1234         return ConstantVector::get(Res);
1235       case Instruction::SRem:
1236         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1237           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1238           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1239           Res.push_back(ConstantExpr::getSRem(C1, C2));
1240         }
1241         return ConstantVector::get(Res);
1242       case Instruction::FRem:
1243         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1244           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1245           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1246           Res.push_back(ConstantExpr::getFRem(C1, C2));
1247         }
1248         return ConstantVector::get(Res);
1249       case Instruction::And: 
1250         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1251           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1252           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1253           Res.push_back(ConstantExpr::getAnd(C1, C2));
1254         }
1255         return ConstantVector::get(Res);
1256       case Instruction::Or:
1257         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1258           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1259           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1260           Res.push_back(ConstantExpr::getOr(C1, C2));
1261         }
1262         return ConstantVector::get(Res);
1263       case Instruction::Xor:
1264         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1265           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1266           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1267           Res.push_back(ConstantExpr::getXor(C1, C2));
1268         }
1269         return ConstantVector::get(Res);
1270       case Instruction::LShr:
1271         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1272           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1273           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1274           Res.push_back(ConstantExpr::getLShr(C1, C2));
1275         }
1276         return ConstantVector::get(Res);
1277       case Instruction::AShr:
1278         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1279           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1280           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1281           Res.push_back(ConstantExpr::getAShr(C1, C2));
1282         }
1283         return ConstantVector::get(Res);
1284       case Instruction::Shl:
1285         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1286           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1287           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1288           Res.push_back(ConstantExpr::getShl(C1, C2));
1289         }
1290         return ConstantVector::get(Res);
1291       }
1292     }
1293   }
1294
1295   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1296     // There are many possible foldings we could do here.  We should probably
1297     // at least fold add of a pointer with an integer into the appropriate
1298     // getelementptr.  This will improve alias analysis a bit.
1299
1300     // Given ((a + b) + c), if (b + c) folds to something interesting, return
1301     // (a + (b + c)).
1302     if (Instruction::isAssociative(Opcode, C1->getType()) &&
1303         CE1->getOpcode() == Opcode) {
1304       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1305       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1306         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1307     }
1308   } else if (isa<ConstantExpr>(C2)) {
1309     // If C2 is a constant expr and C1 isn't, flop them around and fold the
1310     // other way if possible.
1311     switch (Opcode) {
1312     case Instruction::Add:
1313     case Instruction::FAdd:
1314     case Instruction::Mul:
1315     case Instruction::FMul:
1316     case Instruction::And:
1317     case Instruction::Or:
1318     case Instruction::Xor:
1319       // No change of opcode required.
1320       return ConstantFoldBinaryInstruction(Context, Opcode, C2, C1);
1321
1322     case Instruction::Shl:
1323     case Instruction::LShr:
1324     case Instruction::AShr:
1325     case Instruction::Sub:
1326     case Instruction::FSub:
1327     case Instruction::SDiv:
1328     case Instruction::UDiv:
1329     case Instruction::FDiv:
1330     case Instruction::URem:
1331     case Instruction::SRem:
1332     case Instruction::FRem:
1333     default:  // These instructions cannot be flopped around.
1334       break;
1335     }
1336   }
1337
1338   // i1 can be simplified in many cases.
1339   if (C1->getType()->isInteger(1)) {
1340     switch (Opcode) {
1341     case Instruction::Add:
1342     case Instruction::Sub:
1343       return ConstantExpr::getXor(C1, C2);
1344     case Instruction::Mul:
1345       return ConstantExpr::getAnd(C1, C2);
1346     case Instruction::Shl:
1347     case Instruction::LShr:
1348     case Instruction::AShr:
1349       // We can assume that C2 == 0.  If it were one the result would be
1350       // undefined because the shift value is as large as the bitwidth.
1351       return C1;
1352     case Instruction::SDiv:
1353     case Instruction::UDiv:
1354       // We can assume that C2 == 1.  If it were zero the result would be
1355       // undefined through division by zero.
1356       return C1;
1357     case Instruction::URem:
1358     case Instruction::SRem:
1359       // We can assume that C2 == 1.  If it were zero the result would be
1360       // undefined through division by zero.
1361       return ConstantInt::getFalse(Context);
1362     default:
1363       break;
1364     }
1365   }
1366
1367   // We don't know how to fold this.
1368   return 0;
1369 }
1370
1371 /// isZeroSizedType - This type is zero sized if its an array or structure of
1372 /// zero sized types.  The only leaf zero sized type is an empty structure.
1373 static bool isMaybeZeroSizedType(const Type *Ty) {
1374   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
1375   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1376
1377     // If all of elements have zero size, this does too.
1378     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1379       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1380     return true;
1381
1382   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1383     return isMaybeZeroSizedType(ATy->getElementType());
1384   }
1385   return false;
1386 }
1387
1388 /// IdxCompare - Compare the two constants as though they were getelementptr
1389 /// indices.  This allows coersion of the types to be the same thing.
1390 ///
1391 /// If the two constants are the "same" (after coersion), return 0.  If the
1392 /// first is less than the second, return -1, if the second is less than the
1393 /// first, return 1.  If the constants are not integral, return -2.
1394 ///
1395 static int IdxCompare(LLVMContext &Context, Constant *C1, Constant *C2, 
1396                       const Type *ElTy) {
1397   if (C1 == C2) return 0;
1398
1399   // Ok, we found a different index.  If they are not ConstantInt, we can't do
1400   // anything with them.
1401   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1402     return -2; // don't know!
1403
1404   // Ok, we have two differing integer indices.  Sign extend them to be the same
1405   // type.  Long is always big enough, so we use it.
1406   if (!C1->getType()->isInteger(64))
1407     C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(Context));
1408
1409   if (!C2->getType()->isInteger(64))
1410     C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(Context));
1411
1412   if (C1 == C2) return 0;  // They are equal
1413
1414   // If the type being indexed over is really just a zero sized type, there is
1415   // no pointer difference being made here.
1416   if (isMaybeZeroSizedType(ElTy))
1417     return -2; // dunno.
1418
1419   // If they are really different, now that they are the same type, then we
1420   // found a difference!
1421   if (cast<ConstantInt>(C1)->getSExtValue() < 
1422       cast<ConstantInt>(C2)->getSExtValue())
1423     return -1;
1424   else
1425     return 1;
1426 }
1427
1428 /// evaluateFCmpRelation - This function determines if there is anything we can
1429 /// decide about the two constants provided.  This doesn't need to handle simple
1430 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1431 /// If we can determine that the two constants have a particular relation to 
1432 /// each other, we should return the corresponding FCmpInst predicate, 
1433 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1434 /// ConstantFoldCompareInstruction.
1435 ///
1436 /// To simplify this code we canonicalize the relation so that the first
1437 /// operand is always the most "complex" of the two.  We consider ConstantFP
1438 /// to be the simplest, and ConstantExprs to be the most complex.
1439 static FCmpInst::Predicate evaluateFCmpRelation(LLVMContext &Context,
1440                                                 Constant *V1, Constant *V2) {
1441   assert(V1->getType() == V2->getType() &&
1442          "Cannot compare values of different types!");
1443
1444   // No compile-time operations on this type yet.
1445   if (V1->getType()->isPPC_FP128Ty())
1446     return FCmpInst::BAD_FCMP_PREDICATE;
1447
1448   // Handle degenerate case quickly
1449   if (V1 == V2) return FCmpInst::FCMP_OEQ;
1450
1451   if (!isa<ConstantExpr>(V1)) {
1452     if (!isa<ConstantExpr>(V2)) {
1453       // We distilled thisUse the standard constant folder for a few cases
1454       ConstantInt *R = 0;
1455       R = dyn_cast<ConstantInt>(
1456                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1457       if (R && !R->isZero()) 
1458         return FCmpInst::FCMP_OEQ;
1459       R = dyn_cast<ConstantInt>(
1460                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1461       if (R && !R->isZero()) 
1462         return FCmpInst::FCMP_OLT;
1463       R = dyn_cast<ConstantInt>(
1464                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1465       if (R && !R->isZero()) 
1466         return FCmpInst::FCMP_OGT;
1467
1468       // Nothing more we can do
1469       return FCmpInst::BAD_FCMP_PREDICATE;
1470     }
1471
1472     // If the first operand is simple and second is ConstantExpr, swap operands.
1473     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(Context, V2, V1);
1474     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1475       return FCmpInst::getSwappedPredicate(SwappedRelation);
1476   } else {
1477     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1478     // constantexpr or a simple constant.
1479     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1480     switch (CE1->getOpcode()) {
1481     case Instruction::FPTrunc:
1482     case Instruction::FPExt:
1483     case Instruction::UIToFP:
1484     case Instruction::SIToFP:
1485       // We might be able to do something with these but we don't right now.
1486       break;
1487     default:
1488       break;
1489     }
1490   }
1491   // There are MANY other foldings that we could perform here.  They will
1492   // probably be added on demand, as they seem needed.
1493   return FCmpInst::BAD_FCMP_PREDICATE;
1494 }
1495
1496 /// evaluateICmpRelation - This function determines if there is anything we can
1497 /// decide about the two constants provided.  This doesn't need to handle simple
1498 /// things like integer comparisons, but should instead handle ConstantExprs
1499 /// and GlobalValues.  If we can determine that the two constants have a
1500 /// particular relation to each other, we should return the corresponding ICmp
1501 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1502 ///
1503 /// To simplify this code we canonicalize the relation so that the first
1504 /// operand is always the most "complex" of the two.  We consider simple
1505 /// constants (like ConstantInt) to be the simplest, followed by
1506 /// GlobalValues, followed by ConstantExpr's (the most complex).
1507 ///
1508 static ICmpInst::Predicate evaluateICmpRelation(LLVMContext &Context,
1509                                                 Constant *V1, 
1510                                                 Constant *V2,
1511                                                 bool isSigned) {
1512   assert(V1->getType() == V2->getType() &&
1513          "Cannot compare different types of values!");
1514   if (V1 == V2) return ICmpInst::ICMP_EQ;
1515
1516   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
1517     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1518       // We distilled this down to a simple case, use the standard constant
1519       // folder.
1520       ConstantInt *R = 0;
1521       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1522       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1523       if (R && !R->isZero()) 
1524         return pred;
1525       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1526       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1527       if (R && !R->isZero())
1528         return pred;
1529       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1530       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1531       if (R && !R->isZero())
1532         return pred;
1533
1534       // If we couldn't figure it out, bail.
1535       return ICmpInst::BAD_ICMP_PREDICATE;
1536     }
1537
1538     // If the first operand is simple, swap operands.
1539     ICmpInst::Predicate SwappedRelation = 
1540       evaluateICmpRelation(Context, V2, V1, isSigned);
1541     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1542       return ICmpInst::getSwappedPredicate(SwappedRelation);
1543
1544   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
1545     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1546       ICmpInst::Predicate SwappedRelation = 
1547         evaluateICmpRelation(Context, V2, V1, isSigned);
1548       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1549         return ICmpInst::getSwappedPredicate(SwappedRelation);
1550       else
1551         return ICmpInst::BAD_ICMP_PREDICATE;
1552     }
1553
1554     // Now we know that the RHS is a GlobalValue or simple constant,
1555     // which (since the types must match) means that it's a ConstantPointerNull.
1556     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1557       // Don't try to decide equality of aliases.
1558       if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
1559         if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
1560           return ICmpInst::ICMP_NE;
1561     } else {
1562       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1563       // GlobalVals can never be null.  Don't try to evaluate aliases.
1564       if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
1565         return ICmpInst::ICMP_NE;
1566     }
1567   } else {
1568     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1569     // constantexpr, a CPR, or a simple constant.
1570     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1571     Constant *CE1Op0 = CE1->getOperand(0);
1572
1573     switch (CE1->getOpcode()) {
1574     case Instruction::Trunc:
1575     case Instruction::FPTrunc:
1576     case Instruction::FPExt:
1577     case Instruction::FPToUI:
1578     case Instruction::FPToSI:
1579       break; // We can't evaluate floating point casts or truncations.
1580
1581     case Instruction::UIToFP:
1582     case Instruction::SIToFP:
1583     case Instruction::BitCast:
1584     case Instruction::ZExt:
1585     case Instruction::SExt:
1586       // If the cast is not actually changing bits, and the second operand is a
1587       // null pointer, do the comparison with the pre-casted value.
1588       if (V2->isNullValue() &&
1589           (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
1590         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1591         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1592         return evaluateICmpRelation(Context, CE1Op0,
1593                                     Constant::getNullValue(CE1Op0->getType()), 
1594                                     isSigned);
1595       }
1596       break;
1597
1598     case Instruction::GetElementPtr:
1599       // Ok, since this is a getelementptr, we know that the constant has a
1600       // pointer type.  Check the various cases.
1601       if (isa<ConstantPointerNull>(V2)) {
1602         // If we are comparing a GEP to a null pointer, check to see if the base
1603         // of the GEP equals the null pointer.
1604         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1605           if (GV->hasExternalWeakLinkage())
1606             // Weak linkage GVals could be zero or not. We're comparing that
1607             // to null pointer so its greater-or-equal
1608             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1609           else 
1610             // If its not weak linkage, the GVal must have a non-zero address
1611             // so the result is greater-than
1612             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1613         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1614           // If we are indexing from a null pointer, check to see if we have any
1615           // non-zero indices.
1616           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1617             if (!CE1->getOperand(i)->isNullValue())
1618               // Offsetting from null, must not be equal.
1619               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1620           // Only zero indexes from null, must still be zero.
1621           return ICmpInst::ICMP_EQ;
1622         }
1623         // Otherwise, we can't really say if the first operand is null or not.
1624       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1625         if (isa<ConstantPointerNull>(CE1Op0)) {
1626           if (CPR2->hasExternalWeakLinkage())
1627             // Weak linkage GVals could be zero or not. We're comparing it to
1628             // a null pointer, so its less-or-equal
1629             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1630           else
1631             // If its not weak linkage, the GVal must have a non-zero address
1632             // so the result is less-than
1633             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1634         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1635           if (CPR1 == CPR2) {
1636             // If this is a getelementptr of the same global, then it must be
1637             // different.  Because the types must match, the getelementptr could
1638             // only have at most one index, and because we fold getelementptr's
1639             // with a single zero index, it must be nonzero.
1640             assert(CE1->getNumOperands() == 2 &&
1641                    !CE1->getOperand(1)->isNullValue() &&
1642                    "Suprising getelementptr!");
1643             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1644           } else {
1645             // If they are different globals, we don't know what the value is,
1646             // but they can't be equal.
1647             return ICmpInst::ICMP_NE;
1648           }
1649         }
1650       } else {
1651         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1652         Constant *CE2Op0 = CE2->getOperand(0);
1653
1654         // There are MANY other foldings that we could perform here.  They will
1655         // probably be added on demand, as they seem needed.
1656         switch (CE2->getOpcode()) {
1657         default: break;
1658         case Instruction::GetElementPtr:
1659           // By far the most common case to handle is when the base pointers are
1660           // obviously to the same or different globals.
1661           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1662             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1663               return ICmpInst::ICMP_NE;
1664             // Ok, we know that both getelementptr instructions are based on the
1665             // same global.  From this, we can precisely determine the relative
1666             // ordering of the resultant pointers.
1667             unsigned i = 1;
1668
1669             // The logic below assumes that the result of the comparison
1670             // can be determined by finding the first index that differs.
1671             // This doesn't work if there is over-indexing in any
1672             // subsequent indices, so check for that case first.
1673             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1674                 !CE2->isGEPWithNoNotionalOverIndexing())
1675                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1676
1677             // Compare all of the operands the GEP's have in common.
1678             gep_type_iterator GTI = gep_type_begin(CE1);
1679             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1680                  ++i, ++GTI)
1681               switch (IdxCompare(Context, CE1->getOperand(i),
1682                                  CE2->getOperand(i), GTI.getIndexedType())) {
1683               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1684               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1685               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1686               }
1687
1688             // Ok, we ran out of things they have in common.  If any leftovers
1689             // are non-zero then we have a difference, otherwise we are equal.
1690             for (; i < CE1->getNumOperands(); ++i)
1691               if (!CE1->getOperand(i)->isNullValue()) {
1692                 if (isa<ConstantInt>(CE1->getOperand(i)))
1693                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1694                 else
1695                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1696               }
1697
1698             for (; i < CE2->getNumOperands(); ++i)
1699               if (!CE2->getOperand(i)->isNullValue()) {
1700                 if (isa<ConstantInt>(CE2->getOperand(i)))
1701                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1702                 else
1703                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1704               }
1705             return ICmpInst::ICMP_EQ;
1706           }
1707         }
1708       }
1709     default:
1710       break;
1711     }
1712   }
1713
1714   return ICmpInst::BAD_ICMP_PREDICATE;
1715 }
1716
1717 Constant *llvm::ConstantFoldCompareInstruction(LLVMContext &Context,
1718                                                unsigned short pred, 
1719                                                Constant *C1, Constant *C2) {
1720   const Type *ResultTy;
1721   if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1722     ResultTy = VectorType::get(Type::getInt1Ty(Context), VT->getNumElements());
1723   else
1724     ResultTy = Type::getInt1Ty(Context);
1725
1726   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1727   if (pred == FCmpInst::FCMP_FALSE)
1728     return Constant::getNullValue(ResultTy);
1729
1730   if (pred == FCmpInst::FCMP_TRUE)
1731     return Constant::getAllOnesValue(ResultTy);
1732
1733   // Handle some degenerate cases first
1734   if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1735     return UndefValue::get(ResultTy);
1736
1737   // No compile-time operations on this type yet.
1738   if (C1->getType()->isPPC_FP128Ty())
1739     return 0;
1740
1741   // icmp eq/ne(null,GV) -> false/true
1742   if (C1->isNullValue()) {
1743     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1744       // Don't try to evaluate aliases.  External weak GV can be null.
1745       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1746         if (pred == ICmpInst::ICMP_EQ)
1747           return ConstantInt::getFalse(Context);
1748         else if (pred == ICmpInst::ICMP_NE)
1749           return ConstantInt::getTrue(Context);
1750       }
1751   // icmp eq/ne(GV,null) -> false/true
1752   } else if (C2->isNullValue()) {
1753     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1754       // Don't try to evaluate aliases.  External weak GV can be null.
1755       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1756         if (pred == ICmpInst::ICMP_EQ)
1757           return ConstantInt::getFalse(Context);
1758         else if (pred == ICmpInst::ICMP_NE)
1759           return ConstantInt::getTrue(Context);
1760       }
1761   }
1762
1763   // If the comparison is a comparison between two i1's, simplify it.
1764   if (C1->getType()->isInteger(1)) {
1765     switch(pred) {
1766     case ICmpInst::ICMP_EQ:
1767       if (isa<ConstantInt>(C2))
1768         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1769       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1770     case ICmpInst::ICMP_NE:
1771       return ConstantExpr::getXor(C1, C2);
1772     default:
1773       break;
1774     }
1775   }
1776
1777   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1778     APInt V1 = cast<ConstantInt>(C1)->getValue();
1779     APInt V2 = cast<ConstantInt>(C2)->getValue();
1780     switch (pred) {
1781     default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
1782     case ICmpInst::ICMP_EQ:
1783       return ConstantInt::get(Type::getInt1Ty(Context), V1 == V2);
1784     case ICmpInst::ICMP_NE: 
1785       return ConstantInt::get(Type::getInt1Ty(Context), V1 != V2);
1786     case ICmpInst::ICMP_SLT:
1787       return ConstantInt::get(Type::getInt1Ty(Context), V1.slt(V2));
1788     case ICmpInst::ICMP_SGT:
1789       return ConstantInt::get(Type::getInt1Ty(Context), V1.sgt(V2));
1790     case ICmpInst::ICMP_SLE:
1791       return ConstantInt::get(Type::getInt1Ty(Context), V1.sle(V2));
1792     case ICmpInst::ICMP_SGE:
1793       return ConstantInt::get(Type::getInt1Ty(Context), V1.sge(V2));
1794     case ICmpInst::ICMP_ULT:
1795       return ConstantInt::get(Type::getInt1Ty(Context), V1.ult(V2));
1796     case ICmpInst::ICMP_UGT:
1797       return ConstantInt::get(Type::getInt1Ty(Context), V1.ugt(V2));
1798     case ICmpInst::ICMP_ULE:
1799       return ConstantInt::get(Type::getInt1Ty(Context), V1.ule(V2));
1800     case ICmpInst::ICMP_UGE:
1801       return ConstantInt::get(Type::getInt1Ty(Context), V1.uge(V2));
1802     }
1803   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1804     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1805     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1806     APFloat::cmpResult R = C1V.compare(C2V);
1807     switch (pred) {
1808     default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
1809     case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse(Context);
1810     case FCmpInst::FCMP_TRUE:  return ConstantInt::getTrue(Context);
1811     case FCmpInst::FCMP_UNO:
1812       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered);
1813     case FCmpInst::FCMP_ORD:
1814       return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpUnordered);
1815     case FCmpInst::FCMP_UEQ:
1816       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1817                                             R==APFloat::cmpEqual);
1818     case FCmpInst::FCMP_OEQ:   
1819       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpEqual);
1820     case FCmpInst::FCMP_UNE:
1821       return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpEqual);
1822     case FCmpInst::FCMP_ONE:   
1823       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
1824                                             R==APFloat::cmpGreaterThan);
1825     case FCmpInst::FCMP_ULT: 
1826       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1827                                             R==APFloat::cmpLessThan);
1828     case FCmpInst::FCMP_OLT:   
1829       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan);
1830     case FCmpInst::FCMP_UGT:
1831       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1832                                             R==APFloat::cmpGreaterThan);
1833     case FCmpInst::FCMP_OGT:
1834       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan);
1835     case FCmpInst::FCMP_ULE:
1836       return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpGreaterThan);
1837     case FCmpInst::FCMP_OLE: 
1838       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
1839                                             R==APFloat::cmpEqual);
1840     case FCmpInst::FCMP_UGE:
1841       return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpLessThan);
1842     case FCmpInst::FCMP_OGE: 
1843       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan ||
1844                                             R==APFloat::cmpEqual);
1845     }
1846   } else if (isa<VectorType>(C1->getType())) {
1847     SmallVector<Constant*, 16> C1Elts, C2Elts;
1848     C1->getVectorElements(Context, C1Elts);
1849     C2->getVectorElements(Context, C2Elts);
1850     if (C1Elts.empty() || C2Elts.empty())
1851       return 0;
1852
1853     // If we can constant fold the comparison of each element, constant fold
1854     // the whole vector comparison.
1855     SmallVector<Constant*, 4> ResElts;
1856     for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1857       // Compare the elements, producing an i1 result or constant expr.
1858       ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
1859     }
1860     return ConstantVector::get(&ResElts[0], ResElts.size());
1861   }
1862
1863   if (C1->getType()->isFloatingPoint()) {
1864     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1865     switch (evaluateFCmpRelation(Context, C1, C2)) {
1866     default: llvm_unreachable("Unknown relation!");
1867     case FCmpInst::FCMP_UNO:
1868     case FCmpInst::FCMP_ORD:
1869     case FCmpInst::FCMP_UEQ:
1870     case FCmpInst::FCMP_UNE:
1871     case FCmpInst::FCMP_ULT:
1872     case FCmpInst::FCMP_UGT:
1873     case FCmpInst::FCMP_ULE:
1874     case FCmpInst::FCMP_UGE:
1875     case FCmpInst::FCMP_TRUE:
1876     case FCmpInst::FCMP_FALSE:
1877     case FCmpInst::BAD_FCMP_PREDICATE:
1878       break; // Couldn't determine anything about these constants.
1879     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1880       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1881                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1882                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1883       break;
1884     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1885       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1886                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1887                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1888       break;
1889     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1890       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1891                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1892                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1893       break;
1894     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1895       // We can only partially decide this relation.
1896       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1897         Result = 0;
1898       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1899         Result = 1;
1900       break;
1901     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1902       // We can only partially decide this relation.
1903       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1904         Result = 0;
1905       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1906         Result = 1;
1907       break;
1908     case ICmpInst::ICMP_NE: // We know that C1 != C2
1909       // We can only partially decide this relation.
1910       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1911         Result = 0;
1912       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1913         Result = 1;
1914       break;
1915     }
1916
1917     // If we evaluated the result, return it now.
1918     if (Result != -1)
1919       return ConstantInt::get(Type::getInt1Ty(Context), Result);
1920
1921   } else {
1922     // Evaluate the relation between the two constants, per the predicate.
1923     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1924     switch (evaluateICmpRelation(Context, C1, C2, CmpInst::isSigned(pred))) {
1925     default: llvm_unreachable("Unknown relational!");
1926     case ICmpInst::BAD_ICMP_PREDICATE:
1927       break;  // Couldn't determine anything about these constants.
1928     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1929       // If we know the constants are equal, we can decide the result of this
1930       // computation precisely.
1931       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1932       break;
1933     case ICmpInst::ICMP_ULT:
1934       switch (pred) {
1935       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1936         Result = 1; break;
1937       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1938         Result = 0; break;
1939       }
1940       break;
1941     case ICmpInst::ICMP_SLT:
1942       switch (pred) {
1943       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1944         Result = 1; break;
1945       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1946         Result = 0; break;
1947       }
1948       break;
1949     case ICmpInst::ICMP_UGT:
1950       switch (pred) {
1951       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1952         Result = 1; break;
1953       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1954         Result = 0; break;
1955       }
1956       break;
1957     case ICmpInst::ICMP_SGT:
1958       switch (pred) {
1959       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1960         Result = 1; break;
1961       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1962         Result = 0; break;
1963       }
1964       break;
1965     case ICmpInst::ICMP_ULE:
1966       if (pred == ICmpInst::ICMP_UGT) Result = 0;
1967       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1968       break;
1969     case ICmpInst::ICMP_SLE:
1970       if (pred == ICmpInst::ICMP_SGT) Result = 0;
1971       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1972       break;
1973     case ICmpInst::ICMP_UGE:
1974       if (pred == ICmpInst::ICMP_ULT) Result = 0;
1975       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1976       break;
1977     case ICmpInst::ICMP_SGE:
1978       if (pred == ICmpInst::ICMP_SLT) Result = 0;
1979       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1980       break;
1981     case ICmpInst::ICMP_NE:
1982       if (pred == ICmpInst::ICMP_EQ) Result = 0;
1983       if (pred == ICmpInst::ICMP_NE) Result = 1;
1984       break;
1985     }
1986
1987     // If we evaluated the result, return it now.
1988     if (Result != -1)
1989       return ConstantInt::get(Type::getInt1Ty(Context), Result);
1990
1991     // If the right hand side is a bitcast, try using its inverse to simplify
1992     // it by moving it to the left hand side.
1993     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1994       if (CE2->getOpcode() == Instruction::BitCast) {
1995         Constant *CE2Op0 = CE2->getOperand(0);
1996         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1997         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1998       }
1999     }
2000
2001     // If the left hand side is an extension, try eliminating it.
2002     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
2003       if (CE1->getOpcode() == Instruction::SExt ||
2004           CE1->getOpcode() == Instruction::ZExt) {
2005         Constant *CE1Op0 = CE1->getOperand(0);
2006         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2007         if (CE1Inverse == CE1Op0) {
2008           // Check whether we can safely truncate the right hand side.
2009           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2010           if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
2011             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2012           }
2013         }
2014       }
2015     }
2016
2017     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2018         (C1->isNullValue() && !C2->isNullValue())) {
2019       // If C2 is a constant expr and C1 isn't, flip them around and fold the
2020       // other way if possible.
2021       // Also, if C1 is null and C2 isn't, flip them around.
2022       switch (pred) {
2023       case ICmpInst::ICMP_EQ:
2024       case ICmpInst::ICMP_NE:
2025         // No change of predicate required.
2026         return ConstantExpr::getICmp(pred, C2, C1);
2027
2028       case ICmpInst::ICMP_ULT:
2029       case ICmpInst::ICMP_SLT:
2030       case ICmpInst::ICMP_UGT:
2031       case ICmpInst::ICMP_SGT:
2032       case ICmpInst::ICMP_ULE:
2033       case ICmpInst::ICMP_SLE:
2034       case ICmpInst::ICMP_UGE:
2035       case ICmpInst::ICMP_SGE:
2036         // Change the predicate as necessary to swap the operands.
2037         pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
2038         return ConstantExpr::getICmp(pred, C2, C1);
2039
2040       default:  // These predicates cannot be flopped around.
2041         break;
2042       }
2043     }
2044   }
2045   return 0;
2046 }
2047
2048 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
2049 /// is "inbounds".
2050 static bool isInBoundsIndices(Constant *const *Idxs, size_t NumIdx) {
2051   // No indices means nothing that could be out of bounds.
2052   if (NumIdx == 0) return true;
2053
2054   // If the first index is zero, it's in bounds.
2055   if (Idxs[0]->isNullValue()) return true;
2056
2057   // If the first index is one and all the rest are zero, it's in bounds,
2058   // by the one-past-the-end rule.
2059   if (!cast<ConstantInt>(Idxs[0])->isOne())
2060     return false;
2061   for (unsigned i = 1, e = NumIdx; i != e; ++i)
2062     if (!Idxs[i]->isNullValue())
2063       return false;
2064   return true;
2065 }
2066
2067 Constant *llvm::ConstantFoldGetElementPtr(LLVMContext &Context, 
2068                                           Constant *C,
2069                                           bool inBounds,
2070                                           Constant* const *Idxs,
2071                                           unsigned NumIdx) {
2072   if (NumIdx == 0 ||
2073       (NumIdx == 1 && Idxs[0]->isNullValue()))
2074     return C;
2075
2076   if (isa<UndefValue>(C)) {
2077     const PointerType *Ptr = cast<PointerType>(C->getType());
2078     const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
2079                                                        (Value **)Idxs,
2080                                                        (Value **)Idxs+NumIdx);
2081     assert(Ty != 0 && "Invalid indices for GEP!");
2082     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
2083   }
2084
2085   Constant *Idx0 = Idxs[0];
2086   if (C->isNullValue()) {
2087     bool isNull = true;
2088     for (unsigned i = 0, e = NumIdx; i != e; ++i)
2089       if (!Idxs[i]->isNullValue()) {
2090         isNull = false;
2091         break;
2092       }
2093     if (isNull) {
2094       const PointerType *Ptr = cast<PointerType>(C->getType());
2095       const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
2096                                                          (Value**)Idxs,
2097                                                          (Value**)Idxs+NumIdx);
2098       assert(Ty != 0 && "Invalid indices for GEP!");
2099       return  ConstantPointerNull::get(
2100                             PointerType::get(Ty,Ptr->getAddressSpace()));
2101     }
2102   }
2103
2104   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2105     // Combine Indices - If the source pointer to this getelementptr instruction
2106     // is a getelementptr instruction, combine the indices of the two
2107     // getelementptr instructions into a single instruction.
2108     //
2109     if (CE->getOpcode() == Instruction::GetElementPtr) {
2110       const Type *LastTy = 0;
2111       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2112            I != E; ++I)
2113         LastTy = *I;
2114
2115       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
2116         SmallVector<Value*, 16> NewIndices;
2117         NewIndices.reserve(NumIdx + CE->getNumOperands());
2118         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2119           NewIndices.push_back(CE->getOperand(i));
2120
2121         // Add the last index of the source with the first index of the new GEP.
2122         // Make sure to handle the case when they are actually different types.
2123         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2124         // Otherwise it must be an array.
2125         if (!Idx0->isNullValue()) {
2126           const Type *IdxTy = Combined->getType();
2127           if (IdxTy != Idx0->getType()) {
2128             Constant *C1 =
2129               ConstantExpr::getSExtOrBitCast(Idx0, Type::getInt64Ty(Context));
2130             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, 
2131                                                           Type::getInt64Ty(Context));
2132             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2133           } else {
2134             Combined =
2135               ConstantExpr::get(Instruction::Add, Idx0, Combined);
2136           }
2137         }
2138
2139         NewIndices.push_back(Combined);
2140         NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
2141         return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
2142           ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
2143                                                  &NewIndices[0],
2144                                                  NewIndices.size()) :
2145           ConstantExpr::getGetElementPtr(CE->getOperand(0),
2146                                          &NewIndices[0],
2147                                          NewIndices.size());
2148       }
2149     }
2150
2151     // Implement folding of:
2152     //    int* getelementptr ([2 x int]* bitcast ([3 x int]* %X to [2 x int]*),
2153     //                        long 0, long 0)
2154     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
2155     //
2156     if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
2157       if (const PointerType *SPT =
2158           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
2159         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
2160           if (const ArrayType *CAT =
2161         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
2162             if (CAT->getElementType() == SAT->getElementType())
2163               return inBounds ?
2164                 ConstantExpr::getInBoundsGetElementPtr(
2165                       (Constant*)CE->getOperand(0), Idxs, NumIdx) :
2166                 ConstantExpr::getGetElementPtr(
2167                       (Constant*)CE->getOperand(0), Idxs, NumIdx);
2168     }
2169   }
2170
2171   // Check to see if any array indices are not within the corresponding
2172   // notional array bounds. If so, try to determine if they can be factored
2173   // out into preceding dimensions.
2174   bool Unknown = false;
2175   SmallVector<Constant *, 8> NewIdxs;
2176   const Type *Ty = C->getType();
2177   const Type *Prev = 0;
2178   for (unsigned i = 0; i != NumIdx;
2179        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2180     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2181       if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2182         if (ATy->getNumElements() <= INT64_MAX &&
2183             ATy->getNumElements() != 0 &&
2184             CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2185           if (isa<SequentialType>(Prev)) {
2186             // It's out of range, but we can factor it into the prior
2187             // dimension.
2188             NewIdxs.resize(NumIdx);
2189             ConstantInt *Factor = ConstantInt::get(CI->getType(),
2190                                                    ATy->getNumElements());
2191             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2192
2193             Constant *PrevIdx = Idxs[i-1];
2194             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2195
2196             // Before adding, extend both operands to i64 to avoid
2197             // overflow trouble.
2198             if (!PrevIdx->getType()->isInteger(64))
2199               PrevIdx = ConstantExpr::getSExt(PrevIdx,
2200                                               Type::getInt64Ty(Context));
2201             if (!Div->getType()->isInteger(64))
2202               Div = ConstantExpr::getSExt(Div,
2203                                           Type::getInt64Ty(Context));
2204
2205             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2206           } else {
2207             // It's out of range, but the prior dimension is a struct
2208             // so we can't do anything about it.
2209             Unknown = true;
2210           }
2211         }
2212     } else {
2213       // We don't know if it's in range or not.
2214       Unknown = true;
2215     }
2216   }
2217
2218   // If we did any factoring, start over with the adjusted indices.
2219   if (!NewIdxs.empty()) {
2220     for (unsigned i = 0; i != NumIdx; ++i)
2221       if (!NewIdxs[i]) NewIdxs[i] = Idxs[i];
2222     return inBounds ?
2223       ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
2224                                              NewIdxs.size()) :
2225       ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
2226   }
2227
2228   // If all indices are known integers and normalized, we can do a simple
2229   // check for the "inbounds" property.
2230   if (!Unknown && !inBounds &&
2231       isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
2232     return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);
2233
2234   return 0;
2235 }