Fold 'icmp eq (icmp), true' into an xor(icmp).
[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 Constant *llvm::ConstantFoldCastInstruction(LLVMContext &Context, 
183                                             unsigned opc, Constant *V,
184                                             const Type *DestTy) {
185   if (isa<UndefValue>(V)) {
186     // zext(undef) = 0, because the top bits will be zero.
187     // sext(undef) = 0, because the top bits will all be the same.
188     // [us]itofp(undef) = 0, because the result value is bounded.
189     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
190         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
191       return Constant::getNullValue(DestTy);
192     return UndefValue::get(DestTy);
193   }
194   // No compile-time operations on this type yet.
195   if (V->getType() == Type::getPPC_FP128Ty(Context) || DestTy == Type::getPPC_FP128Ty(Context))
196     return 0;
197
198   // If the cast operand is a constant expression, there's a few things we can
199   // do to try to simplify it.
200   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
201     if (CE->isCast()) {
202       // Try hard to fold cast of cast because they are often eliminable.
203       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
204         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
205     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
206       // If all of the indexes in the GEP are null values, there is no pointer
207       // adjustment going on.  We might as well cast the source pointer.
208       bool isAllNull = true;
209       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
210         if (!CE->getOperand(i)->isNullValue()) {
211           isAllNull = false;
212           break;
213         }
214       if (isAllNull)
215         // This is casting one pointer type to another, always BitCast
216         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
217     }
218   }
219
220   // If the cast operand is a constant vector, perform the cast by
221   // operating on each element. In the cast of bitcasts, the element
222   // count may be mismatched; don't attempt to handle that here.
223   if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
224     if (isa<VectorType>(DestTy) &&
225         cast<VectorType>(DestTy)->getNumElements() ==
226         CV->getType()->getNumElements()) {
227       std::vector<Constant*> res;
228       const VectorType *DestVecTy = cast<VectorType>(DestTy);
229       const Type *DstEltTy = DestVecTy->getElementType();
230       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
231         res.push_back(ConstantExpr::getCast(opc,
232                                             CV->getOperand(i), DstEltTy));
233       return ConstantVector::get(DestVecTy, res);
234     }
235
236   // We actually have to do a cast now. Perform the cast according to the
237   // opcode specified.
238   switch (opc) {
239   case Instruction::FPTrunc:
240   case Instruction::FPExt:
241     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
242       bool ignored;
243       APFloat Val = FPC->getValueAPF();
244       Val.convert(DestTy == Type::getFloatTy(Context) ? APFloat::IEEEsingle :
245                   DestTy == Type::getDoubleTy(Context) ? APFloat::IEEEdouble :
246                   DestTy == Type::getX86_FP80Ty(Context) ? APFloat::x87DoubleExtended :
247                   DestTy == Type::getFP128Ty(Context) ? APFloat::IEEEquad :
248                   APFloat::Bogus,
249                   APFloat::rmNearestTiesToEven, &ignored);
250       return ConstantFP::get(Context, Val);
251     }
252     return 0; // Can't fold.
253   case Instruction::FPToUI: 
254   case Instruction::FPToSI:
255     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
256       const APFloat &V = FPC->getValueAPF();
257       bool ignored;
258       uint64_t x[2]; 
259       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
260       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
261                                 APFloat::rmTowardZero, &ignored);
262       APInt Val(DestBitWidth, 2, x);
263       return ConstantInt::get(Context, Val);
264     }
265     return 0; // Can't fold.
266   case Instruction::IntToPtr:   //always treated as unsigned
267     if (V->isNullValue())       // Is it an integral null value?
268       return ConstantPointerNull::get(cast<PointerType>(DestTy));
269     return 0;                   // Other pointer types cannot be casted
270   case Instruction::PtrToInt:   // always treated as unsigned
271     if (V->isNullValue())       // is it a null pointer value?
272       return ConstantInt::get(DestTy, 0);
273     return 0;                   // Other pointer types cannot be casted
274   case Instruction::UIToFP:
275   case Instruction::SIToFP:
276     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
277       APInt api = CI->getValue();
278       const uint64_t zero[] = {0, 0};
279       APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
280                                   2, zero));
281       (void)apf.convertFromAPInt(api, 
282                                  opc==Instruction::SIToFP,
283                                  APFloat::rmNearestTiesToEven);
284       return ConstantFP::get(Context, apf);
285     }
286     return 0;
287   case Instruction::ZExt:
288     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
289       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
290       APInt Result(CI->getValue());
291       Result.zext(BitWidth);
292       return ConstantInt::get(Context, Result);
293     }
294     return 0;
295   case Instruction::SExt:
296     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
297       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
298       APInt Result(CI->getValue());
299       Result.sext(BitWidth);
300       return ConstantInt::get(Context, Result);
301     }
302     return 0;
303   case Instruction::Trunc:
304     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
305       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
306       APInt Result(CI->getValue());
307       Result.trunc(BitWidth);
308       return ConstantInt::get(Context, Result);
309     }
310     return 0;
311   case Instruction::BitCast:
312     return FoldBitCast(Context, V, DestTy);
313   default:
314     assert(!"Invalid CE CastInst opcode");
315     break;
316   }
317
318   llvm_unreachable("Failed to cast constant expression");
319   return 0;
320 }
321
322 Constant *llvm::ConstantFoldSelectInstruction(LLVMContext&,
323                                               Constant *Cond,
324                                               Constant *V1, Constant *V2) {
325   if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
326     return CB->getZExtValue() ? V1 : V2;
327
328   if (isa<UndefValue>(V1)) return V2;
329   if (isa<UndefValue>(V2)) return V1;
330   if (isa<UndefValue>(Cond)) return V1;
331   if (V1 == V2) return V1;
332   return 0;
333 }
334
335 Constant *llvm::ConstantFoldExtractElementInstruction(LLVMContext &Context,
336                                                       Constant *Val,
337                                                       Constant *Idx) {
338   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
339     return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
340   if (Val->isNullValue())  // ee(zero, x) -> zero
341     return Constant::getNullValue(
342                           cast<VectorType>(Val->getType())->getElementType());
343
344   if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
345     if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
346       return CVal->getOperand(CIdx->getZExtValue());
347     } else if (isa<UndefValue>(Idx)) {
348       // ee({w,x,y,z}, undef) -> w (an arbitrary value).
349       return CVal->getOperand(0);
350     }
351   }
352   return 0;
353 }
354
355 Constant *llvm::ConstantFoldInsertElementInstruction(LLVMContext &Context,
356                                                      Constant *Val,
357                                                      Constant *Elt,
358                                                      Constant *Idx) {
359   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
360   if (!CIdx) return 0;
361   APInt idxVal = CIdx->getValue();
362   if (isa<UndefValue>(Val)) { 
363     // Insertion of scalar constant into vector undef
364     // Optimize away insertion of undef
365     if (isa<UndefValue>(Elt))
366       return Val;
367     // Otherwise break the aggregate undef into multiple undefs and do
368     // the insertion
369     unsigned numOps = 
370       cast<VectorType>(Val->getType())->getNumElements();
371     std::vector<Constant*> Ops; 
372     Ops.reserve(numOps);
373     for (unsigned i = 0; i < numOps; ++i) {
374       Constant *Op =
375         (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
376       Ops.push_back(Op);
377     }
378     return ConstantVector::get(Ops);
379   }
380   if (isa<ConstantAggregateZero>(Val)) {
381     // Insertion of scalar constant into vector aggregate zero
382     // Optimize away insertion of zero
383     if (Elt->isNullValue())
384       return Val;
385     // Otherwise break the aggregate zero into multiple zeros and do
386     // the insertion
387     unsigned numOps = 
388       cast<VectorType>(Val->getType())->getNumElements();
389     std::vector<Constant*> Ops; 
390     Ops.reserve(numOps);
391     for (unsigned i = 0; i < numOps; ++i) {
392       Constant *Op =
393         (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
394       Ops.push_back(Op);
395     }
396     return ConstantVector::get(Ops);
397   }
398   if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
399     // Insertion of scalar constant into vector constant
400     std::vector<Constant*> Ops; 
401     Ops.reserve(CVal->getNumOperands());
402     for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
403       Constant *Op =
404         (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
405       Ops.push_back(Op);
406     }
407     return ConstantVector::get(Ops);
408   }
409
410   return 0;
411 }
412
413 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
414 /// return the specified element value.  Otherwise return null.
415 static Constant *GetVectorElement(LLVMContext &Context, Constant *C,
416                                   unsigned EltNo) {
417   if (ConstantVector *CV = dyn_cast<ConstantVector>(C))
418     return CV->getOperand(EltNo);
419
420   const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
421   if (isa<ConstantAggregateZero>(C))
422     return Constant::getNullValue(EltTy);
423   if (isa<UndefValue>(C))
424     return UndefValue::get(EltTy);
425   return 0;
426 }
427
428 Constant *llvm::ConstantFoldShuffleVectorInstruction(LLVMContext &Context,
429                                                      Constant *V1,
430                                                      Constant *V2,
431                                                      Constant *Mask) {
432   // Undefined shuffle mask -> undefined value.
433   if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
434
435   unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
436   unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
437   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
438
439   // Loop over the shuffle mask, evaluating each element.
440   SmallVector<Constant*, 32> Result;
441   for (unsigned i = 0; i != MaskNumElts; ++i) {
442     Constant *InElt = GetVectorElement(Context, Mask, i);
443     if (InElt == 0) return 0;
444
445     if (isa<UndefValue>(InElt))
446       InElt = UndefValue::get(EltTy);
447     else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
448       unsigned Elt = CI->getZExtValue();
449       if (Elt >= SrcNumElts*2)
450         InElt = UndefValue::get(EltTy);
451       else if (Elt >= SrcNumElts)
452         InElt = GetVectorElement(Context, V2, Elt - SrcNumElts);
453       else
454         InElt = GetVectorElement(Context, V1, Elt);
455       if (InElt == 0) return 0;
456     } else {
457       // Unknown value.
458       return 0;
459     }
460     Result.push_back(InElt);
461   }
462
463   return ConstantVector::get(&Result[0], Result.size());
464 }
465
466 Constant *llvm::ConstantFoldExtractValueInstruction(LLVMContext &Context,
467                                                     Constant *Agg,
468                                                     const unsigned *Idxs,
469                                                     unsigned NumIdx) {
470   // Base case: no indices, so return the entire value.
471   if (NumIdx == 0)
472     return Agg;
473
474   if (isa<UndefValue>(Agg))  // ev(undef, x) -> undef
475     return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
476                                                             Idxs,
477                                                             Idxs + NumIdx));
478
479   if (isa<ConstantAggregateZero>(Agg))  // ev(0, x) -> 0
480     return
481       Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
482                                                               Idxs,
483                                                               Idxs + NumIdx));
484
485   // Otherwise recurse.
486   return ConstantFoldExtractValueInstruction(Context, Agg->getOperand(*Idxs),
487                                              Idxs+1, NumIdx-1);
488 }
489
490 Constant *llvm::ConstantFoldInsertValueInstruction(LLVMContext &Context,
491                                                    Constant *Agg,
492                                                    Constant *Val,
493                                                    const unsigned *Idxs,
494                                                    unsigned NumIdx) {
495   // Base case: no indices, so replace the entire value.
496   if (NumIdx == 0)
497     return Val;
498
499   if (isa<UndefValue>(Agg)) {
500     // Insertion of constant into aggregate undef
501     // Optimize away insertion of undef.
502     if (isa<UndefValue>(Val))
503       return Agg;
504     
505     // Otherwise break the aggregate undef into multiple undefs and do
506     // the insertion.
507     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
508     unsigned numOps;
509     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
510       numOps = AR->getNumElements();
511     else
512       numOps = cast<StructType>(AggTy)->getNumElements();
513     
514     std::vector<Constant*> Ops(numOps); 
515     for (unsigned i = 0; i < numOps; ++i) {
516       const Type *MemberTy = AggTy->getTypeAtIndex(i);
517       Constant *Op =
518         (*Idxs == i) ?
519         ConstantFoldInsertValueInstruction(Context, UndefValue::get(MemberTy),
520                                            Val, Idxs+1, NumIdx-1) :
521         UndefValue::get(MemberTy);
522       Ops[i] = Op;
523     }
524     
525     if (const StructType* ST = dyn_cast<StructType>(AggTy))
526       return ConstantStruct::get(Context, Ops, ST->isPacked());
527     return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
528   }
529   
530   if (isa<ConstantAggregateZero>(Agg)) {
531     // Insertion of constant into aggregate zero
532     // Optimize away insertion of zero.
533     if (Val->isNullValue())
534       return Agg;
535     
536     // Otherwise break the aggregate zero into multiple zeros and do
537     // the insertion.
538     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
539     unsigned numOps;
540     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
541       numOps = AR->getNumElements();
542     else
543       numOps = cast<StructType>(AggTy)->getNumElements();
544     
545     std::vector<Constant*> Ops(numOps);
546     for (unsigned i = 0; i < numOps; ++i) {
547       const Type *MemberTy = AggTy->getTypeAtIndex(i);
548       Constant *Op =
549         (*Idxs == i) ?
550         ConstantFoldInsertValueInstruction(Context, 
551                                            Constant::getNullValue(MemberTy),
552                                            Val, Idxs+1, NumIdx-1) :
553         Constant::getNullValue(MemberTy);
554       Ops[i] = Op;
555     }
556     
557     if (const StructType* ST = dyn_cast<StructType>(AggTy))
558       return ConstantStruct::get(Context, Ops, ST->isPacked());
559     return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
560   }
561   
562   if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
563     // Insertion of constant into aggregate constant.
564     std::vector<Constant*> Ops(Agg->getNumOperands());
565     for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
566       Constant *Op =
567         (*Idxs == i) ?
568         ConstantFoldInsertValueInstruction(Context, Agg->getOperand(i),
569                                            Val, Idxs+1, NumIdx-1) :
570         Agg->getOperand(i);
571       Ops[i] = Op;
572     }
573     
574     if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
575       return ConstantStruct::get(Context, Ops, ST->isPacked());
576     return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
577   }
578
579   return 0;
580 }
581
582
583 Constant *llvm::ConstantFoldBinaryInstruction(LLVMContext &Context,
584                                               unsigned Opcode,
585                                               Constant *C1, Constant *C2) {
586   // No compile-time operations on this type yet.
587   if (C1->getType() == Type::getPPC_FP128Ty(Context))
588     return 0;
589
590   // Handle UndefValue up front.
591   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
592     switch (Opcode) {
593     case Instruction::Xor:
594       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
595         // Handle undef ^ undef -> 0 special case. This is a common
596         // idiom (misuse).
597         return Constant::getNullValue(C1->getType());
598       // Fallthrough
599     case Instruction::Add:
600     case Instruction::Sub:
601       return UndefValue::get(C1->getType());
602     case Instruction::Mul:
603     case Instruction::And:
604       return Constant::getNullValue(C1->getType());
605     case Instruction::UDiv:
606     case Instruction::SDiv:
607     case Instruction::URem:
608     case Instruction::SRem:
609       if (!isa<UndefValue>(C2))                    // undef / X -> 0
610         return Constant::getNullValue(C1->getType());
611       return C2;                                   // X / undef -> undef
612     case Instruction::Or:                          // X | undef -> -1
613       if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
614         return Constant::getAllOnesValue(PTy);
615       return Constant::getAllOnesValue(C1->getType());
616     case Instruction::LShr:
617       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
618         return C1;                                  // undef lshr undef -> undef
619       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
620                                                     // undef lshr X -> 0
621     case Instruction::AShr:
622       if (!isa<UndefValue>(C2))
623         return C1;                                  // undef ashr X --> undef
624       else if (isa<UndefValue>(C1)) 
625         return C1;                                  // undef ashr undef -> undef
626       else
627         return C1;                                  // X ashr undef --> X
628     case Instruction::Shl:
629       // undef << X -> 0   or   X << undef -> 0
630       return Constant::getNullValue(C1->getType());
631     }
632   }
633
634   // Handle simplifications when the RHS is a constant int.
635   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
636     switch (Opcode) {
637     case Instruction::Add:
638       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
639       break;
640     case Instruction::Sub:
641       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
642       break;
643     case Instruction::Mul:
644       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
645       if (CI2->equalsInt(1))
646         return C1;                                              // X * 1 == X
647       break;
648     case Instruction::UDiv:
649     case Instruction::SDiv:
650       if (CI2->equalsInt(1))
651         return C1;                                            // X / 1 == X
652       if (CI2->equalsInt(0))
653         return UndefValue::get(CI2->getType());               // X / 0 == undef
654       break;
655     case Instruction::URem:
656     case Instruction::SRem:
657       if (CI2->equalsInt(1))
658         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
659       if (CI2->equalsInt(0))
660         return UndefValue::get(CI2->getType());               // X % 0 == undef
661       break;
662     case Instruction::And:
663       if (CI2->isZero()) return C2;                           // X & 0 == 0
664       if (CI2->isAllOnesValue())
665         return C1;                                            // X & -1 == X
666
667       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
668         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
669         if (CE1->getOpcode() == Instruction::ZExt) {
670           unsigned DstWidth = CI2->getType()->getBitWidth();
671           unsigned SrcWidth =
672             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
673           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
674           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
675             return C1;
676         }
677
678         // If and'ing the address of a global with a constant, fold it.
679         if (CE1->getOpcode() == Instruction::PtrToInt && 
680             isa<GlobalValue>(CE1->getOperand(0))) {
681           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
682
683           // Functions are at least 4-byte aligned.
684           unsigned GVAlign = GV->getAlignment();
685           if (isa<Function>(GV))
686             GVAlign = std::max(GVAlign, 4U);
687
688           if (GVAlign > 1) {
689             unsigned DstWidth = CI2->getType()->getBitWidth();
690             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
691             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
692
693             // If checking bits we know are clear, return zero.
694             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
695               return Constant::getNullValue(CI2->getType());
696           }
697         }
698       }
699       break;
700     case Instruction::Or:
701       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
702       if (CI2->isAllOnesValue())
703         return C2;                         // X | -1 == -1
704       break;
705     case Instruction::Xor:
706       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
707
708       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
709         switch (CE1->getOpcode()) {
710         default: break;
711         case Instruction::ICmp:
712         case Instruction::FCmp:
713           // cmp pred ^ true -> cmp !pred
714           assert(CI2->equalsInt(1));
715           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
716           pred = CmpInst::getInversePredicate(pred);
717           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
718                                           CE1->getOperand(1));
719         }
720       }
721       break;
722     case Instruction::AShr:
723       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
724       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
725         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
726           return ConstantExpr::getLShr(C1, C2);
727       break;
728     }
729   }
730
731   // At this point we know neither constant is an UndefValue.
732   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
733     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
734       using namespace APIntOps;
735       const APInt &C1V = CI1->getValue();
736       const APInt &C2V = CI2->getValue();
737       switch (Opcode) {
738       default:
739         break;
740       case Instruction::Add:     
741         return ConstantInt::get(Context, C1V + C2V);
742       case Instruction::Sub:     
743         return ConstantInt::get(Context, C1V - C2V);
744       case Instruction::Mul:     
745         return ConstantInt::get(Context, C1V * C2V);
746       case Instruction::UDiv:
747         assert(!CI2->isNullValue() && "Div by zero handled above");
748         return ConstantInt::get(Context, C1V.udiv(C2V));
749       case Instruction::SDiv:
750         assert(!CI2->isNullValue() && "Div by zero handled above");
751         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
752           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
753         return ConstantInt::get(Context, C1V.sdiv(C2V));
754       case Instruction::URem:
755         assert(!CI2->isNullValue() && "Div by zero handled above");
756         return ConstantInt::get(Context, C1V.urem(C2V));
757       case Instruction::SRem:
758         assert(!CI2->isNullValue() && "Div by zero handled above");
759         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
760           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
761         return ConstantInt::get(Context, C1V.srem(C2V));
762       case Instruction::And:
763         return ConstantInt::get(Context, C1V & C2V);
764       case Instruction::Or:
765         return ConstantInt::get(Context, C1V | C2V);
766       case Instruction::Xor:
767         return ConstantInt::get(Context, C1V ^ C2V);
768       case Instruction::Shl: {
769         uint32_t shiftAmt = C2V.getZExtValue();
770         if (shiftAmt < C1V.getBitWidth())
771           return ConstantInt::get(Context, C1V.shl(shiftAmt));
772         else
773           return UndefValue::get(C1->getType()); // too big shift is undef
774       }
775       case Instruction::LShr: {
776         uint32_t shiftAmt = C2V.getZExtValue();
777         if (shiftAmt < C1V.getBitWidth())
778           return ConstantInt::get(Context, C1V.lshr(shiftAmt));
779         else
780           return UndefValue::get(C1->getType()); // too big shift is undef
781       }
782       case Instruction::AShr: {
783         uint32_t shiftAmt = C2V.getZExtValue();
784         if (shiftAmt < C1V.getBitWidth())
785           return ConstantInt::get(Context, C1V.ashr(shiftAmt));
786         else
787           return UndefValue::get(C1->getType()); // too big shift is undef
788       }
789       }
790     }
791
792     switch (Opcode) {
793     case Instruction::SDiv:
794     case Instruction::UDiv:
795     case Instruction::URem:
796     case Instruction::SRem:
797     case Instruction::LShr:
798     case Instruction::AShr:
799     case Instruction::Shl:
800       if (CI1->equalsInt(0)) return C1;
801       break;
802     default:
803       break;
804     }
805   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
806     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
807       APFloat C1V = CFP1->getValueAPF();
808       APFloat C2V = CFP2->getValueAPF();
809       APFloat C3V = C1V;  // copy for modification
810       switch (Opcode) {
811       default:                   
812         break;
813       case Instruction::FAdd:
814         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
815         return ConstantFP::get(Context, C3V);
816       case Instruction::FSub:
817         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
818         return ConstantFP::get(Context, C3V);
819       case Instruction::FMul:
820         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
821         return ConstantFP::get(Context, C3V);
822       case Instruction::FDiv:
823         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
824         return ConstantFP::get(Context, C3V);
825       case Instruction::FRem:
826         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
827         return ConstantFP::get(Context, C3V);
828       }
829     }
830   } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
831     ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
832     ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
833     if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
834         (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
835       std::vector<Constant*> Res;
836       const Type* EltTy = VTy->getElementType();  
837       Constant *C1 = 0;
838       Constant *C2 = 0;
839       switch (Opcode) {
840       default:
841         break;
842       case Instruction::Add:
843         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
844           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
845           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
846           Res.push_back(ConstantExpr::getAdd(C1, C2));
847         }
848         return ConstantVector::get(Res);
849       case Instruction::FAdd:
850         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
851           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
852           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
853           Res.push_back(ConstantExpr::getFAdd(C1, C2));
854         }
855         return ConstantVector::get(Res);
856       case Instruction::Sub:
857         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
858           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
859           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
860           Res.push_back(ConstantExpr::getSub(C1, C2));
861         }
862         return ConstantVector::get(Res);
863       case Instruction::FSub:
864         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
865           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
866           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
867           Res.push_back(ConstantExpr::getFSub(C1, C2));
868         }
869         return ConstantVector::get(Res);
870       case Instruction::Mul:
871         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
872           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
873           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
874           Res.push_back(ConstantExpr::getMul(C1, C2));
875         }
876         return ConstantVector::get(Res);
877       case Instruction::FMul:
878         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
879           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
880           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
881           Res.push_back(ConstantExpr::getFMul(C1, C2));
882         }
883         return ConstantVector::get(Res);
884       case Instruction::UDiv:
885         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
886           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
887           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
888           Res.push_back(ConstantExpr::getUDiv(C1, C2));
889         }
890         return ConstantVector::get(Res);
891       case Instruction::SDiv:
892         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
893           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
894           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
895           Res.push_back(ConstantExpr::getSDiv(C1, C2));
896         }
897         return ConstantVector::get(Res);
898       case Instruction::FDiv:
899         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
900           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
901           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
902           Res.push_back(ConstantExpr::getFDiv(C1, C2));
903         }
904         return ConstantVector::get(Res);
905       case Instruction::URem:
906         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
907           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
908           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
909           Res.push_back(ConstantExpr::getURem(C1, C2));
910         }
911         return ConstantVector::get(Res);
912       case Instruction::SRem:
913         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
914           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
915           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
916           Res.push_back(ConstantExpr::getSRem(C1, C2));
917         }
918         return ConstantVector::get(Res);
919       case Instruction::FRem:
920         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
921           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
922           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
923           Res.push_back(ConstantExpr::getFRem(C1, C2));
924         }
925         return ConstantVector::get(Res);
926       case Instruction::And: 
927         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
928           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
929           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
930           Res.push_back(ConstantExpr::getAnd(C1, C2));
931         }
932         return ConstantVector::get(Res);
933       case Instruction::Or:
934         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
935           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
936           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
937           Res.push_back(ConstantExpr::getOr(C1, C2));
938         }
939         return ConstantVector::get(Res);
940       case Instruction::Xor:
941         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
942           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
943           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
944           Res.push_back(ConstantExpr::getXor(C1, C2));
945         }
946         return ConstantVector::get(Res);
947       case Instruction::LShr:
948         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
949           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
950           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
951           Res.push_back(ConstantExpr::getLShr(C1, C2));
952         }
953         return ConstantVector::get(Res);
954       case Instruction::AShr:
955         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
956           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
957           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
958           Res.push_back(ConstantExpr::getAShr(C1, C2));
959         }
960         return ConstantVector::get(Res);
961       case Instruction::Shl:
962         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
963           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
964           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
965           Res.push_back(ConstantExpr::getShl(C1, C2));
966         }
967         return ConstantVector::get(Res);
968       }
969     }
970   }
971
972   if (isa<ConstantExpr>(C1)) {
973     // There are many possible foldings we could do here.  We should probably
974     // at least fold add of a pointer with an integer into the appropriate
975     // getelementptr.  This will improve alias analysis a bit.
976   } else if (isa<ConstantExpr>(C2)) {
977     // If C2 is a constant expr and C1 isn't, flop them around and fold the
978     // other way if possible.
979     switch (Opcode) {
980     case Instruction::Add:
981     case Instruction::FAdd:
982     case Instruction::Mul:
983     case Instruction::FMul:
984     case Instruction::And:
985     case Instruction::Or:
986     case Instruction::Xor:
987       // No change of opcode required.
988       return ConstantFoldBinaryInstruction(Context, Opcode, C2, C1);
989
990     case Instruction::Shl:
991     case Instruction::LShr:
992     case Instruction::AShr:
993     case Instruction::Sub:
994     case Instruction::FSub:
995     case Instruction::SDiv:
996     case Instruction::UDiv:
997     case Instruction::FDiv:
998     case Instruction::URem:
999     case Instruction::SRem:
1000     case Instruction::FRem:
1001     default:  // These instructions cannot be flopped around.
1002       break;
1003     }
1004   }
1005
1006   // i1 can be simplified in many cases.
1007   if (C1->getType() == Type::getInt1Ty(Context)) {
1008     switch (Opcode) {
1009     case Instruction::Add:
1010     case Instruction::Sub:
1011       return ConstantExpr::getXor(C1, C2);
1012     case Instruction::Mul:
1013       return ConstantExpr::getAnd(C1, C2);
1014     case Instruction::Shl:
1015     case Instruction::LShr:
1016     case Instruction::AShr:
1017       // We can assume that C2 == 0.  If it were one the result would be
1018       // undefined because the shift value is as large as the bitwidth.
1019       return C1;
1020     case Instruction::SDiv:
1021     case Instruction::UDiv:
1022       // We can assume that C2 == 1.  If it were zero the result would be
1023       // undefined through division by zero.
1024       return C1;
1025     case Instruction::URem:
1026     case Instruction::SRem:
1027       // We can assume that C2 == 1.  If it were zero the result would be
1028       // undefined through division by zero.
1029       return ConstantInt::getFalse(Context);
1030     default:
1031       break;
1032     }
1033   }
1034
1035   // We don't know how to fold this.
1036   return 0;
1037 }
1038
1039 /// isZeroSizedType - This type is zero sized if its an array or structure of
1040 /// zero sized types.  The only leaf zero sized type is an empty structure.
1041 static bool isMaybeZeroSizedType(const Type *Ty) {
1042   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
1043   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1044
1045     // If all of elements have zero size, this does too.
1046     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1047       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1048     return true;
1049
1050   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1051     return isMaybeZeroSizedType(ATy->getElementType());
1052   }
1053   return false;
1054 }
1055
1056 /// IdxCompare - Compare the two constants as though they were getelementptr
1057 /// indices.  This allows coersion of the types to be the same thing.
1058 ///
1059 /// If the two constants are the "same" (after coersion), return 0.  If the
1060 /// first is less than the second, return -1, if the second is less than the
1061 /// first, return 1.  If the constants are not integral, return -2.
1062 ///
1063 static int IdxCompare(LLVMContext &Context, Constant *C1, Constant *C2, 
1064                       const Type *ElTy) {
1065   if (C1 == C2) return 0;
1066
1067   // Ok, we found a different index.  If they are not ConstantInt, we can't do
1068   // anything with them.
1069   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1070     return -2; // don't know!
1071
1072   // Ok, we have two differing integer indices.  Sign extend them to be the same
1073   // type.  Long is always big enough, so we use it.
1074   if (C1->getType() != Type::getInt64Ty(Context))
1075     C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(Context));
1076
1077   if (C2->getType() != Type::getInt64Ty(Context))
1078     C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(Context));
1079
1080   if (C1 == C2) return 0;  // They are equal
1081
1082   // If the type being indexed over is really just a zero sized type, there is
1083   // no pointer difference being made here.
1084   if (isMaybeZeroSizedType(ElTy))
1085     return -2; // dunno.
1086
1087   // If they are really different, now that they are the same type, then we
1088   // found a difference!
1089   if (cast<ConstantInt>(C1)->getSExtValue() < 
1090       cast<ConstantInt>(C2)->getSExtValue())
1091     return -1;
1092   else
1093     return 1;
1094 }
1095
1096 /// evaluateFCmpRelation - This function determines if there is anything we can
1097 /// decide about the two constants provided.  This doesn't need to handle simple
1098 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1099 /// If we can determine that the two constants have a particular relation to 
1100 /// each other, we should return the corresponding FCmpInst predicate, 
1101 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1102 /// ConstantFoldCompareInstruction.
1103 ///
1104 /// To simplify this code we canonicalize the relation so that the first
1105 /// operand is always the most "complex" of the two.  We consider ConstantFP
1106 /// to be the simplest, and ConstantExprs to be the most complex.
1107 static FCmpInst::Predicate evaluateFCmpRelation(LLVMContext &Context,
1108                                                 Constant *V1, Constant *V2) {
1109   assert(V1->getType() == V2->getType() &&
1110          "Cannot compare values of different types!");
1111
1112   // No compile-time operations on this type yet.
1113   if (V1->getType() == Type::getPPC_FP128Ty(Context))
1114     return FCmpInst::BAD_FCMP_PREDICATE;
1115
1116   // Handle degenerate case quickly
1117   if (V1 == V2) return FCmpInst::FCMP_OEQ;
1118
1119   if (!isa<ConstantExpr>(V1)) {
1120     if (!isa<ConstantExpr>(V2)) {
1121       // We distilled thisUse the standard constant folder for a few cases
1122       ConstantInt *R = 0;
1123       R = dyn_cast<ConstantInt>(
1124                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1125       if (R && !R->isZero()) 
1126         return FCmpInst::FCMP_OEQ;
1127       R = dyn_cast<ConstantInt>(
1128                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1129       if (R && !R->isZero()) 
1130         return FCmpInst::FCMP_OLT;
1131       R = dyn_cast<ConstantInt>(
1132                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1133       if (R && !R->isZero()) 
1134         return FCmpInst::FCMP_OGT;
1135
1136       // Nothing more we can do
1137       return FCmpInst::BAD_FCMP_PREDICATE;
1138     }
1139
1140     // If the first operand is simple and second is ConstantExpr, swap operands.
1141     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(Context, V2, V1);
1142     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1143       return FCmpInst::getSwappedPredicate(SwappedRelation);
1144   } else {
1145     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1146     // constantexpr or a simple constant.
1147     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1148     switch (CE1->getOpcode()) {
1149     case Instruction::FPTrunc:
1150     case Instruction::FPExt:
1151     case Instruction::UIToFP:
1152     case Instruction::SIToFP:
1153       // We might be able to do something with these but we don't right now.
1154       break;
1155     default:
1156       break;
1157     }
1158   }
1159   // There are MANY other foldings that we could perform here.  They will
1160   // probably be added on demand, as they seem needed.
1161   return FCmpInst::BAD_FCMP_PREDICATE;
1162 }
1163
1164 /// evaluateICmpRelation - This function determines if there is anything we can
1165 /// decide about the two constants provided.  This doesn't need to handle simple
1166 /// things like integer comparisons, but should instead handle ConstantExprs
1167 /// and GlobalValues.  If we can determine that the two constants have a
1168 /// particular relation to each other, we should return the corresponding ICmp
1169 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1170 ///
1171 /// To simplify this code we canonicalize the relation so that the first
1172 /// operand is always the most "complex" of the two.  We consider simple
1173 /// constants (like ConstantInt) to be the simplest, followed by
1174 /// GlobalValues, followed by ConstantExpr's (the most complex).
1175 ///
1176 static ICmpInst::Predicate evaluateICmpRelation(LLVMContext &Context,
1177                                                 Constant *V1, 
1178                                                 Constant *V2,
1179                                                 bool isSigned) {
1180   assert(V1->getType() == V2->getType() &&
1181          "Cannot compare different types of values!");
1182   if (V1 == V2) return ICmpInst::ICMP_EQ;
1183
1184   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
1185     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1186       // We distilled this down to a simple case, use the standard constant
1187       // folder.
1188       ConstantInt *R = 0;
1189       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1190       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1191       if (R && !R->isZero()) 
1192         return pred;
1193       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1194       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1195       if (R && !R->isZero())
1196         return pred;
1197       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1198       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1199       if (R && !R->isZero())
1200         return pred;
1201
1202       // If we couldn't figure it out, bail.
1203       return ICmpInst::BAD_ICMP_PREDICATE;
1204     }
1205
1206     // If the first operand is simple, swap operands.
1207     ICmpInst::Predicate SwappedRelation = 
1208       evaluateICmpRelation(Context, V2, V1, isSigned);
1209     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1210       return ICmpInst::getSwappedPredicate(SwappedRelation);
1211
1212   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
1213     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1214       ICmpInst::Predicate SwappedRelation = 
1215         evaluateICmpRelation(Context, V2, V1, isSigned);
1216       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1217         return ICmpInst::getSwappedPredicate(SwappedRelation);
1218       else
1219         return ICmpInst::BAD_ICMP_PREDICATE;
1220     }
1221
1222     // Now we know that the RHS is a GlobalValue or simple constant,
1223     // which (since the types must match) means that it's a ConstantPointerNull.
1224     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1225       // Don't try to decide equality of aliases.
1226       if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
1227         if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
1228           return ICmpInst::ICMP_NE;
1229     } else {
1230       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1231       // GlobalVals can never be null.  Don't try to evaluate aliases.
1232       if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
1233         return ICmpInst::ICMP_NE;
1234     }
1235   } else {
1236     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1237     // constantexpr, a CPR, or a simple constant.
1238     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1239     Constant *CE1Op0 = CE1->getOperand(0);
1240
1241     switch (CE1->getOpcode()) {
1242     case Instruction::Trunc:
1243     case Instruction::FPTrunc:
1244     case Instruction::FPExt:
1245     case Instruction::FPToUI:
1246     case Instruction::FPToSI:
1247       break; // We can't evaluate floating point casts or truncations.
1248
1249     case Instruction::UIToFP:
1250     case Instruction::SIToFP:
1251     case Instruction::BitCast:
1252     case Instruction::ZExt:
1253     case Instruction::SExt:
1254       // If the cast is not actually changing bits, and the second operand is a
1255       // null pointer, do the comparison with the pre-casted value.
1256       if (V2->isNullValue() &&
1257           (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
1258         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1259         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1260         return evaluateICmpRelation(Context, CE1Op0,
1261                                     Constant::getNullValue(CE1Op0->getType()), 
1262                                     isSigned);
1263       }
1264       break;
1265
1266     case Instruction::GetElementPtr:
1267       // Ok, since this is a getelementptr, we know that the constant has a
1268       // pointer type.  Check the various cases.
1269       if (isa<ConstantPointerNull>(V2)) {
1270         // If we are comparing a GEP to a null pointer, check to see if the base
1271         // of the GEP equals the null pointer.
1272         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1273           if (GV->hasExternalWeakLinkage())
1274             // Weak linkage GVals could be zero or not. We're comparing that
1275             // to null pointer so its greater-or-equal
1276             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1277           else 
1278             // If its not weak linkage, the GVal must have a non-zero address
1279             // so the result is greater-than
1280             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1281         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1282           // If we are indexing from a null pointer, check to see if we have any
1283           // non-zero indices.
1284           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1285             if (!CE1->getOperand(i)->isNullValue())
1286               // Offsetting from null, must not be equal.
1287               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1288           // Only zero indexes from null, must still be zero.
1289           return ICmpInst::ICMP_EQ;
1290         }
1291         // Otherwise, we can't really say if the first operand is null or not.
1292       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1293         if (isa<ConstantPointerNull>(CE1Op0)) {
1294           if (CPR2->hasExternalWeakLinkage())
1295             // Weak linkage GVals could be zero or not. We're comparing it to
1296             // a null pointer, so its less-or-equal
1297             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1298           else
1299             // If its not weak linkage, the GVal must have a non-zero address
1300             // so the result is less-than
1301             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1302         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1303           if (CPR1 == CPR2) {
1304             // If this is a getelementptr of the same global, then it must be
1305             // different.  Because the types must match, the getelementptr could
1306             // only have at most one index, and because we fold getelementptr's
1307             // with a single zero index, it must be nonzero.
1308             assert(CE1->getNumOperands() == 2 &&
1309                    !CE1->getOperand(1)->isNullValue() &&
1310                    "Suprising getelementptr!");
1311             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1312           } else {
1313             // If they are different globals, we don't know what the value is,
1314             // but they can't be equal.
1315             return ICmpInst::ICMP_NE;
1316           }
1317         }
1318       } else {
1319         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1320         Constant *CE2Op0 = CE2->getOperand(0);
1321
1322         // There are MANY other foldings that we could perform here.  They will
1323         // probably be added on demand, as they seem needed.
1324         switch (CE2->getOpcode()) {
1325         default: break;
1326         case Instruction::GetElementPtr:
1327           // By far the most common case to handle is when the base pointers are
1328           // obviously to the same or different globals.
1329           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1330             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1331               return ICmpInst::ICMP_NE;
1332             // Ok, we know that both getelementptr instructions are based on the
1333             // same global.  From this, we can precisely determine the relative
1334             // ordering of the resultant pointers.
1335             unsigned i = 1;
1336
1337             // The logic below assumes that the result of the comparison
1338             // can be determined by finding the first index that differs.
1339             // This doesn't work if there is over-indexing in any
1340             // subsequent indices, so check for that case first.
1341             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1342                 !CE2->isGEPWithNoNotionalOverIndexing())
1343                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1344
1345             // Compare all of the operands the GEP's have in common.
1346             gep_type_iterator GTI = gep_type_begin(CE1);
1347             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1348                  ++i, ++GTI)
1349               switch (IdxCompare(Context, CE1->getOperand(i),
1350                                  CE2->getOperand(i), GTI.getIndexedType())) {
1351               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1352               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1353               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1354               }
1355
1356             // Ok, we ran out of things they have in common.  If any leftovers
1357             // are non-zero then we have a difference, otherwise we are equal.
1358             for (; i < CE1->getNumOperands(); ++i)
1359               if (!CE1->getOperand(i)->isNullValue()) {
1360                 if (isa<ConstantInt>(CE1->getOperand(i)))
1361                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1362                 else
1363                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1364               }
1365
1366             for (; i < CE2->getNumOperands(); ++i)
1367               if (!CE2->getOperand(i)->isNullValue()) {
1368                 if (isa<ConstantInt>(CE2->getOperand(i)))
1369                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1370                 else
1371                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1372               }
1373             return ICmpInst::ICMP_EQ;
1374           }
1375         }
1376       }
1377     default:
1378       break;
1379     }
1380   }
1381
1382   return ICmpInst::BAD_ICMP_PREDICATE;
1383 }
1384
1385 Constant *llvm::ConstantFoldCompareInstruction(LLVMContext &Context,
1386                                                unsigned short pred, 
1387                                                Constant *C1, Constant *C2) {
1388   const Type *ResultTy;
1389   if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1390     ResultTy = VectorType::get(Type::getInt1Ty(Context), VT->getNumElements());
1391   else
1392     ResultTy = Type::getInt1Ty(Context);
1393
1394   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1395   if (pred == FCmpInst::FCMP_FALSE)
1396     return Constant::getNullValue(ResultTy);
1397
1398   if (pred == FCmpInst::FCMP_TRUE)
1399     return Constant::getAllOnesValue(ResultTy);
1400
1401   // Handle some degenerate cases first
1402   if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1403     return UndefValue::get(ResultTy);
1404
1405   // No compile-time operations on this type yet.
1406   if (C1->getType() == Type::getPPC_FP128Ty(Context))
1407     return 0;
1408
1409   // icmp eq/ne(null,GV) -> false/true
1410   if (C1->isNullValue()) {
1411     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1412       // Don't try to evaluate aliases.  External weak GV can be null.
1413       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1414         if (pred == ICmpInst::ICMP_EQ)
1415           return ConstantInt::getFalse(Context);
1416         else if (pred == ICmpInst::ICMP_NE)
1417           return ConstantInt::getTrue(Context);
1418       }
1419   // icmp eq/ne(GV,null) -> false/true
1420   } else if (C2->isNullValue()) {
1421     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1422       // Don't try to evaluate aliases.  External weak GV can be null.
1423       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1424         if (pred == ICmpInst::ICMP_EQ)
1425           return ConstantInt::getFalse(Context);
1426         else if (pred == ICmpInst::ICMP_NE)
1427           return ConstantInt::getTrue(Context);
1428       }
1429   }
1430
1431   // If the comparison is a comparison between two i1's, simplify it.
1432   if (C1->getType() == Type::getInt1Ty(Context)) {
1433     switch(pred) {
1434     case ICmpInst::ICMP_EQ:
1435       if (isa<ConstantInt>(C2))
1436         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1437       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1438     case ICmpInst::ICMP_NE:
1439       return ConstantExpr::getXor(C1, C2);
1440     default:
1441       break;
1442     }
1443   }
1444
1445   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1446     APInt V1 = cast<ConstantInt>(C1)->getValue();
1447     APInt V2 = cast<ConstantInt>(C2)->getValue();
1448     switch (pred) {
1449     default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
1450     case ICmpInst::ICMP_EQ:
1451       return ConstantInt::get(Type::getInt1Ty(Context), V1 == V2);
1452     case ICmpInst::ICMP_NE: 
1453       return ConstantInt::get(Type::getInt1Ty(Context), V1 != V2);
1454     case ICmpInst::ICMP_SLT:
1455       return ConstantInt::get(Type::getInt1Ty(Context), V1.slt(V2));
1456     case ICmpInst::ICMP_SGT:
1457       return ConstantInt::get(Type::getInt1Ty(Context), V1.sgt(V2));
1458     case ICmpInst::ICMP_SLE:
1459       return ConstantInt::get(Type::getInt1Ty(Context), V1.sle(V2));
1460     case ICmpInst::ICMP_SGE:
1461       return ConstantInt::get(Type::getInt1Ty(Context), V1.sge(V2));
1462     case ICmpInst::ICMP_ULT:
1463       return ConstantInt::get(Type::getInt1Ty(Context), V1.ult(V2));
1464     case ICmpInst::ICMP_UGT:
1465       return ConstantInt::get(Type::getInt1Ty(Context), V1.ugt(V2));
1466     case ICmpInst::ICMP_ULE:
1467       return ConstantInt::get(Type::getInt1Ty(Context), V1.ule(V2));
1468     case ICmpInst::ICMP_UGE:
1469       return ConstantInt::get(Type::getInt1Ty(Context), V1.uge(V2));
1470     }
1471   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1472     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1473     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1474     APFloat::cmpResult R = C1V.compare(C2V);
1475     switch (pred) {
1476     default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
1477     case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse(Context);
1478     case FCmpInst::FCMP_TRUE:  return ConstantInt::getTrue(Context);
1479     case FCmpInst::FCMP_UNO:
1480       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered);
1481     case FCmpInst::FCMP_ORD:
1482       return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpUnordered);
1483     case FCmpInst::FCMP_UEQ:
1484       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1485                                             R==APFloat::cmpEqual);
1486     case FCmpInst::FCMP_OEQ:   
1487       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpEqual);
1488     case FCmpInst::FCMP_UNE:
1489       return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpEqual);
1490     case FCmpInst::FCMP_ONE:   
1491       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
1492                                             R==APFloat::cmpGreaterThan);
1493     case FCmpInst::FCMP_ULT: 
1494       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1495                                             R==APFloat::cmpLessThan);
1496     case FCmpInst::FCMP_OLT:   
1497       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan);
1498     case FCmpInst::FCMP_UGT:
1499       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1500                                             R==APFloat::cmpGreaterThan);
1501     case FCmpInst::FCMP_OGT:
1502       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan);
1503     case FCmpInst::FCMP_ULE:
1504       return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpGreaterThan);
1505     case FCmpInst::FCMP_OLE: 
1506       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
1507                                             R==APFloat::cmpEqual);
1508     case FCmpInst::FCMP_UGE:
1509       return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpLessThan);
1510     case FCmpInst::FCMP_OGE: 
1511       return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan ||
1512                                             R==APFloat::cmpEqual);
1513     }
1514   } else if (isa<VectorType>(C1->getType())) {
1515     SmallVector<Constant*, 16> C1Elts, C2Elts;
1516     C1->getVectorElements(Context, C1Elts);
1517     C2->getVectorElements(Context, C2Elts);
1518
1519     // If we can constant fold the comparison of each element, constant fold
1520     // the whole vector comparison.
1521     SmallVector<Constant*, 4> ResElts;
1522     for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1523       // Compare the elements, producing an i1 result or constant expr.
1524       ResElts.push_back(
1525                     ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
1526     }
1527     return ConstantVector::get(&ResElts[0], ResElts.size());
1528   }
1529
1530   if (C1->getType()->isFloatingPoint()) {
1531     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1532     switch (evaluateFCmpRelation(Context, C1, C2)) {
1533     default: llvm_unreachable("Unknown relation!");
1534     case FCmpInst::FCMP_UNO:
1535     case FCmpInst::FCMP_ORD:
1536     case FCmpInst::FCMP_UEQ:
1537     case FCmpInst::FCMP_UNE:
1538     case FCmpInst::FCMP_ULT:
1539     case FCmpInst::FCMP_UGT:
1540     case FCmpInst::FCMP_ULE:
1541     case FCmpInst::FCMP_UGE:
1542     case FCmpInst::FCMP_TRUE:
1543     case FCmpInst::FCMP_FALSE:
1544     case FCmpInst::BAD_FCMP_PREDICATE:
1545       break; // Couldn't determine anything about these constants.
1546     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1547       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1548                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1549                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1550       break;
1551     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1552       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1553                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1554                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1555       break;
1556     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1557       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1558                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1559                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1560       break;
1561     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1562       // We can only partially decide this relation.
1563       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1564         Result = 0;
1565       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1566         Result = 1;
1567       break;
1568     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1569       // We can only partially decide this relation.
1570       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1571         Result = 0;
1572       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1573         Result = 1;
1574       break;
1575     case ICmpInst::ICMP_NE: // We know that C1 != C2
1576       // We can only partially decide this relation.
1577       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1578         Result = 0;
1579       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1580         Result = 1;
1581       break;
1582     }
1583
1584     // If we evaluated the result, return it now.
1585     if (Result != -1)
1586       return ConstantInt::get(Type::getInt1Ty(Context), Result);
1587
1588   } else {
1589     // Evaluate the relation between the two constants, per the predicate.
1590     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1591     switch (evaluateICmpRelation(Context, C1, C2, CmpInst::isSigned(pred))) {
1592     default: llvm_unreachable("Unknown relational!");
1593     case ICmpInst::BAD_ICMP_PREDICATE:
1594       break;  // Couldn't determine anything about these constants.
1595     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1596       // If we know the constants are equal, we can decide the result of this
1597       // computation precisely.
1598       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1599       break;
1600     case ICmpInst::ICMP_ULT:
1601       switch (pred) {
1602       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1603         Result = 1; break;
1604       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1605         Result = 0; break;
1606       }
1607       break;
1608     case ICmpInst::ICMP_SLT:
1609       switch (pred) {
1610       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1611         Result = 1; break;
1612       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1613         Result = 0; break;
1614       }
1615       break;
1616     case ICmpInst::ICMP_UGT:
1617       switch (pred) {
1618       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1619         Result = 1; break;
1620       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1621         Result = 0; break;
1622       }
1623       break;
1624     case ICmpInst::ICMP_SGT:
1625       switch (pred) {
1626       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1627         Result = 1; break;
1628       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1629         Result = 0; break;
1630       }
1631       break;
1632     case ICmpInst::ICMP_ULE:
1633       if (pred == ICmpInst::ICMP_UGT) Result = 0;
1634       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1635       break;
1636     case ICmpInst::ICMP_SLE:
1637       if (pred == ICmpInst::ICMP_SGT) Result = 0;
1638       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1639       break;
1640     case ICmpInst::ICMP_UGE:
1641       if (pred == ICmpInst::ICMP_ULT) Result = 0;
1642       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1643       break;
1644     case ICmpInst::ICMP_SGE:
1645       if (pred == ICmpInst::ICMP_SLT) Result = 0;
1646       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1647       break;
1648     case ICmpInst::ICMP_NE:
1649       if (pred == ICmpInst::ICMP_EQ) Result = 0;
1650       if (pred == ICmpInst::ICMP_NE) Result = 1;
1651       break;
1652     }
1653
1654     // If we evaluated the result, return it now.
1655     if (Result != -1)
1656       return ConstantInt::get(Type::getInt1Ty(Context), Result);
1657
1658     // If the right hand side is a bitcast, try using its inverse to simplify
1659     // it by moving it to the left hand side.
1660     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1661       if (CE2->getOpcode() == Instruction::BitCast) {
1662         Constant *CE2Op0 = CE2->getOperand(0);
1663         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1664         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1665       }
1666     }
1667
1668     if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1669       // If C2 is a constant expr and C1 isn't, flip them around and fold the
1670       // other way if possible.
1671       switch (pred) {
1672       case ICmpInst::ICMP_EQ:
1673       case ICmpInst::ICMP_NE:
1674         // No change of predicate required.
1675         return ConstantFoldCompareInstruction(Context, pred, C2, C1);
1676
1677       case ICmpInst::ICMP_ULT:
1678       case ICmpInst::ICMP_SLT:
1679       case ICmpInst::ICMP_UGT:
1680       case ICmpInst::ICMP_SGT:
1681       case ICmpInst::ICMP_ULE:
1682       case ICmpInst::ICMP_SLE:
1683       case ICmpInst::ICMP_UGE:
1684       case ICmpInst::ICMP_SGE:
1685         // Change the predicate as necessary to swap the operands.
1686         pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1687         return ConstantFoldCompareInstruction(Context, pred, C2, C1);
1688
1689       default:  // These predicates cannot be flopped around.
1690         break;
1691       }
1692     }
1693   }
1694   return 0;
1695 }
1696
1697 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1698 /// is "inbounds".
1699 static bool isInBoundsIndices(Constant *const *Idxs, size_t NumIdx) {
1700   // No indices means nothing that could be out of bounds.
1701   if (NumIdx == 0) return true;
1702
1703   // If the first index is zero, it's in bounds.
1704   if (Idxs[0]->isNullValue()) return true;
1705
1706   // If the first index is one and all the rest are zero, it's in bounds,
1707   // by the one-past-the-end rule.
1708   if (!cast<ConstantInt>(Idxs[0])->isOne())
1709     return false;
1710   for (unsigned i = 1, e = NumIdx; i != e; ++i)
1711     if (!Idxs[i]->isNullValue())
1712       return false;
1713   return true;
1714 }
1715
1716 Constant *llvm::ConstantFoldGetElementPtr(LLVMContext &Context, 
1717                                           Constant *C,
1718                                           bool inBounds,
1719                                           Constant* const *Idxs,
1720                                           unsigned NumIdx) {
1721   if (NumIdx == 0 ||
1722       (NumIdx == 1 && Idxs[0]->isNullValue()))
1723     return C;
1724
1725   if (isa<UndefValue>(C)) {
1726     const PointerType *Ptr = cast<PointerType>(C->getType());
1727     const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1728                                                        (Value **)Idxs,
1729                                                        (Value **)Idxs+NumIdx);
1730     assert(Ty != 0 && "Invalid indices for GEP!");
1731     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1732   }
1733
1734   Constant *Idx0 = Idxs[0];
1735   if (C->isNullValue()) {
1736     bool isNull = true;
1737     for (unsigned i = 0, e = NumIdx; i != e; ++i)
1738       if (!Idxs[i]->isNullValue()) {
1739         isNull = false;
1740         break;
1741       }
1742     if (isNull) {
1743       const PointerType *Ptr = cast<PointerType>(C->getType());
1744       const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1745                                                          (Value**)Idxs,
1746                                                          (Value**)Idxs+NumIdx);
1747       assert(Ty != 0 && "Invalid indices for GEP!");
1748       return  ConstantPointerNull::get(
1749                             PointerType::get(Ty,Ptr->getAddressSpace()));
1750     }
1751   }
1752
1753   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1754     // Combine Indices - If the source pointer to this getelementptr instruction
1755     // is a getelementptr instruction, combine the indices of the two
1756     // getelementptr instructions into a single instruction.
1757     //
1758     if (CE->getOpcode() == Instruction::GetElementPtr) {
1759       const Type *LastTy = 0;
1760       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1761            I != E; ++I)
1762         LastTy = *I;
1763
1764       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1765         SmallVector<Value*, 16> NewIndices;
1766         NewIndices.reserve(NumIdx + CE->getNumOperands());
1767         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1768           NewIndices.push_back(CE->getOperand(i));
1769
1770         // Add the last index of the source with the first index of the new GEP.
1771         // Make sure to handle the case when they are actually different types.
1772         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1773         // Otherwise it must be an array.
1774         if (!Idx0->isNullValue()) {
1775           const Type *IdxTy = Combined->getType();
1776           if (IdxTy != Idx0->getType()) {
1777             Constant *C1 =
1778               ConstantExpr::getSExtOrBitCast(Idx0, Type::getInt64Ty(Context));
1779             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, 
1780                                                           Type::getInt64Ty(Context));
1781             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1782           } else {
1783             Combined =
1784               ConstantExpr::get(Instruction::Add, Idx0, Combined);
1785           }
1786         }
1787
1788         NewIndices.push_back(Combined);
1789         NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1790         return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
1791           ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
1792                                                  &NewIndices[0],
1793                                                  NewIndices.size()) :
1794           ConstantExpr::getGetElementPtr(CE->getOperand(0),
1795                                          &NewIndices[0],
1796                                          NewIndices.size());
1797       }
1798     }
1799
1800     // Implement folding of:
1801     //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1802     //                        long 0, long 0)
1803     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1804     //
1805     if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
1806       if (const PointerType *SPT =
1807           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1808         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1809           if (const ArrayType *CAT =
1810         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1811             if (CAT->getElementType() == SAT->getElementType())
1812               return inBounds ?
1813                 ConstantExpr::getInBoundsGetElementPtr(
1814                       (Constant*)CE->getOperand(0), Idxs, NumIdx) :
1815                 ConstantExpr::getGetElementPtr(
1816                       (Constant*)CE->getOperand(0), Idxs, NumIdx);
1817     }
1818
1819     // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1820     // Into: inttoptr (i64 0 to i8*)
1821     // This happens with pointers to member functions in C++.
1822     if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1823         isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1824         cast<PointerType>(CE->getType())->getElementType() == Type::getInt8Ty(Context)) {
1825       Constant *Base = CE->getOperand(0);
1826       Constant *Offset = Idxs[0];
1827
1828       // Convert the smaller integer to the larger type.
1829       if (Offset->getType()->getPrimitiveSizeInBits() < 
1830           Base->getType()->getPrimitiveSizeInBits())
1831         Offset = ConstantExpr::getSExt(Offset, Base->getType());
1832       else if (Base->getType()->getPrimitiveSizeInBits() <
1833                Offset->getType()->getPrimitiveSizeInBits())
1834         Base = ConstantExpr::getZExt(Base, Offset->getType());
1835
1836       Base = ConstantExpr::getAdd(Base, Offset);
1837       return ConstantExpr::getIntToPtr(Base, CE->getType());
1838     }
1839   }
1840
1841   // Check to see if any array indices are not within the corresponding
1842   // notional array bounds. If so, try to determine if they can be factored
1843   // out into preceding dimensions.
1844   bool Unknown = false;
1845   SmallVector<Constant *, 8> NewIdxs;
1846   const Type *Ty = C->getType();
1847   const Type *Prev = 0;
1848   for (unsigned i = 0; i != NumIdx;
1849        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
1850     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
1851       if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
1852         if (ATy->getNumElements() <= INT64_MAX &&
1853             ATy->getNumElements() != 0 &&
1854             CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
1855           if (isa<SequentialType>(Prev)) {
1856             // It's out of range, but we can factor it into the prior
1857             // dimension.
1858             NewIdxs.resize(NumIdx);
1859             ConstantInt *Factor = ConstantInt::get(CI->getType(),
1860                                                    ATy->getNumElements());
1861             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
1862
1863             Constant *PrevIdx = Idxs[i-1];
1864             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
1865
1866             // Before adding, extend both operands to i64 to avoid
1867             // overflow trouble.
1868             if (PrevIdx->getType() != Type::getInt64Ty(Context))
1869               PrevIdx = ConstantExpr::getSExt(PrevIdx,
1870                                               Type::getInt64Ty(Context));
1871             if (Div->getType() != Type::getInt64Ty(Context))
1872               Div = ConstantExpr::getSExt(Div,
1873                                           Type::getInt64Ty(Context));
1874
1875             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
1876           } else {
1877             // It's out of range, but the prior dimension is a struct
1878             // so we can't do anything about it.
1879             Unknown = true;
1880           }
1881         }
1882     } else {
1883       // We don't know if it's in range or not.
1884       Unknown = true;
1885     }
1886   }
1887
1888   // If we did any factoring, start over with the adjusted indices.
1889   if (!NewIdxs.empty()) {
1890     for (unsigned i = 0; i != NumIdx; ++i)
1891       if (!NewIdxs[i]) NewIdxs[i] = Idxs[i];
1892     return inBounds ?
1893       ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
1894                                              NewIdxs.size()) :
1895       ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
1896   }
1897
1898   // If all indices are known integers and normalized, we can do a simple
1899   // check for the "inbounds" property.
1900   if (!Unknown && !inBounds &&
1901       isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
1902     return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);
1903
1904   return 0;
1905 }